@itphx/synth-backend 0.9.0 → 0.10.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.
Files changed (55) hide show
  1. package/dist/app/bootstrap.d.ts +11 -0
  2. package/dist/app/bootstrap.js +19 -0
  3. package/dist/app/deps.d.ts +106 -0
  4. package/dist/app/deps.js +617 -0
  5. package/dist/app/listen.d.ts +29 -0
  6. package/dist/app/listen.js +298 -0
  7. package/dist/app/mount-routes.d.ts +18 -0
  8. package/dist/app/mount-routes.js +466 -0
  9. package/dist/app/sse-events.d.ts +15 -0
  10. package/dist/app/sse-events.js +83 -0
  11. package/dist/app.d.ts +29 -3
  12. package/dist/app.js +110 -900
  13. package/dist/auth/guards.d.ts +20 -0
  14. package/dist/auth/guards.js +65 -0
  15. package/dist/auth/middleware.d.ts +20 -1
  16. package/dist/auth/middleware.js +53 -1
  17. package/dist/auth/oidc.d.ts +15 -0
  18. package/dist/auth/oidc.js +41 -3
  19. package/dist/auth/service-scope.d.ts +14 -0
  20. package/dist/auth/service-scope.js +40 -0
  21. package/dist/events/hub.d.ts +9 -0
  22. package/dist/events/hub.js +29 -0
  23. package/dist/lib/cors.d.ts +23 -0
  24. package/dist/lib/cors.js +24 -0
  25. package/dist/lib/i18n.js +64 -0
  26. package/dist/main.js +10 -1
  27. package/dist/middleware/rate-limiter.d.ts +4 -1
  28. package/dist/middleware/rate-limiter.js +4 -2
  29. package/dist/routes/audit.d.ts +1 -1
  30. package/dist/routes/audit.js +2 -2
  31. package/dist/routes/auth.js +35 -5
  32. package/dist/routes/gateway-patterns.d.ts +1 -1
  33. package/dist/routes/gateway-patterns.js +1 -1
  34. package/dist/routes/llm.js +7 -4
  35. package/dist/routes/mcp-registry.d.ts +3 -3
  36. package/dist/routes/mcp-registry.js +40 -17
  37. package/dist/routes/mcp.d.ts +1 -1
  38. package/dist/routes/mcp.js +1 -1
  39. package/dist/routes/projects.d.ts +7 -4
  40. package/dist/routes/projects.js +17 -7
  41. package/dist/routes/providers.js +1 -0
  42. package/dist/routes/sessions.d.ts +7 -1
  43. package/dist/routes/sessions.js +119 -8
  44. package/dist/routes/users.js +17 -4
  45. package/package.json +4 -4
  46. package/dist/agents/definitions/admin.json +0 -24
  47. package/dist/agents/definitions/analyst.json +0 -20
  48. package/dist/agents/definitions/assistant.json +0 -25
  49. package/dist/agents/definitions/auditor.json +0 -19
  50. package/dist/agents/definitions/developer.json +0 -23
  51. package/dist/agents/definitions/devops.json +0 -23
  52. package/dist/agents/definitions/explore.json +0 -15
  53. package/dist/agents/definitions/general.json +0 -15
  54. package/dist/agents/definitions/pm.json +0 -20
  55. package/dist/agents/definitions/qa.json +0 -22
@@ -2,8 +2,10 @@ import { createMiddleware } from 'hono/factory';
2
2
  /**
3
3
  * In-memory rate limiter.
4
4
  * Ключ — Authorization header (уникален для каждого пользователя/ключа).
5
+ * `message` — опциональный резолвер локализованного текста (i18n); по умолчанию —
6
+ * общий русский текст (обратная совместимость).
5
7
  */
6
- export function createRateLimiter(maxRequests = 20, windowMs = 60_000) {
8
+ export function createRateLimiter(maxRequests = 20, windowMs = 60_000, message) {
7
9
  const hits = new Map();
8
10
  setInterval(() => {
9
11
  const now = Date.now();
@@ -24,7 +26,7 @@ export function createRateLimiter(maxRequests = 20, windowMs = 60_000) {
24
26
  }
25
27
  entry.count += 1;
26
28
  if (entry.count > maxRequests) {
27
- return c.json({ error: { code: 'RATE_LIMITED', message: 'Превышен лимит запросов' } }, 429);
29
+ return c.json({ error: { code: 'RATE_LIMITED', message: message ? message(c) : 'Превышен лимит запросов' } }, 429);
28
30
  }
29
31
  await next();
30
32
  });
@@ -10,7 +10,7 @@ export interface AuditRoutesDeps {
10
10
  logger: AuditLogger;
11
11
  }
12
12
  /**
13
- * GET /api/v2/audit — просмотр аудита LLM Gateway (AD-036).
13
+ * GET /api/v2/audit — просмотр аудита LLM Gateway (ADR-036).
14
14
  * RBAC: только ADMIN/AUDITOR.
15
15
  * Фильтры: userId, sessionId, since/until (ISO), limit (дефолт 100, макс 500).
16
16
  */
@@ -9,7 +9,7 @@ function toInt(value, fallback) {
9
9
  return Number.isFinite(n) ? n : fallback;
10
10
  }
11
11
  /**
12
- * GET /api/v2/audit — просмотр аудита LLM Gateway (AD-036).
12
+ * GET /api/v2/audit — просмотр аудита LLM Gateway (ADR-036).
13
13
  * RBAC: только ADMIN/AUDITOR.
14
14
  * Фильтры: userId, sessionId, since/until (ISO), limit (дефолт 100, макс 500).
15
15
  */
@@ -28,7 +28,7 @@ export function createAuditRoutes(kit, deps) {
28
28
  return c.json({ entries, total });
29
29
  });
30
30
  /**
31
- * POST /api/v2/audit/revealed — логирование раскрытия плейсхолдера (AD-036).
31
+ * POST /api/v2/audit/revealed — логирование раскрытия плейсхолдера (ADR-036).
32
32
  * RBAC: любой авторизованный (клик по бейджу SecretPlaceholder делает
33
33
  * пользователь сессии), userId фиксируется из токена.
34
34
  * Тело: { sessionId, placeholder } (placeholder вида ⟦SYNTH_SECRET_N⟧).
@@ -5,7 +5,7 @@ import { getCookie, setCookie, deleteCookie } from 'hono/cookie';
5
5
  import { t } from '../lib/i18n.js';
6
6
  import { getDefaultLang, setDefaultLang } from '../lib/i18n-config.js';
7
7
  import { readFile, writeFile, unlink } from 'node:fs/promises';
8
- import { join } from 'node:path';
8
+ import { join, resolve, sep } from 'node:path';
9
9
  const OIDC_STATE_COOKIE = 'oidc_state';
10
10
  // Встроенные умолчания оформления (совпадают с тем, что использует UI
11
11
  // по умолчанию: packages/ui/src/lib/defaults.ts + uiScale.ts).
@@ -18,6 +18,24 @@ const BUILT_IN_DEFAULTS = {
18
18
  export function createAuthRoutes(kit, config, profiles, dataDir, defaultsStore) {
19
19
  const app = new Hono();
20
20
  const avatarsDir = dataDir ? join(dataDir, 'auth', 'avatars') : null;
21
+ // Корень каталога аватаров (абсолютный) — для containment-проверки.
22
+ const avatarsRoot = avatarsDir ? resolve(avatarsDir) : null;
23
+ /**
24
+ * Безопасный абсолютный путь к файлу аватара по `username`.
25
+ * Отклоняет пустое имя, разделители пути (`/`, `\`) и `.`/`..` (traversal),
26
+ * а также результат вне каталога аватаров (defense-in-depth). `null` — отказ.
27
+ */
28
+ const resolveAvatarPath = (username) => {
29
+ if (!avatarsRoot)
30
+ return null;
31
+ const name = username.trim();
32
+ if (!name || name === '.' || name === '..')
33
+ return null;
34
+ if (/[/\\\0]/.test(name))
35
+ return null;
36
+ const full = resolve(avatarsRoot, `${name}.png`);
37
+ return full.startsWith(avatarsRoot + sep) ? full : null;
38
+ };
21
39
  // Сохранённые умолчания перекрывают встроенные; uiScaleMobile/uiScaleDesktop: null — умолчание не задано.
22
40
  const resolveDefaults = async () => {
23
41
  const stored = defaultsStore ? await defaultsStore.loadDefaults() : {};
@@ -237,7 +255,7 @@ export function createAuthRoutes(kit, config, profiles, dataDir, defaultsStore)
237
255
  preferred_language: user.preferredLanguage,
238
256
  team_role: profile?.teamRoles?.[0] ?? user.teamRole,
239
257
  notes: profile?.notes ?? user.notes,
240
- interview_completed: user.interviewCompleted,
258
+ interview_completed: profile?.interviewCompleted ?? user.interviewCompleted,
241
259
  display_name: profile?.displayName ?? null,
242
260
  is_active: profile?.isActive ?? true,
243
261
  created_at: profile?.createdAt ?? user.createdAt,
@@ -272,6 +290,11 @@ export function createAuthRoutes(kit, config, profiles, dataDir, defaultsStore)
272
290
  profile.teamRoles = [body.team_role];
273
291
  if (body.display_name)
274
292
  profile.displayName = body.display_name;
293
+ if (body.interview_completed !== undefined) {
294
+ // Отдельное поле статуса интервью — персистим вместе с временем.
295
+ profile.interviewCompleted = body.interview_completed;
296
+ profile.interviewCompletedAt = body.interview_completed ? new Date().toISOString() : undefined;
297
+ }
275
298
  if (body.preferences !== undefined) {
276
299
  profile.preferences = { ...(profile.preferences || {}), ...body.preferences };
277
300
  }
@@ -291,6 +314,7 @@ export function createAuthRoutes(kit, config, profiles, dataDir, defaultsStore)
291
314
  display_name: profile.displayName,
292
315
  notes: profile.notes,
293
316
  team_role: profile.teamRoles?.[0],
317
+ interview_completed: profile.interviewCompleted,
294
318
  preferences: profile.preferences,
295
319
  },
296
320
  });
@@ -381,7 +405,10 @@ export function createAuthRoutes(kit, config, profiles, dataDir, defaultsStore)
381
405
  return c.json({ error: { code: 'UNAUTHORIZED' } }, 401);
382
406
  if (!avatarsDir)
383
407
  return c.body(null, 404);
384
- const avatarPath = join(avatarsDir, `${user.username}.png`);
408
+ const avatarPath = resolveAvatarPath(user.username);
409
+ if (!avatarPath) {
410
+ return c.json({ error: { code: 'VALIDATION_ERROR', message: t('errors.validation.invalidUsername', undefined, c) } }, 400);
411
+ }
385
412
  try {
386
413
  const data = await readFile(avatarPath);
387
414
  return new Response(data, {
@@ -399,11 +426,15 @@ export function createAuthRoutes(kit, config, profiles, dataDir, defaultsStore)
399
426
  return c.json({ error: { code: 'UNAUTHORIZED' } }, 401);
400
427
  if (!avatarsDir)
401
428
  return c.json({ error: { code: 'INTERNAL_ERROR' } }, 500);
429
+ const avatarPath = resolveAvatarPath(user.username);
430
+ if (!avatarPath) {
431
+ return c.json({ error: { code: 'VALIDATION_ERROR', message: t('errors.validation.invalidUsername', undefined, c) } }, 400);
432
+ }
402
433
  try {
403
434
  const buffer = await c.req.arrayBuffer();
404
435
  if (buffer.byteLength === 0) {
405
436
  // Удаление аватара
406
- await unlink(join(avatarsDir, `${user.username}.png`)).catch(() => { });
437
+ await unlink(avatarPath).catch(() => { });
407
438
  if (profiles) {
408
439
  const profile = await profiles.getOrCreateProfile({ username: user.username, roles: user.roles });
409
440
  const prefs = { ...(profile.preferences || {}), avatar: '' };
@@ -412,7 +443,6 @@ export function createAuthRoutes(kit, config, profiles, dataDir, defaultsStore)
412
443
  }
413
444
  return c.json({ status: 'ok' });
414
445
  }
415
- const avatarPath = join(avatarsDir, `${user.username}.png`);
416
446
  await writeFile(avatarPath, Buffer.from(buffer));
417
447
  if (profiles) {
418
448
  const profile = await profiles.getOrCreateProfile({ username: user.username, roles: user.roles });
@@ -2,7 +2,7 @@ import { Hono } from 'hono';
2
2
  import type { AuthKit } from '../auth/middleware.js';
3
3
  import type { SecretPatternStore } from '@itphx/synth-core';
4
4
  /**
5
- * LLM Gateway (AD-036) — управление regex-паттернами детекции секретов.
5
+ * LLM Gateway (ADR-036) — управление regex-паттернами детекции секретов.
6
6
  * Схема «системный + override»: пользовательский список полностью заменяет дефолтный,
7
7
  * DELETE сбрасывает к встроенным паттернам. Только ADMIN.
8
8
  */
@@ -16,7 +16,7 @@ function isValidPattern(p) {
16
16
  }
17
17
  }
18
18
  /**
19
- * LLM Gateway (AD-036) — управление regex-паттернами детекции секретов.
19
+ * LLM Gateway (ADR-036) — управление regex-паттернами детекции секретов.
20
20
  * Схема «системный + override»: пользовательский список полностью заменяет дефолтный,
21
21
  * DELETE сбрасывает к встроенным паттернам. Только ADMIN.
22
22
  */
@@ -1,10 +1,11 @@
1
1
  import { Hono } from 'hono';
2
2
  import { z } from 'zod';
3
+ import { scopeGuard } from '../auth/service-scope.js';
3
4
  import { ContextLengthExceededError, deobfuscateSecrets, GatewayProvider, ProviderError, ProviderFactory, RateLimitError, } from '@itphx/synth-core';
4
5
  /**
5
6
  * LLM Proxy endpoint (гибридный режим, Часть 5).
6
7
  * OpenAI-совместимый POST /api/v2/llm/chat/completions, через который локальный
7
- * core гоняет LLM-запросы централизованно — с применением LLM Gateway (AD-036):
8
+ * core гоняет LLM-запросы централизованно — с применением LLM Gateway (ADR-036):
8
9
  * обфускация/блокировка секретов, rate limit, аудит, полный payload-лог.
9
10
  */
10
11
  /**
@@ -29,7 +30,7 @@ const chatCompletionsSchema = z.object({
29
30
  max_tokens: z.number().int().positive().optional(),
30
31
  top_p: z.number().optional(),
31
32
  stream: z.boolean().optional(),
32
- // AD-070: remote-зеркала (RemoteProvider) просят usage в стриме. Внутренний
33
+ // ADR-070: remote-зеркала (RemoteProvider) просят usage в стриме. Внутренний
33
34
  // OpenAIProvider всегда шлёт stream_options.include_usage, но поле принимаем
34
35
  // явно, чтобы Zod его не срезал (контракт запроса).
35
36
  stream_options: z.object({ include_usage: z.boolean().optional() }).optional(),
@@ -99,7 +100,8 @@ function toLlmMessages(raw) {
99
100
  }
100
101
  export function createLlmRoutes(kit, deps) {
101
102
  const app = new Hono();
102
- const middlewares = deps.rateLimiter ? [deps.rateLimiter] : [];
103
+ // ADR-052: `llm:chat` — scope service-key; обычные креды scope не ограничивают.
104
+ const middlewares = [scopeGuard('llm:chat'), ...(deps.rateLimiter ? [deps.rateLimiter] : [])];
103
105
  // POST /api/v2/llm/chat/completions — OpenAI-совместимый LLM Proxy
104
106
  app.post('/chat/completions', kit.requireAuth, ...middlewares, async (c) => {
105
107
  const user = (await kit.getCurrentUser(c));
@@ -164,6 +166,7 @@ export function createLlmRoutes(kit, deps) {
164
166
  model: modelConfig.name,
165
167
  timeout: providerConfig.timeout ?? 120,
166
168
  maxTokens: body.max_tokens,
169
+ numCtx: providerConfig.numCtx,
167
170
  }, body.temperature, body.top_p);
168
171
  }
169
172
  catch (e) {
@@ -174,7 +177,7 @@ export function createLlmRoutes(kit, deps) {
174
177
  },
175
178
  }, 502);
176
179
  }
177
- // 3. AD-036: оборачиваем провайдер в GatewayProvider.
180
+ // 3. ADR-036: оборачиваем провайдер в GatewayProvider.
178
181
  // У локального core нет карты обфускации, поэтому для прокси держим
179
182
  // transient-карту на время запроса: getMap/saveMap читают/пишут её, а после
180
183
  // ответа деобфусцируем контент по той же карте (иначе клиент увидел бы
@@ -3,12 +3,12 @@ import type { AuthKit } from '../auth/middleware.js';
3
3
  import type { SessionManager, McpManager, McpRegistryStore } from '@itphx/synth-core';
4
4
  import type { McpNetworkPolicy } from '@itphx/synth-shared';
5
5
  export interface McpRoutesOptions {
6
- /** AD-071 §2.5: единый реестр MCP-серверов (источник истины для `/servers` и `/registry`). */
6
+ /** ADR-071 §2.5: единый реестр MCP-серверов (источник истины для `/servers` и `/registry`). */
7
7
  registry: McpRegistryStore;
8
- /** AD-071 §2.3.1: политика сетевого доступа HTTP-серверов. */
8
+ /** ADR-071 §2.3.1: политика сетевого доступа HTTP-серверов. */
9
9
  networkPolicy?: McpNetworkPolicy;
10
10
  /**
11
- * AD-071 §2.3.1: динамический источник политики (runtime-настройка из админки).
11
+ * ADR-071 §2.3.1: динамический источник политики (runtime-настройка из админки).
12
12
  * Приоритетнее статической `networkPolicy`; читается на каждый запрос.
13
13
  */
14
14
  getNetworkPolicy?: () => McpNetworkPolicy | undefined;
@@ -1,9 +1,10 @@
1
1
  import { Hono } from 'hono';
2
2
  import { z } from 'zod';
3
- import { evaluateMcpNetworkAccess } from '@itphx/synth-core';
4
- import { sessionMcpScopeSchema } from '@itphx/synth-shared';
3
+ import { evaluateMcpNetworkAccess, getServiceCredential } from '@itphx/synth-core';
4
+ import { sessionMcpScopeSchema, hasServiceScope } from '@itphx/synth-shared';
5
5
  import { mcpServerConfigSchema } from '@itphx/synth-shared/config';
6
- // Backend-only MCP-роуты (AD-071 §2.5): legacy `/servers*`, `/session/:id` и
6
+ import { requireAdminOrScope, requireScopeForServiceKey } from '../auth/guards.js';
7
+ // Backend-only MCP-роуты (ADR-071 §2.5): legacy `/servers*`, `/session/:id` и
7
8
  // единый реестр `/registry*`. Probe (`POST /probe`) — общая логика core,
8
9
  // монтируется в `routes/mcp.ts` ПЕРЕД этим роутером.
9
10
  const addServerSchema = z.object({
@@ -11,7 +12,7 @@ const addServerSchema = z.object({
11
12
  config: mcpServerConfigSchema,
12
13
  });
13
14
  const updateServerSchema = mcpServerConfigSchema;
14
- // AD-071 §2.5: единый реестр MCP-серверов.
15
+ // ADR-071 §2.5: единый реестр MCP-серверов.
15
16
  const registryAddSchema = z.object({
16
17
  name: z.string().min(1).max(200),
17
18
  config: mcpServerConfigSchema,
@@ -46,8 +47,17 @@ export function createMcpRegistryRoutes(kit, mcpManager, sessionManager, options
46
47
  };
47
48
  const isConnected = (name) => mcpManager?.getConfiguredServers().find((s) => s.name === name)?.connected ?? false;
48
49
  const currentUser = (c) => c.get('user') ?? null;
50
+ /**
51
+ * ADR-052/O1: запрос от installer-service-key (scope `addons:install`).
52
+ * Даёт scoped-ключу без роли ADMIN создавать **instance**-записи реестра
53
+ * (общие для инстанса, а не персональные) и обновлять созданные им записи.
54
+ */
55
+ const isInstallerKey = (c) => {
56
+ const cred = getServiceCredential(c);
57
+ return !!cred && hasServiceScope(cred.scopes, 'addons:install');
58
+ };
49
59
  const checkNetwork = async (config, origin) => {
50
- // AD-071 §2.3.1: политика — для пользовательских HTTP-серверов; instance
60
+ // ADR-071 §2.3.1: политика — для пользовательских HTTP-серверов; instance
51
61
  // (в т.ч. приватные сети инстанса) доверенные.
52
62
  if (origin !== 'user' || config.type === 'stdio' || !config.url)
53
63
  return null;
@@ -60,7 +70,7 @@ export function createMcpRegistryRoutes(kit, mcpManager, sessionManager, options
60
70
  return { code: 'NETWORK_POLICY_VIOLATION', message: result.reason ?? 'Адрес запрещён сетевой политикой' };
61
71
  };
62
72
  // ---------------------------------------------------------------------------
63
- // Legacy `/servers*` — тонкие адаптеры над единым реестром (AD-071 §2.5).
73
+ // Legacy `/servers*` — тонкие адаптеры над единым реестром (ADR-071 §2.5).
64
74
  // Второго хранилища (config.yaml) больше нет: источник истины — McpRegistryStore.
65
75
  // ---------------------------------------------------------------------------
66
76
  // --- Список настроенных серверов ---
@@ -101,8 +111,8 @@ export function createMcpRegistryRoutes(kit, mcpManager, sessionManager, options
101
111
  }
102
112
  return c.json({ name: entry.name, config: entry.config, connected: isConnected(entry.name) });
103
113
  });
104
- // --- Обновить сервер (ADMIN) ---
105
- app.put('/servers/:name', kit.requireAdmin, async (c) => {
114
+ // --- Обновить сервер (ADMIN или scope `addons:install`) ---
115
+ app.put('/servers/:name', requireAdminOrScope('addons:install'), async (c) => {
106
116
  const name = c.req.param('name');
107
117
  const entry = await registry.getByName(name);
108
118
  if (!entry) {
@@ -121,8 +131,8 @@ export function createMcpRegistryRoutes(kit, mcpManager, sessionManager, options
121
131
  await syncManagerConfig();
122
132
  return c.json({ name, config: parsed.data, connected: isConnected(name) });
123
133
  });
124
- // --- Удалить сервер (ADMIN) ---
125
- app.delete('/servers/:name', kit.requireAdmin, async (c) => {
134
+ // --- Удалить сервер (ADMIN или scope `addons:install`) ---
135
+ app.delete('/servers/:name', requireAdminOrScope('addons:install'), async (c) => {
126
136
  const name = c.req.param('name');
127
137
  const entry = await registry.getByName(name);
128
138
  if (!entry) {
@@ -135,8 +145,8 @@ export function createMcpRegistryRoutes(kit, mcpManager, sessionManager, options
135
145
  await syncManagerConfig();
136
146
  return c.json({ success: true });
137
147
  });
138
- // --- Проверить подключение (ADMIN) ---
139
- app.post('/servers/:name/test', kit.requireAdmin, async (c) => {
148
+ // --- Проверить подключение (ADMIN или scope `addons:install`) ---
149
+ app.post('/servers/:name/test', requireAdminOrScope('addons:install'), async (c) => {
140
150
  const name = c.req.param('name');
141
151
  // Принимаем опциональный конфиг в теле — для теста до сохранения.
142
152
  let config;
@@ -250,14 +260,17 @@ export function createMcpRegistryRoutes(kit, mcpManager, sessionManager, options
250
260
  });
251
261
  });
252
262
  }
253
- // --- Единый реестр MCP-серверов (AD-071 §2.5) ---
263
+ // --- Единый реестр MCP-серверов (ADR-071 §2.5) ---
254
264
  // Список записей реестра (auth).
255
265
  app.get('/registry', kit.requireAuth, async (c) => {
256
266
  const entries = await registry.list();
257
267
  return c.json({ entries });
258
268
  });
259
269
  // Добавить запись (auth): HTTP — любой пользователь, stdio — только ADMIN.
260
- app.post('/registry', kit.requireAuth, async (c) => {
270
+ // ADR-052/O1: service-key должен нести scope `addons:install` (интерактив без
271
+ // изменений — HTTP добавляет любой, stdio-проверка ниже). Installer-ключ со
272
+ // scope создаёт instance-записи (общие для инстанса) без роли ADMIN.
273
+ app.post('/registry', kit.requireAuth, requireScopeForServiceKey('addons:install'), async (c) => {
261
274
  const body = await c.req.json().catch(() => null);
262
275
  const parsed = registryAddSchema.safeParse(body);
263
276
  if (!parsed.success) {
@@ -265,9 +278,13 @@ export function createMcpRegistryRoutes(kit, mcpManager, sessionManager, options
265
278
  }
266
279
  const { name, config, enabled, enabledByDefault, origin } = parsed.data;
267
280
  const admin = kit.isAdmin(c);
281
+ // ADR-052/O1: installer-ключ (scope `addons:install`) создаёт instance-записи
282
+ // даже без роли ADMIN — это общие записи инстанса (а не персональные).
283
+ const isInstaller = isInstallerKey(c);
268
284
  let entryOrigin;
269
285
  let trust;
270
286
  if (config.type === 'stdio') {
287
+ // stdio — только ADMIN (scope НЕ ослабляет проверку).
271
288
  if (!admin) {
272
289
  return c.json({
273
290
  error: { code: 'FORBIDDEN', message: 'stdio-серверы может добавлять только ADMIN' },
@@ -277,7 +294,8 @@ export function createMcpRegistryRoutes(kit, mcpManager, sessionManager, options
277
294
  trust = 'builtin';
278
295
  }
279
296
  else {
280
- entryOrigin = admin && origin === 'instance' ? 'instance' : 'user';
297
+ const wantsInstance = origin === 'instance' || isInstaller;
298
+ entryOrigin = (admin || isInstaller) && wantsInstance ? 'instance' : 'user';
281
299
  trust = entryOrigin === 'instance' ? 'builtin' : 'community';
282
300
  }
283
301
  const networkError = await checkNetwork(config, entryOrigin);
@@ -301,7 +319,7 @@ export function createMcpRegistryRoutes(kit, mcpManager, sessionManager, options
301
319
  await syncManagerConfig();
302
320
  return c.json(entry, 201);
303
321
  });
304
- // Обновить запись (автор или ADMIN).
322
+ // Обновить запись (автор, ADMIN или installer-ключ со scope `addons:install`).
305
323
  app.put('/registry/:id', kit.requireAuth, async (c) => {
306
324
  const id = c.req.param('id');
307
325
  const existing = await registry.get(id);
@@ -310,7 +328,12 @@ export function createMcpRegistryRoutes(kit, mcpManager, sessionManager, options
310
328
  }
311
329
  const admin = kit.isAdmin(c);
312
330
  const user = currentUser(c);
313
- if (!admin && existing.author?.userId !== user?.id) {
331
+ // Автор записи (для service-key автор — `service:<keyId>`), ADMIN **или**
332
+ // installer-ключ со scope `addons:install`: аддон может обновлять созданные
333
+ // им instance-записи; scope-ветка переживает ротацию/пересоздание ключа
334
+ // (id меняется, author-check бы не сработал).
335
+ const isAuthor = existing.author?.userId === user?.id;
336
+ if (!admin && !isAuthor && !isInstallerKey(c)) {
314
337
  return c.json({ error: { code: 'FORBIDDEN', message: 'Обновлять запись может автор или ADMIN' } }, 403);
315
338
  }
316
339
  const body = await c.req.json().catch(() => null);
@@ -5,7 +5,7 @@ import type { McpRoutesOptions } from './mcp-registry.js';
5
5
  export type { McpRoutesOptions } from './mcp-registry.js';
6
6
  /**
7
7
  * Backend MCP: probe (`POST /probe`) — общая логика core-фабрики; legacy
8
- * `/servers*`, `/session/:id` и единый реестр `/registry*` (AD-071) —
8
+ * `/servers*`, `/session/:id` и единый реестр `/registry*` (ADR-071) —
9
9
  * backend-only (см. `mcp-registry.ts`). Порядок монтирования: core probe
10
10
  * первым, затем backend-only.
11
11
  */
@@ -3,7 +3,7 @@ import { createMcpRoutes as createCoreMcpRoutes } from '@itphx/synth-core';
3
3
  import { createMcpRegistryRoutes } from './mcp-registry.js';
4
4
  /**
5
5
  * Backend MCP: probe (`POST /probe`) — общая логика core-фабрики; legacy
6
- * `/servers*`, `/session/:id` и единый реестр `/registry*` (AD-071) —
6
+ * `/servers*`, `/session/:id` и единый реестр `/registry*` (ADR-071) —
7
7
  * backend-only (см. `mcp-registry.ts`). Порядок монтирования: core probe
8
8
  * первым, затем backend-only.
9
9
  */
@@ -3,7 +3,7 @@ import type { AuthKit } from '../auth/middleware.js';
3
3
  import type { ProjectStore, SessionManager, McpManager, SkillService, RuntimeSettingsStore, McpRegistryStore } from '@itphx/synth-core';
4
4
  import type { Project } from '@itphx/synth-shared';
5
5
  /**
6
- * AD-076 §T4: RBAC-хелперы проекта (owner/EDITOR/LEAD/ADMIN). Вынесены фабрикой,
6
+ * ADR-076 §T4: RBAC-хелперы проекта (owner/EDITOR/LEAD/ADMIN). Вынесены фабрикой,
7
7
  * чтобы их переиспользовали git-роуты core-фабрики (`authorizeProject`), а логика
8
8
  * ролей не дублировалась.
9
9
  */
@@ -14,15 +14,18 @@ export declare function createProjectAccess(kit: AuthKit): {
14
14
  canEditProjectContent: (c: {
15
15
  get(key: "user"): unknown;
16
16
  }, project: Project, userId: string) => boolean;
17
+ canReadProject: (c: {
18
+ get(key: "user"): unknown;
19
+ }, project: Project, userId: string) => boolean;
17
20
  };
18
21
  /**
19
22
  * Backend-обёртка над core-фабрикой проектов: общая логика — в core, здесь только
20
23
  * managed-специфика — RBAC (`createProjectAccess`), i18n-сообщения, авто-имя
21
- * workspace (AD-075, политика `deny` вне root), проектный MCP-скоуп (AD-071 §2.4)
24
+ * workspace (ADR-075, политика `deny` вне root), проектный MCP-скоуп (ADR-071 §2.4)
22
25
  * и статистика сессий. Полная реализация — `@itphx/synth-core`.
23
26
  */
24
27
  export declare function createProjectRoutes(kit: AuthKit, store: ProjectStore, sessionManager: SessionManager, workspacesRoot: string,
25
- /** AD-071 §2.4: источник известных MCP-серверов для проектного скоупа. */
28
+ /** ADR-071 §2.4: источник известных MCP-серверов для проектного скоупа. */
26
29
  mcpManager?: McpManager,
27
- /** AD-046 §4.5: сид скиллов нового проекта (системные дефолты). */
30
+ /** ADR-046 §4.5: сид скиллов нового проекта (системные дефолты). */
28
31
  skillService?: SkillService, settingsStore?: RuntimeSettingsStore, mcpRegistryStore?: McpRegistryStore): Hono;
@@ -2,12 +2,12 @@ import { createProjectRoutes as createCoreProjectRoutes, resolveProjectSkillSeed
2
2
  import { ProjectRole } from '@itphx/synth-shared';
3
3
  import { t } from '../lib/i18n.js';
4
4
  /**
5
- * AD-076 §T4: RBAC-хелперы проекта (owner/EDITOR/LEAD/ADMIN). Вынесены фабрикой,
5
+ * ADR-076 §T4: RBAC-хелперы проекта (owner/EDITOR/LEAD/ADMIN). Вынесены фабрикой,
6
6
  * чтобы их переиспользовали git-роуты core-фабрики (`authorizeProject`), а логика
7
7
  * ролей не дублировалась.
8
8
  */
9
9
  export function createProjectAccess(kit) {
10
- /** AD-071 §2.4: owner проекта или глобальные LEAD/ADMIN (через AuthKit). */
10
+ /** ADR-071 §2.4: owner проекта или глобальные LEAD/ADMIN (через AuthKit). */
11
11
  const canManageProject = (c, project, userId) => (typeof kit.isAdmin === 'function' && kit.isAdmin(c))
12
12
  || (typeof kit.hasRole === 'function' && kit.hasRole(c, 'LEAD'))
13
13
  || project.ownerId === userId
@@ -15,23 +15,33 @@ export function createProjectAccess(kit) {
15
15
  /** D5: owner / EDITOR / глобальные LEAD/ADMIN — редактирование контента проекта. */
16
16
  const canEditProjectContent = (c, project, userId) => canManageProject(c, project, userId)
17
17
  || project.members?.[userId] === ProjectRole.EDITOR;
18
- return { canManageProject, canEditProjectContent };
18
+ /**
19
+ * ADR-089: чтение проекта по id — owner / любой участник (любая роль, в т.ч.
20
+ * VIEWER) / глобальные LEAD/ADMIN. Не расширяет права на редактирование.
21
+ */
22
+ const canReadProject = (c, project, userId) => canManageProject(c, project, userId)
23
+ || userId in (project.members ?? {});
24
+ return { canManageProject, canEditProjectContent, canReadProject };
19
25
  }
20
26
  /**
21
27
  * Backend-обёртка над core-фабрикой проектов: общая логика — в core, здесь только
22
28
  * managed-специфика — RBAC (`createProjectAccess`), i18n-сообщения, авто-имя
23
- * workspace (AD-075, политика `deny` вне root), проектный MCP-скоуп (AD-071 §2.4)
29
+ * workspace (ADR-075, политика `deny` вне root), проектный MCP-скоуп (ADR-071 §2.4)
24
30
  * и статистика сессий. Полная реализация — `@itphx/synth-core`.
25
31
  */
26
32
  export function createProjectRoutes(kit, store, sessionManager, workspacesRoot,
27
- /** AD-071 §2.4: источник известных MCP-серверов для проектного скоупа. */
33
+ /** ADR-071 §2.4: источник известных MCP-серверов для проектного скоупа. */
28
34
  mcpManager,
29
- /** AD-046 §4.5: сид скиллов нового проекта (системные дефолты). */
35
+ /** ADR-046 §4.5: сид скиллов нового проекта (системные дефолты). */
30
36
  skillService, settingsStore, mcpRegistryStore) {
31
- const { canManageProject, canEditProjectContent } = createProjectAccess(kit);
37
+ const { canManageProject, canEditProjectContent, canReadProject } = createProjectAccess(kit);
32
38
  return createCoreProjectRoutes({ requireAuth: kit.requireAuth }, store, undefined, {
33
39
  canManage: canManageProject,
34
40
  canEditContent: canEditProjectContent,
41
+ canRead: canReadProject,
42
+ // ADR-089: ADMIN/LEAD — сквозная видимость всех проектов (защита от мок-AuthKit).
43
+ resolveElevated: (c) => (typeof kit.isAdmin === 'function' && kit.isAdmin(c))
44
+ || (typeof kit.hasRole === 'function' && kit.hasRole(c, 'LEAD')),
35
45
  getCurrentUserId: async (c) => (await kit.getCurrentUser(c))?.id ?? '',
36
46
  messages: {
37
47
  nameRequired: (c) => t('errors.validation.nameRequired', undefined, c),
@@ -108,6 +108,7 @@ export function createProviderRoutes(kit, store, providerCache) {
108
108
  providerNotFound: (c) => t('errors.notFound.provider', undefined, c),
109
109
  providerDisabled: (c) => t('errors.providerDisabled', undefined, c),
110
110
  urlRequired: (c) => t('errors.validation.urlRequired', undefined, c),
111
+ urlInvalid: (c) => t('errors.validation.invalidUrl', undefined, c),
111
112
  connectionError: (c) => t('errors.connectionError', undefined, c),
112
113
  },
113
114
  }));
@@ -5,6 +5,7 @@ import type { EventBus } from '@itphx/synth-core';
5
5
  import type { QueueProcessorManager } from '@itphx/synth-core';
6
6
  import type { ChatOrchestrator } from '@itphx/synth-core';
7
7
  import type { ContextOptimizer } from '@itphx/synth-core';
8
+ import type { RequestSessionService } from '@itphx/synth-core';
8
9
  import type { ProfileStore } from '@itphx/synth-shared';
9
10
  import type { EventHub } from '../events/hub.js';
10
11
  import type { ProjectStore } from '@itphx/synth-core';
@@ -23,4 +24,9 @@ export declare function createSessionRoutes(kit: AuthKit, sessionManager: Sessio
23
24
  /** Профили пользователей: display name для статистики (fallback — username). */
24
25
  profilesStore?: ProfileStore,
25
26
  /** Агент по умолчанию для новых сессий без `settings.agentRole` (runtime-настройка). */
26
- resolveDefaultAgent?: () => string | Promise<string>): Hono;
27
+ resolveDefaultAgent?: () => string | Promise<string>,
28
+ /**
29
+ * ADR-089: единый funnel создания сессий (прокидывается в core-фабрику).
30
+ * Не задан — core-фабрика использует прямой `SessionManager.createSession`.
31
+ */
32
+ requestSessionService?: RequestSessionService): Hono;