@itphx/synth-backend 0.10.1 → 0.12.4

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 (53) hide show
  1. package/dist/app/bootstrap.d.ts +2 -2
  2. package/dist/app/deps.d.ts +77 -33
  3. package/dist/app/deps.js +969 -102
  4. package/dist/app/listen.d.ts +13 -2
  5. package/dist/app/listen.js +138 -10
  6. package/dist/app/mount-routes.d.ts +16 -3
  7. package/dist/app/mount-routes.js +625 -32
  8. package/dist/app.d.ts +42 -7
  9. package/dist/app.js +149 -12
  10. package/dist/auth/guards.d.ts +17 -1
  11. package/dist/auth/guards.js +46 -2
  12. package/dist/auth/middleware.d.ts +2 -12
  13. package/dist/auth/middleware.js +20 -2
  14. package/dist/auth/oidc.d.ts +7 -0
  15. package/dist/auth/oidc.js +27 -6
  16. package/dist/auth/plugin-scope.d.ts +10 -0
  17. package/dist/auth/plugin-scope.js +69 -0
  18. package/dist/auth/service-scope.d.ts +7 -3
  19. package/dist/auth/service-scope.js +8 -4
  20. package/dist/events/hub.js +3 -38
  21. package/dist/lib/app-config.d.ts +2 -0
  22. package/dist/lib/app-config.js +3 -2
  23. package/dist/lib/defaults-store.d.ts +2 -25
  24. package/dist/lib/defaults-store.js +5 -87
  25. package/dist/lib/i18n.js +153 -0
  26. package/dist/main.js +67 -4
  27. package/dist/routes/agents.d.ts +12 -3
  28. package/dist/routes/agents.js +14 -2
  29. package/dist/routes/auth.d.ts +12 -2
  30. package/dist/routes/auth.js +16 -2
  31. package/dist/routes/context.d.ts +2 -2
  32. package/dist/routes/gateway-patterns.d.ts +2 -2
  33. package/dist/routes/llm.d.ts +8 -2
  34. package/dist/routes/llm.js +6 -3
  35. package/dist/routes/mcp-registry.d.ts +15 -3
  36. package/dist/routes/mcp-registry.js +122 -21
  37. package/dist/routes/messages.d.ts +7 -4
  38. package/dist/routes/messages.js +34 -3
  39. package/dist/routes/models.d.ts +7 -2
  40. package/dist/routes/models.js +3 -1
  41. package/dist/routes/processes.d.ts +34 -0
  42. package/dist/routes/processes.js +26 -0
  43. package/dist/routes/projects.d.ts +9 -3
  44. package/dist/routes/projects.js +8 -1
  45. package/dist/routes/providers.d.ts +15 -3
  46. package/dist/routes/providers.js +33 -21
  47. package/dist/routes/queue.d.ts +5 -4
  48. package/dist/routes/queue.js +30 -3
  49. package/dist/routes/sessions.d.ts +50 -3
  50. package/dist/routes/sessions.js +221 -74
  51. package/dist/test-helpers/close-server.d.ts +33 -0
  52. package/dist/test-helpers/close-server.js +50 -0
  53. package/package.json +4 -4
@@ -1,11 +1,20 @@
1
1
  import { Hono } from 'hono';
2
2
  import type { AuthKit } from '../auth/middleware.js';
3
- import { JsonStore } from '@itphx/synth-core';
3
+ import type { JsonStoreLike } from '@itphx/synth-core';
4
4
  import type { AgentDefinition } from '@itphx/synth-shared';
5
- import type { AgentRegistry } from '@itphx/synth-core';
5
+ import type { AgentRegistry, ContextFileRepository } from '@itphx/synth-core';
6
6
  /**
7
7
  * Backend-обёртка над core-фабрикой агентов: добавляет только RBAC
8
8
  * (админ-эндпоинты — ADMIN) и i18n-сообщения. Логика роутов
9
9
  * (GET /, GET /all, POST /, GET /:id, DELETE /:id, PATCH /:id/enabled) — в core.
10
+ *
11
+ * `contextFiles` — порт файлов контекста: запись ролевого промпта агента
12
+ * вместе с агентом (ADR-046/ADR-089, поле `role_prompt` в теле POST).
13
+ * Роль пишется тем же guard'ом, что и создание агента (ADMIN).
14
+ *
15
+ * ADR-052: запись агентов (создание + ролевой промпт) — «роль ADMIN **или**
16
+ * scope `automation:install`» (зонтичный скоуп установщика пакетов
17
+ * расширений). Guard `requireAdminRoleOrScope` учитывает и роль ADMIN в
18
+ * service-key, и scope — прежние права не отбираются, новые добавляются.
10
19
  */
11
- export declare function createAgentRoutes(kit: AuthKit, agentStore: JsonStore<AgentDefinition>, agentRegistry?: AgentRegistry, getDefaultAgentId?: () => string | Promise<string>): Hono;
20
+ export declare function createAgentRoutes(kit: AuthKit, agentStore: JsonStoreLike<AgentDefinition>, agentRegistry?: AgentRegistry, getDefaultAgentId?: () => string | Promise<string>, contextFiles?: ContextFileRepository): Hono;
@@ -1,20 +1,32 @@
1
1
  import { Hono } from 'hono';
2
2
  import { createAgentRoutes as createCoreAgentRoutes } from '@itphx/synth-core';
3
+ import { requireAdminRoleOrScope } from '../auth/guards.js';
3
4
  import { t } from '../lib/i18n.js';
4
5
  /**
5
6
  * Backend-обёртка над core-фабрикой агентов: добавляет только RBAC
6
7
  * (админ-эндпоинты — ADMIN) и i18n-сообщения. Логика роутов
7
8
  * (GET /, GET /all, POST /, GET /:id, DELETE /:id, PATCH /:id/enabled) — в core.
9
+ *
10
+ * `contextFiles` — порт файлов контекста: запись ролевого промпта агента
11
+ * вместе с агентом (ADR-046/ADR-089, поле `role_prompt` в теле POST).
12
+ * Роль пишется тем же guard'ом, что и создание агента (ADMIN).
13
+ *
14
+ * ADR-052: запись агентов (создание + ролевой промпт) — «роль ADMIN **или**
15
+ * scope `automation:install`» (зонтичный скоуп установщика пакетов
16
+ * расширений). Guard `requireAdminRoleOrScope` учитывает и роль ADMIN в
17
+ * service-key, и scope — прежние права не отбираются, новые добавляются.
8
18
  */
9
- export function createAgentRoutes(kit, agentStore, agentRegistry, getDefaultAgentId) {
19
+ export function createAgentRoutes(kit, agentStore, agentRegistry, getDefaultAgentId, contextFiles) {
10
20
  const app = new Hono();
11
21
  app.route('/', createCoreAgentRoutes({ requireAuth: kit.requireAuth }, agentStore, agentRegistry, getDefaultAgentId, {
12
- writeGuard: kit.requireAdmin,
22
+ writeGuard: requireAdminRoleOrScope('automation:install'),
13
23
  allGuard: kit.requireAdmin,
14
24
  detailGuard: kit.requireAdmin,
25
+ roleFiles: contextFiles,
15
26
  messages: {
16
27
  idRequired: (c) => t('errors.validation.idRequired', undefined, c),
17
28
  invalidAgentId: (c) => t('errors.validation.invalidAgentId', undefined, c),
29
+ invalidRoleFile: (c) => t('errors.validation.invalidRoleFile', undefined, c),
18
30
  agentNotFound: (c) => t('errors.notFound.agent', undefined, c),
19
31
  agentOverrideNotFound: (c) => t('errors.notFound.agentOverride', undefined, c),
20
32
  },
@@ -1,6 +1,16 @@
1
1
  import { Hono } from 'hono';
2
2
  import type { AuthKit } from '../auth/middleware.js';
3
3
  import type { AuthConfig } from '@itphx/synth-shared';
4
+ import type { PluginPolicySignal } from '@itphx/synth-shared';
4
5
  import type { ProfileStore } from '@itphx/synth-shared';
5
- import type { DefaultsStore } from '../lib/defaults-store.js';
6
- export declare function createAuthRoutes(kit: AuthKit, config: AuthConfig, profiles?: ProfileStore, dataDir?: string, defaultsStore?: DefaultsStore | null): Hono;
6
+ import type { DefaultsRepository } from '@itphx/synth-core';
7
+ export declare function createAuthRoutes(kit: AuthKit, config: AuthConfig, profiles?: ProfileStore, dataDir?: string, defaultsStore?: DefaultsRepository | null,
8
+ /**
9
+ * ADR-090 Ф7: сигнал о серверной политике плагинов для публичного
10
+ * дискавери (`GET /auth/oidc-meta`).
11
+ *
12
+ * Только `{ enabled, mode }` — **без списка имён**: allow-list не публичен,
13
+ * полный список отдаёт аутентифицированный роут `GET /api/v2/settings/plugins`.
14
+ * Не задан — сигнала нет (старый клиент трактует это как «неизвестно»).
15
+ */
16
+ pluginPolicySignal?: PluginPolicySignal | null): Hono;
@@ -15,7 +15,16 @@ const BUILT_IN_DEFAULTS = {
15
15
  uiScaleMobile: null,
16
16
  uiScaleDesktop: null,
17
17
  };
18
- export function createAuthRoutes(kit, config, profiles, dataDir, defaultsStore) {
18
+ export function createAuthRoutes(kit, config, profiles, dataDir, defaultsStore,
19
+ /**
20
+ * ADR-090 Ф7: сигнал о серверной политике плагинов для публичного
21
+ * дискавери (`GET /auth/oidc-meta`).
22
+ *
23
+ * Только `{ enabled, mode }` — **без списка имён**: allow-list не публичен,
24
+ * полный список отдаёт аутентифицированный роут `GET /api/v2/settings/plugins`.
25
+ * Не задан — сигнала нет (старый клиент трактует это как «неизвестно»).
26
+ */
27
+ pluginPolicySignal) {
19
28
  const app = new Hono();
20
29
  const avatarsDir = dataDir ? join(dataDir, 'auth', 'avatars') : null;
21
30
  // Корень каталога аватаров (абсолютный) — для containment-проверки.
@@ -135,13 +144,18 @@ export function createAuthRoutes(kit, config, profiles, dataDir, defaultsStore)
135
144
  // Локальный core по адресу сервера узнаёт issuer и public client_id (для ROPC/device flow).
136
145
  // Секрет клиента НЕ отдаётся.
137
146
  app.get('/oidc-meta', (c) => {
147
+ // Ф7 (ADR-090): сигнал о серверной политике плагинов — только режим и
148
+ // признак включения слоя; список имён не публичен (полный список — по
149
+ // аутентифицированному роуту `/api/v2/settings/plugins`).
150
+ const pluginsSignal = pluginPolicySignal ? { plugins: pluginPolicySignal } : {};
138
151
  if (!config.oidc?.enabled) {
139
- return c.json({ enabled: false });
152
+ return c.json({ enabled: false, ...pluginsSignal });
140
153
  }
141
154
  return c.json({
142
155
  enabled: true,
143
156
  issuer: config.oidc.issuer,
144
157
  clientId: config.oidc.cliClientId || 'synth-cli',
158
+ ...pluginsSignal,
145
159
  });
146
160
  });
147
161
  // GET /auth/session — проверка cookie-сессии
@@ -1,4 +1,4 @@
1
1
  import { Hono } from 'hono';
2
2
  import type { AuthKit } from '../auth/middleware.js';
3
- import type { ContextConfig } from '@itphx/synth-core';
4
- export declare function createContextRoutes(kit: AuthKit, config: ContextConfig): Hono;
3
+ import type { ContextFileRepository } from '@itphx/synth-core';
4
+ export declare function createContextRoutes(kit: AuthKit, config: ContextFileRepository): Hono;
@@ -1,9 +1,9 @@
1
1
  import { Hono } from 'hono';
2
2
  import type { AuthKit } from '../auth/middleware.js';
3
- import type { SecretPatternStore } from '@itphx/synth-core';
3
+ import type { SecretPatternRepository } from '@itphx/synth-core';
4
4
  /**
5
5
  * LLM Gateway (ADR-036) — управление regex-паттернами детекции секретов.
6
6
  * Схема «системный + override»: пользовательский список полностью заменяет дефолтный,
7
7
  * DELETE сбрасывает к встроенным паттернам. Только ADMIN.
8
8
  */
9
- export declare function createGatewayPatternsRoutes(kit: AuthKit, store: SecretPatternStore): Hono;
9
+ export declare function createGatewayPatternsRoutes(kit: AuthKit, store: SecretPatternRepository): Hono;
@@ -2,7 +2,8 @@ import { Hono } from 'hono';
2
2
  import type { AuthKit } from '../auth/middleware.js';
3
3
  import { createRateLimiter } from '../middleware/rate-limiter.js';
4
4
  import type { LLMGatewayConfig, ModelConfig, ProviderConfig as SharedProviderConfig } from '@itphx/synth-shared';
5
- import { AuditLogger, RateLimiter, SecretPatternStore } from '@itphx/synth-core';
5
+ import { AuditLogger, RateLimiter } from '@itphx/synth-core';
6
+ import type { MetricsRegistry, SecretPatternRepository } from '@itphx/synth-core';
6
7
  export interface LlmRoutesDeps {
7
8
  /** Резолв провайдера по имени (backend providerCache). */
8
9
  providerLoader: (name: string) => SharedProviderConfig | null;
@@ -17,8 +18,13 @@ export interface LlmRoutesDeps {
17
18
  /** Путь к JSONL полного лога запросов/ответов LLM. */
18
19
  gatewayPayloadLogPath?: string;
19
20
  /** Хранилище кастомных regex-паттернов детекции секретов (null — дефолт детектора). */
20
- patternStore: SecretPatternStore | null;
21
+ patternStore: SecretPatternRepository | null;
21
22
  /** HTTP-мидлварь лимита запросов на ключ/пользователя (необязательно). */
22
23
  rateLimiter?: ReturnType<typeof createRateLimiter>;
24
+ /**
25
+ * ADR-094: реестр метрик для учёта LLM-вызовов через прокси (`onCall`).
26
+ * Не задан (метрики выключены) — нулевые накладные расходы.
27
+ */
28
+ metrics?: MetricsRegistry;
23
29
  }
24
30
  export declare function createLlmRoutes(kit: AuthKit, deps: LlmRoutesDeps): Hono;
@@ -1,7 +1,7 @@
1
1
  import { Hono } from 'hono';
2
2
  import { z } from 'zod';
3
3
  import { scopeGuard } from '../auth/service-scope.js';
4
- import { ContextLengthExceededError, deobfuscateSecrets, GatewayProvider, ProviderError, ProviderFactory, RateLimitError, } from '@itphx/synth-core';
4
+ import { ContextLengthExceededError, deobfuscateSecrets, GatewayProvider, ProviderError, ProviderFactory, RateLimitError, createLlmCallRecorder, } from '@itphx/synth-core';
5
5
  /**
6
6
  * LLM Proxy endpoint (гибридный режим, Часть 5).
7
7
  * OpenAI-совместимый POST /api/v2/llm/chat/completions, через который локальный
@@ -17,7 +17,7 @@ import { ContextLengthExceededError, deobfuscateSecrets, GatewayProvider, Provid
17
17
  const chatMessageSchema = z.object({
18
18
  role: z.string().min(1),
19
19
  content: z.string().nullable(),
20
- tool_calls: z.array(z.record(z.unknown())).optional(),
20
+ tool_calls: z.array(z.record(z.string(), z.unknown())).optional(),
21
21
  tool_call_id: z.string().optional(),
22
22
  reasoning_content: z.string().optional(),
23
23
  name: z.string().optional(),
@@ -34,7 +34,7 @@ const chatCompletionsSchema = z.object({
34
34
  // OpenAIProvider всегда шлёт stream_options.include_usage, но поле принимаем
35
35
  // явно, чтобы Zod его не срезал (контракт запроса).
36
36
  stream_options: z.object({ include_usage: z.boolean().optional() }).optional(),
37
- tools: z.array(z.record(z.unknown())).optional(),
37
+ tools: z.array(z.record(z.string(), z.unknown())).optional(),
38
38
  session_id: z.string().optional(),
39
39
  // Имя серверного провайдера (шлют remote-зеркала RemoteProvider в гибриде).
40
40
  // Опционально — старые клиенты без поля работают как раньше (резолв по модели).
@@ -193,6 +193,9 @@ export function createLlmRoutes(kit, deps) {
193
193
  getRateLimiter: () => deps.gatewayRateLimiter,
194
194
  getPatterns: patternStore ? () => patternStore.getPatterns() : undefined,
195
195
  payloadLogPath: deps.gatewayPayloadLogPath,
196
+ // ADR-094: метрики LLM-вызова (ok/error/rate_limited/blocked + duration/tokens);
197
+ // при выключенных метриках колбэк не создаётся.
198
+ onCall: deps.metrics ? createLlmCallRecorder(deps.metrics) : undefined,
196
199
  sessionId,
197
200
  userId: user.id,
198
201
  });
@@ -1,16 +1,28 @@
1
1
  import { Hono } from 'hono';
2
+ import type { Context } from 'hono';
2
3
  import type { AuthKit } from '../auth/middleware.js';
3
- import type { SessionManager, McpManager, McpRegistryStore } from '@itphx/synth-core';
4
+ import type { SessionManager, McpManager, McpRegistryRepository, ExternalCredentialRepository } from '@itphx/synth-core';
4
5
  import type { McpNetworkPolicy } from '@itphx/synth-shared';
5
6
  export interface McpRoutesOptions {
6
7
  /** ADR-071 §2.5: единый реестр MCP-серверов (источник истины для `/servers` и `/registry`). */
7
- registry: McpRegistryStore;
8
+ registry: McpRegistryRepository;
8
9
  /** ADR-071 §2.3.1: политика сетевого доступа HTTP-серверов. */
9
10
  networkPolicy?: McpNetworkPolicy;
10
11
  /**
11
12
  * ADR-071 §2.3.1: динамический источник политики (runtime-настройка из админки).
12
13
  * Приоритетнее статической `networkPolicy`; читается на каждый запрос.
13
14
  */
14
- getNetworkPolicy?: () => McpNetworkPolicy | undefined;
15
+ getNetworkPolicy?: () => Promise<McpNetworkPolicy | undefined>;
16
+ /**
17
+ * ADR-105 (Ф3): порт слоя внешних доступов — право привязать доступ
18
+ * к коннектору проверяется на границе (инвариант 16). Не задан — привязка
19
+ * запрещена (fail-closed).
20
+ */
21
+ credentials?: ExternalCredentialRepository;
22
+ /**
23
+ * ADR-105 (Ф3): право участника проекта **изменять содержимое** проекта
24
+ * (`OWNER`/`EDITOR`, а также `LEAD`/`ADMIN`) — для доступа уровня проекта.
25
+ */
26
+ canEditProject?: (c: Context, projectId: string) => boolean | Promise<boolean>;
15
27
  }
16
28
  export declare function createMcpRegistryRoutes(kit: AuthKit, mcpManager: McpManager | null, sessionManager: SessionManager | null, options: McpRoutesOptions): Hono;
@@ -1,9 +1,10 @@
1
1
  import { Hono } from 'hono';
2
2
  import { z } from 'zod';
3
- import { evaluateMcpNetworkAccess, getServiceCredential } from '@itphx/synth-core';
4
- import { sessionMcpScopeSchema, hasServiceScope } from '@itphx/synth-shared';
3
+ import { createCredentialBindGuard, evaluateMcpNetworkAccess, getServiceCredential, McpRegistryValidationError, syncMcpManagerFromRegistry, } from '@itphx/synth-core';
4
+ import { sessionMcpScopeSchema, hasServiceScope, findForbiddenMcpSecretHeaders, mcpSecretHeaderErrorMessage, MCP_SECRET_HEADER_ERROR_CODE, } from '@itphx/synth-shared';
5
5
  import { mcpServerConfigSchema } from '@itphx/synth-shared/config';
6
6
  import { requireAdminOrScope, requireScopeForServiceKey } from '../auth/guards.js';
7
+ import { t } from '../lib/i18n.js';
7
8
  // Backend-only MCP-роуты (ADR-071 §2.5): legacy `/servers*`, `/session/:id` и
8
9
  // единый реестр `/registry*`. Probe (`POST /probe`) — общая логика core,
9
10
  // монтируется в `routes/mcp.ts` ПЕРЕД этим роутером.
@@ -29,24 +30,59 @@ const registryUpdateSchema = z.object({
29
30
  enabled: z.boolean().optional(),
30
31
  enabledByDefault: z.boolean().optional(),
31
32
  });
33
+ /**
34
+ * ADR-105 (Ф3): plaintext-секрет в заголовках коннектора запрещён —
35
+ * авторизация только через слой внешних доступов (`auth.kind='credential'`).
36
+ *
37
+ * Значений заголовков в тексте ошибки нет — только их имена.
38
+ */
39
+ function secretHeaderError(config) {
40
+ const forbidden = findForbiddenMcpSecretHeaders(config?.headers);
41
+ if (forbidden.length === 0)
42
+ return null;
43
+ return { code: MCP_SECRET_HEADER_ERROR_CODE, message: mcpSecretHeaderErrorMessage(forbidden) };
44
+ }
45
+ /**
46
+ * ADR-105 (Ф3): хранилище реестра — последний рубеж запрета plaintext-секрета.
47
+ * Ошибка валидации → 400 с тем же кодом (иначе роут отдал бы 500).
48
+ */
49
+ function secretHeaderStoreError(err) {
50
+ if (err instanceof McpRegistryValidationError && err.code === MCP_SECRET_HEADER_ERROR_CODE) {
51
+ return { code: err.code, message: err.message };
52
+ }
53
+ return null;
54
+ }
32
55
  export function createMcpRegistryRoutes(kit, mcpManager, sessionManager, options) {
33
56
  const app = new Hono();
34
57
  const registry = options.registry;
35
- const resolveNetworkPolicy = () => options.getNetworkPolicy?.() ?? options.networkPolicy;
58
+ const resolveNetworkPolicy = async () => (options.getNetworkPolicy ? await options.getNetworkPolicy() : undefined) ?? options.networkPolicy;
36
59
  /** Синхронизировать конфиг менеджера из реестра — одно чтение на все карты. */
37
60
  const syncManagerConfig = async () => {
38
61
  if (!mcpManager)
39
62
  return;
40
- const maps = await registry.toManagerMaps();
41
- mcpManager.setConfig(maps.servers);
42
- mcpManager.setServerOrigins(maps.origins);
43
- mcpManager.setServerTrusts(maps.trusts);
44
- mcpManager.setServerAuthors(maps.authors);
45
- mcpManager.setDefaultServers(maps.defaults);
46
- mcpManager.setServerSystemEnabled(maps.systemEnabled);
63
+ await syncMcpManagerFromRegistry(mcpManager, registry);
47
64
  };
48
65
  const isConnected = (name) => mcpManager?.getConfiguredServers().find((s) => s.name === name)?.connected ?? false;
49
66
  const currentUser = (c) => c.get('user') ?? null;
67
+ /**
68
+ * ADR-105 (Ф3): граница проверки права привязки внешнего доступа к коннектору
69
+ * (инвариант 16 — проверка не в обработчике, правило — в core).
70
+ *
71
+ * Актор — пользователь запроса (для service-key — синтетический
72
+ * `service:<keyId>` с ролями ключа, ADR-052).
73
+ */
74
+ const checkCredentialBinding = createCredentialBindGuard({
75
+ ...(options.credentials ? { credentials: options.credentials } : {}),
76
+ resolveActor: (c) => {
77
+ const user = currentUser(c);
78
+ return { userId: user?.id ?? '', roles: user?.roles ?? [] };
79
+ },
80
+ ...(options.canEditProject ? { canEditProject: options.canEditProject } : {}),
81
+ messages: {
82
+ notFound: (c) => t('errors.notFound.credential', undefined, c),
83
+ forbidden: (c) => t('auth.forbidden', undefined, c),
84
+ },
85
+ });
50
86
  /**
51
87
  * ADR-052/O1: запрос от installer-service-key (scope `addons:install`).
52
88
  * Даёт scoped-ключу без роли ADMIN создавать **instance**-записи реестра
@@ -61,7 +97,7 @@ export function createMcpRegistryRoutes(kit, mcpManager, sessionManager, options
61
97
  // (в т.ч. приватные сети инстанса) доверенные.
62
98
  if (origin !== 'user' || config.type === 'stdio' || !config.url)
63
99
  return null;
64
- const policy = resolveNetworkPolicy();
100
+ const policy = await resolveNetworkPolicy();
65
101
  if (!policy)
66
102
  return null;
67
103
  const result = await evaluateMcpNetworkAccess(config.url, policy);
@@ -93,6 +129,16 @@ export function createMcpRegistryRoutes(kit, mcpManager, sessionManager, options
93
129
  if (await registry.getByName(name)) {
94
130
  return c.json({ error: { code: 'CONFLICT', message: `Сервер "${name}" уже существует` } }, 409);
95
131
  }
132
+ // ADR-105 (Ф3): plaintext-секрет в заголовках → 400 (не 500).
133
+ const secretError = secretHeaderError(config);
134
+ if (secretError) {
135
+ return c.json({ error: secretError }, 400);
136
+ }
137
+ // ADR-105 (Ф3): право привязать внешний доступ к коннектору (граница).
138
+ const bindError = await checkCredentialBinding(c, config);
139
+ if (bindError) {
140
+ return c.json({ error: bindError }, bindError.code === 'NOT_FOUND' ? 404 : 403);
141
+ }
96
142
  const networkError = await checkNetwork(config, 'instance');
97
143
  if (networkError) {
98
144
  return c.json({ error: networkError }, 400);
@@ -123,6 +169,16 @@ export function createMcpRegistryRoutes(kit, mcpManager, sessionManager, options
123
169
  if (!parsed.success) {
124
170
  return c.json({ error: { code: 'VALIDATION_ERROR', message: parsed.error.message } }, 400);
125
171
  }
172
+ // ADR-105 (Ф3): plaintext-секрет в заголовках → 400 (не 500).
173
+ const secretError = secretHeaderError(parsed.data);
174
+ if (secretError) {
175
+ return c.json({ error: secretError }, 400);
176
+ }
177
+ // ADR-105 (Ф3): право привязать внешний доступ к коннектору (граница).
178
+ const bindError = await checkCredentialBinding(c, parsed.data, entry.config.auth?.kind === 'credential' ? entry.config.auth.credentialId : undefined);
179
+ if (bindError) {
180
+ return c.json({ error: bindError }, bindError.code === 'NOT_FOUND' ? 404 : 403);
181
+ }
126
182
  const networkError = await checkNetwork(parsed.data, entry.origin);
127
183
  if (networkError) {
128
184
  return c.json({ error: networkError }, 400);
@@ -163,6 +219,11 @@ export function createMcpRegistryRoutes(kit, mcpManager, sessionManager, options
163
219
  if (!config) {
164
220
  return c.json({ error: { code: 'NOT_FOUND', message: `Сервер "${name}" не найден` } }, 404);
165
221
  }
222
+ // ADR-105 (Ф3): probe/тест не подключается к коннектору с plaintext-секретом.
223
+ const secretError = secretHeaderError(config);
224
+ if (secretError) {
225
+ return c.json({ error: secretError }, 400);
226
+ }
166
227
  if (!mcpManager) {
167
228
  return c.json({ error: { code: 'INTERNAL_ERROR', message: 'McpManager не настроен' } }, 500);
168
229
  }
@@ -278,6 +339,16 @@ export function createMcpRegistryRoutes(kit, mcpManager, sessionManager, options
278
339
  }
279
340
  const { name, config, enabled, enabledByDefault, origin } = parsed.data;
280
341
  const admin = kit.isAdmin(c);
342
+ // ADR-105 (Ф3): plaintext-секрет в заголовках → 400 (не 500).
343
+ const secretError = secretHeaderError(config);
344
+ if (secretError) {
345
+ return c.json({ error: secretError }, 400);
346
+ }
347
+ // ADR-105 (Ф3): право привязать внешний доступ к коннектору (граница).
348
+ const bindError = await checkCredentialBinding(c, config);
349
+ if (bindError) {
350
+ return c.json({ error: bindError }, bindError.code === 'NOT_FOUND' ? 404 : 403);
351
+ }
281
352
  // ADR-052/O1: installer-ключ (scope `addons:install`) создаёт instance-записи
282
353
  // даже без роли ADMIN — это общие записи инстанса (а не персональные).
283
354
  const isInstaller = isInstallerKey(c);
@@ -307,15 +378,25 @@ export function createMcpRegistryRoutes(kit, mcpManager, sessionManager, options
307
378
  }
308
379
  const user = currentUser(c);
309
380
  const author = user ? { userId: user.id, username: user.username } : null;
310
- const entry = await registry.add({
311
- name,
312
- config,
313
- origin: entryOrigin,
314
- trust,
315
- author,
316
- enabled,
317
- enabledByDefault,
318
- });
381
+ let entry;
382
+ try {
383
+ entry = await registry.add({
384
+ name,
385
+ config,
386
+ origin: entryOrigin,
387
+ trust,
388
+ author,
389
+ enabled,
390
+ enabledByDefault,
391
+ });
392
+ }
393
+ catch (err) {
394
+ // ADR-105 (Ф3): запрет plaintext-секрета → 400, а не 500.
395
+ const storeError = secretHeaderStoreError(err);
396
+ if (storeError)
397
+ return c.json({ error: storeError }, 400);
398
+ throw err;
399
+ }
319
400
  await syncManagerConfig();
320
401
  return c.json(entry, 201);
321
402
  });
@@ -345,6 +426,16 @@ export function createMcpRegistryRoutes(kit, mcpManager, sessionManager, options
345
426
  if (nextConfig.type === 'stdio' && !admin) {
346
427
  return c.json({ error: { code: 'FORBIDDEN', message: 'stdio-серверы может изменять только ADMIN' } }, 403);
347
428
  }
429
+ // ADR-105 (Ф3): plaintext-секрет в заголовках → 400 (не 500).
430
+ const secretError = secretHeaderError(nextConfig);
431
+ if (secretError) {
432
+ return c.json({ error: secretError }, 400);
433
+ }
434
+ // ADR-105 (Ф3): право привязать внешний доступ к коннектору (граница).
435
+ const bindError = await checkCredentialBinding(c, nextConfig, existing.config.auth?.kind === 'credential' ? existing.config.auth.credentialId : undefined);
436
+ if (bindError) {
437
+ return c.json({ error: bindError }, bindError.code === 'NOT_FOUND' ? 404 : 403);
438
+ }
348
439
  const networkError = await checkNetwork(nextConfig, existing.origin);
349
440
  if (networkError) {
350
441
  return c.json({ error: networkError }, 400);
@@ -356,7 +447,17 @@ export function createMcpRegistryRoutes(kit, mcpManager, sessionManager, options
356
447
  error: { code: 'CONFLICT', message: `Сервер "${parsed.data.name}" уже существует в реестре` },
357
448
  }, 409);
358
449
  }
359
- const updated = await registry.update(id, parsed.data);
450
+ let updated;
451
+ try {
452
+ updated = await registry.update(id, parsed.data);
453
+ }
454
+ catch (err) {
455
+ // ADR-105 (Ф3): запрет plaintext-секрета → 400, а не 500.
456
+ const storeError = secretHeaderStoreError(err);
457
+ if (storeError)
458
+ return c.json({ error: storeError }, 400);
459
+ throw err;
460
+ }
360
461
  await syncManagerConfig();
361
462
  return c.json(updated);
362
463
  });
@@ -1,9 +1,12 @@
1
1
  import { Hono } from 'hono';
2
2
  import type { AuthKit } from '../auth/middleware.js';
3
- import type { SessionManager, ContextOptimizer, EventBus } from '@itphx/synth-core';
3
+ import type { SessionManager, ContextOptimizer, EventBus, ProjectRepository, BlobRefRepository } from '@itphx/synth-core';
4
4
  /**
5
- * Backend-обёртка над core-фабрикой сообщений: добавляет i18n-сообщения и хук
6
- * пересчёта `canSummarize` после мутаций (backend-специфика). Логика роутов
5
+ * Backend-обёртка над core-фабрикой сообщений: добавляет i18n-сообщения, RBAC
6
+ * доступа к сессии (владелец/ADMIN/участник проекта/LEAD) и хук пересчёта
7
+ * `canSummarize` после мутаций (backend-специфика). Логика роутов
7
8
  * (batch/toggle/pin/delete/retry/debug) — в core-фабрике.
8
9
  */
9
- export declare function createMessageRoutes(kit: AuthKit, sessionManager: SessionManager, contextOptimizer: ContextOptimizer | null, eventBus: EventBus): Hono;
10
+ export declare function createMessageRoutes(kit: AuthKit, sessionManager: SessionManager, contextOptimizer: ContextOptimizer | null, eventBus: EventBus, projectStore?: ProjectRepository,
11
+ /** ADR-115: учёт ссылок на объекты blob-хранилища (снятие при удалении). */
12
+ blobRefs?: BlobRefRepository): Hono;
@@ -2,20 +2,51 @@ import { Hono } from 'hono';
2
2
  import { createMessageRoutes as createCoreMessageRoutes } from '@itphx/synth-core';
3
3
  import { t } from '../lib/i18n.js';
4
4
  import { createRecalcCanSummarize } from '../lib/recalc-can-summarize.js';
5
+ import { createProjectAccess } from './projects.js';
5
6
  /**
6
- * Backend-обёртка над core-фабрикой сообщений: добавляет i18n-сообщения и хук
7
- * пересчёта `canSummarize` после мутаций (backend-специфика). Логика роутов
7
+ * Backend-обёртка над core-фабрикой сообщений: добавляет i18n-сообщения, RBAC
8
+ * доступа к сессии (владелец/ADMIN/участник проекта/LEAD) и хук пересчёта
9
+ * `canSummarize` после мутаций (backend-специфика). Логика роутов
8
10
  * (batch/toggle/pin/delete/retry/debug) — в core-фабрике.
9
11
  */
10
- export function createMessageRoutes(kit, sessionManager, contextOptimizer, eventBus) {
12
+ export function createMessageRoutes(kit, sessionManager, contextOptimizer, eventBus, projectStore,
13
+ /** ADR-115: учёт ссылок на объекты blob-хранилища (снятие при удалении). */
14
+ blobRefs) {
11
15
  const app = new Hono();
12
16
  const recalcCanSummarize = createRecalcCanSummarize({ sessionManager, contextOptimizer, eventBus });
17
+ const { canReadProject, canEditProjectContent } = createProjectAccess(kit);
18
+ // ADR-071 §2.4: владелец сессии — обычный пользователь.
19
+ const isSessionOwner = (session, userId) => (session.ownerId ?? session.userId) === userId;
13
20
  app.route('/', createCoreMessageRoutes({ requireAuth: kit.requireAuth }, sessionManager, undefined, {
14
21
  messages: {
15
22
  sessionNotFound: (c) => t('errors.notFound.session', undefined, c),
16
23
  messageNotFound: (c) => t('errors.notFound.message', undefined, c),
24
+ forbidden: (c) => t('auth.forbidden', undefined, c),
17
25
  },
18
26
  onMessagesChanged: (sessionId) => recalcCanSummarize(sessionId),
27
+ // ADR-115: ссылки на объекты вложений снимаются при удалении сообщения.
28
+ ...(blobRefs ? { blobRefs } : {}),
29
+ resolveUserId: async (c) => (await kit.getCurrentUser(c))?.id ?? '',
30
+ canAccess: (session, c, userId) => isSessionOwner(session, userId)
31
+ || (typeof kit.isAdmin === 'function' && kit.isAdmin(c)),
32
+ resolveElevated: (c) => {
33
+ const isAdmin = typeof kit.isAdmin === 'function' && kit.isAdmin(c);
34
+ const isLead = typeof kit.hasRole === 'function' && kit.hasRole(c, 'LEAD');
35
+ return isAdmin || isLead;
36
+ },
37
+ // read/write по роли в проекте: чтение — owner/любой участник, мутация —
38
+ // owner/EDITOR/LEAD/ADMIN (`createProjectAccess`; см. sessions.ts).
39
+ resolveCanAccessExtra: async (session, c, userId, access) => {
40
+ if (!projectStore || !session.projectId)
41
+ return false;
42
+ const project = await projectStore.load(session.projectId);
43
+ if (!project)
44
+ return false;
45
+ const ctx = c;
46
+ return access === 'read'
47
+ ? canReadProject(ctx, project, userId)
48
+ : canEditProjectContent(ctx, project, userId);
49
+ },
19
50
  }));
20
51
  return app;
21
52
  }
@@ -1,10 +1,15 @@
1
1
  import { Hono } from 'hono';
2
2
  import type { AuthKit } from '../auth/middleware.js';
3
- import { JsonStore } from '@itphx/synth-core';
3
+ import type { DefaultModelPair, JsonStoreLike } from '@itphx/synth-core';
4
4
  import type { ModelConfig, ProviderConfig } from '@itphx/synth-shared';
5
+ /** Колбэки модели по умолчанию инстанса (runtime-пара provider+model). */
6
+ export interface ModelRoutesDefaultOptions {
7
+ getDefaultModel?: () => DefaultModelPair | null | Promise<DefaultModelPair | null>;
8
+ setDefaultModel?: (pair: DefaultModelPair) => void | Promise<void>;
9
+ }
5
10
  /**
6
11
  * Backend-обёртка над core-фабрикой моделей: добавляет только RBAC
7
12
  * (мутации и синхронизация — ADMIN), rate limit на `fetch` и `set_as_default`.
8
13
  * Логика роутов (GET /, POST /, DELETE /:id, POST /fetch) — в core-фабрике.
9
14
  */
10
- export declare function createModelRoutes(kit: AuthKit, modelStore: JsonStore<ModelConfig>, providerStore: JsonStore<ProviderConfig>, modelCache: Map<string, ModelConfig>, providerCache: Map<string, ProviderConfig>): Hono;
15
+ export declare function createModelRoutes(kit: AuthKit, modelStore: JsonStoreLike<ModelConfig>, providerStore: JsonStoreLike<ProviderConfig>, modelCache: Map<string, ModelConfig>, providerCache: Map<string, ProviderConfig>, defaults?: ModelRoutesDefaultOptions): Hono;
@@ -7,7 +7,7 @@ import { createRateLimiter } from '../middleware/rate-limiter.js';
7
7
  * (мутации и синхронизация — ADMIN), rate limit на `fetch` и `set_as_default`.
8
8
  * Логика роутов (GET /, POST /, DELETE /:id, POST /fetch) — в core-фабрике.
9
9
  */
10
- export function createModelRoutes(kit, modelStore, providerStore, modelCache, providerCache) {
10
+ export function createModelRoutes(kit, modelStore, providerStore, modelCache, providerCache, defaults = {}) {
11
11
  const app = new Hono();
12
12
  // Общая логика (GET /, POST /, DELETE /:id, POST /fetch, set_as_default) — в core.
13
13
  app.route('/', createCoreModelRoutes({ requireAuth: kit.requireAuth }, modelStore, providerStore, modelCache, {
@@ -16,6 +16,8 @@ export function createModelRoutes(kit, modelStore, providerStore, modelCache, pr
16
16
  fetchMiddleware: [createRateLimiter(3, 120_000)],
17
17
  providerCache,
18
18
  supportSetAsDefault: true,
19
+ getDefaultModel: defaults.getDefaultModel,
20
+ setDefaultModel: defaults.setDefaultModel,
19
21
  messages: {
20
22
  idRequired: (c) => t('errors.validation.idRequired', undefined, c),
21
23
  modelNotFound: (c) => t('errors.notFound.model', undefined, c),
@@ -0,0 +1,34 @@
1
+ /**
2
+ * Managed-правило доступа к реестру фоновых прогонов (PROP-096/097).
3
+ *
4
+ * Право на прогон — это право на его **сессию-владельца**:
5
+ * - **владелец** сессии — да;
6
+ * - **ADMIN** — да (сквозной доступ к инстансу);
7
+ * - **участник проекта** сессии: чтение — `canReadProject` (любая роль, в т.ч.
8
+ * `VIEWER`), изменение — `canEditProjectContent` (`OWNER`/`EDITOR`/`LEAD`/
9
+ * `ADMIN`). Read-доступ **не** расширяет права на изменение (инвариант 21):
10
+ * `VIEWER` читает прогон, но не может его остановить или удалить;
11
+ * - **LEAD** — сквозной доступ к содержимому проекта (как у `canManageProject`).
12
+ *
13
+ * Правило одно и то же для HTTP-контура и для любых других потребителей
14
+ * (его же использует `createProjectAccess` — источник истины по ролям).
15
+ */
16
+ import type { Context } from 'hono';
17
+ import type { Session } from '@itphx/synth-shared';
18
+ import type { ProjectRepository, SessionAccessKind } from '@itphx/synth-core';
19
+ import type { AuthKit } from '../auth/middleware.js';
20
+ export interface BackendProcessAccessDeps {
21
+ /** AuthKit backend (OIDC/RBAC). */
22
+ auth: AuthKit;
23
+ /** Порт проектов — по нему резолвятся права на проект сессии. */
24
+ projectStore: ProjectRepository;
25
+ }
26
+ /** Предикат доступа к прогону (совместим с `SessionAccessPredicate` core). */
27
+ export type BackendProcessAccess = (session: Session, c: Context, userId: string, access: SessionAccessKind) => Promise<boolean>;
28
+ /**
29
+ * Собрать правило доступа к фоновым прогонам для managed-контура.
30
+ *
31
+ * Fail-closed: сессия без проекта и не своего владельца — отказ; проект не
32
+ * найден — отказ.
33
+ */
34
+ export declare function createBackendProcessAccess(deps: BackendProcessAccessDeps): BackendProcessAccess;
@@ -0,0 +1,26 @@
1
+ import { createProjectAccess } from './projects.js';
2
+ /**
3
+ * Собрать правило доступа к фоновым прогонам для managed-контура.
4
+ *
5
+ * Fail-closed: сессия без проекта и не своего владельца — отказ; проект не
6
+ * найден — отказ.
7
+ */
8
+ export function createBackendProcessAccess(deps) {
9
+ const projectAccess = createProjectAccess(deps.auth);
10
+ return async (session, c, userId, access) => {
11
+ const owner = session.ownerId ?? session.userId;
12
+ if (owner && owner === userId)
13
+ return true;
14
+ if (deps.auth.isAdmin(c))
15
+ return true;
16
+ if (!session.projectId)
17
+ return false;
18
+ const project = await deps.projectStore.load(session.projectId);
19
+ if (!project)
20
+ return false;
21
+ const ctx = c;
22
+ return access === 'read'
23
+ ? projectAccess.canReadProject(ctx, project, userId)
24
+ : projectAccess.canEditProjectContent(ctx, project, userId);
25
+ };
26
+ }