@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
@@ -6,13 +6,39 @@
6
6
  import { isAbsolute, join, normalize, resolve } from 'node:path';
7
7
  import { randomUUID } from 'node:crypto';
8
8
  import { DEFAULT_LLM_GATEWAY_RATE_LIMIT, ProjectRole, SYNTH_VERSION, resolveSecretKey, resolveStorageBackend, resolvePostgresConfig, resolvePostgresPassword } from '@itphx/synth-shared';
9
- import { DEFAULT_AGENT_ID, RateLimiter, getPublicOpenApiDocument, createFsRoutes, createGitRoutes, createSshKeyRoutes, createAgentSshKeyRoutes, createEventRoutes, createSchedulerRoutes, createServiceKeyRoutes, createWebhookRoutes, mergeLlmGatewayConfig, mergeSecurityConfig, mergePluginsConfig, createSkillRoutes, createCommandRoutes, createSkillBundleRoutes, createSessionSkillScopeRoutes, createProjectSkillScopeRoutes, createSkillSettingsRoutes, createIdentityRoutes, createMaintenanceRoutes, createAnalyticsRoutes, AnalyticsService, createProjectPortableRoutes, createStorageContextAsync, ProjectInstructionsResolver, createInstructionsInfoResolver, createSettingsRoutes, createDictionaryRoutes, createAuditRoutes as createSecurityAuditRoutes, currentEgressLog, createContextRoutes as createCoreContextRoutes, createMetricsSettingsRoutes,
9
+ import { resolvePromptInjection } from '@itphx/synth-shared/config';
10
+ import { DEFAULT_AGENT_ID, RateLimiter, resolveAgentRoleAlias, getPublicOpenApiDocument, createFsRoutes, createGitRoutes, createSshKeyRoutes, createAgentSshKeyRoutes, createEventRoutes, createSchedulerRoutes, createServiceKeyRoutes, createWebhookRoutes,
11
+ // PROP-141 (этап 5, B-2): HTTP-контур таймеров и будильников.
12
+ createTimerRoutes, mergeLlmGatewayConfig, mergeSecurityConfig, mergePluginsConfig, createSkillRoutes, createCommandRoutes, createSkillBundleRoutes, createSnippetRoutes, createSessionSkillScopeRoutes, createProjectSkillScopeRoutes, createSkillSettingsRoutes, createIdentityRoutes, createMaintenanceRoutes, createAnalyticsRoutes, AnalyticsService, createProjectPortableRoutes, createStorageContextAsync, ProjectInstructionsResolver, createInstructionsInfoResolver, createSettingsRoutes, createDictionaryRoutes, createAuditRoutes, currentEgressLog,
13
+ // ADR-036/ADR-095: логи, аудит LLM Gateway, regex-паттерны, файлы контекста
14
+ // и группы логирования — core-фабрики (backend передаёт RBAC/i18n через opts).
15
+ createLogsRoutes, resolveLogDir, createGatewayPatternsRoutes, createContextFileRoutes, createDebugRoutes, createContextRoutes as createCoreContextRoutes, createMetricsSettingsRoutes,
16
+ // ADR-133: обновления — проверка по каналам, SSE-установка и тумблер автопроверки.
17
+ createUpdateRoutes, createUpdatesSettingsRoutes,
10
18
  // ADR-115: админ-раздел «Вложения» — runtime-настройки мультимодального ввода.
11
- createAttachmentsSettingsRoutes, createModalityModelLookup, createContextWindowSettingsRoutes, createAgentsLimitsSettingsRoutes, createContextDefaultsSettingsRoutes, createStickyNotesSettingsRoutes, createStagingAttachmentRoutes, AttachmentService, createPacksRoutes, createPipelinesRoutes, createPipelineProjectRoutes, createProcessRoutes, createPluginsRoutes, createPluginSettingsRoutes, createMemoryRoutes, MEMORY_PLUGIN_NAME, MemoryProviderUnavailableError, executeToolDef,
19
+ createAttachmentsSettingsRoutes, createModalityModelLookup, createContextWindowSettingsRoutes, createAgentsLimitsSettingsRoutes,
20
+ // Лимит тяжёлых операций с сессиями (`limits.sessionOpsPerMinute`).
21
+ createRequestLimitsSettingsRoutes, createContextDefaultsSettingsRoutes, createStickyNotesSettingsRoutes, createSshSettingsRoutes, createBackgroundSettingsRoutes, createStagingAttachmentRoutes, AttachmentService, createPacksRoutes, createPipelinesRoutes, createPipelineProjectRoutes, createProcessRoutes, toBlockingRunDto,
22
+ // ADR-111 §detach: авто-detach блокирующих прогонов при вмешательстве
23
+ // (вклинивание из очереди) — тот же шов, что у prompt-роута.
24
+ autoDetachOnSteer,
25
+ // PROP-132 (Ф3б): HTTP-контур терминалов (сервис собирается в `deps.ts`).
26
+ createTerminalRoutes,
27
+ // PROP-132 (Ф3в): мастер-выключатель терминалов (`/api/v2/settings/terminal`).
28
+ createTerminalSettingsRoutes,
29
+ // PROP-135 Ф6b-1: профили и пулы исполнения — admin-API (`/api/v2/execution/*`).
30
+ createExecutionRoutes, createPluginsRoutes, createPluginSettingsRoutes, createMemoryRoutes, MEMORY_PLUGIN_NAME, MemoryProviderUnavailableError, executeToolDef,
12
31
  // ADR-118 §8: возможности инстанса (`GET /api/v2/meta`).
13
- createMetaRoutes, createOAuthRoutes, bindCredentialToConnector, syncMcpManagerFromRegistry, resolveProjectWorkspace, resolvePluginServerPolicy, } from '@itphx/synth-core';
32
+ createMetaRoutes, createOAuthRoutes, bindCredentialToConnector, syncMcpManagerFromRegistry, createProjectPlanRoutes, createProjectLogRoutes, resolveProjectWorkspace, resolvePluginServerPolicy,
33
+ // PROP-135 Ф6a: каталог профилей исполнения — валидация проектных/сессионных
34
+ // настроек профиля.
35
+ executionProfileCatalog, browserProfileCatalog,
36
+ // ADR-099: env дочернего npm (CA `security.tls` + прокси-маршрут реестра).
37
+ resolveNpmInstallEnvironment, } from '@itphx/synth-core';
14
38
  import { createProjectRoutes, createProjectAccess } from '../routes/projects.js';
15
39
  import { createBackendProcessAccess } from '../routes/processes.js';
40
+ import { createBackendScheduleAccess } from '../routes/schedules.js';
41
+ import { createBackendProjectAccess } from '../routes/project-access.js';
16
42
  import { createSessionRoutes } from '../routes/sessions.js';
17
43
  import { createMessageRoutes } from '../routes/messages.js';
18
44
  import { createQueueRoutes } from '../routes/queue.js';
@@ -20,12 +46,7 @@ import { createProviderRoutes } from '../routes/providers.js';
20
46
  import { createModelRoutes } from '../routes/models.js';
21
47
  import { createAgentRoutes } from '../routes/agents.js';
22
48
  import { createMcpRoutes } from '../routes/mcp.js';
23
- import { createContextRoutes as createContextFileRoutes } from '../routes/context.js';
24
- import { createDebugRoutes } from '../routes/debug.js';
25
49
  import { createUserRoutes } from '../routes/users.js';
26
- import { createAuditRoutes } from '../routes/audit.js';
27
- import { createLogsRoutes, resolveLogDir } from '../routes/logs.js';
28
- import { createGatewayPatternsRoutes } from '../routes/gateway-patterns.js';
29
50
  import { createLlmRoutes } from '../routes/llm.js';
30
51
  import { createRateLimiter } from '../middleware/rate-limiter.js';
31
52
  import { scopeGuard, serviceProjectProjection } from '../auth/service-scope.js';
@@ -38,7 +59,7 @@ import { registerEventsSse } from './sse-events.js';
38
59
  */
39
60
  export function mountBackendRoutes(app, auth, ctx) {
40
61
  const { config, deps } = ctx;
41
- const { dataDir, projectStore, sessionManager, eventBus, queueManager, processMessage, orchestrator, profilesStore, getDefaultAgentId, requestSessionService, contextOptimizer, protectedPathsStore, providerStore, providerCache, modelStore, modelCache, agentStore, agentRegistry, contextConfig, sshKeyStore, commandService, bundleStore, dictionaries, serviceApiKeyStore, eventIngress, eventBindingStore, eventJournal, routeRuleStore, eventApiKeyStore, schedulerService, scheduleStore, jobStore, webhookStore, webhookDeliveryStore, webhookService, webhooksConfig, eventHub, mcpManager, mcpRegistryStore, skillService, settingsStore, egressResolver, securityAudit, egressRequests, defaultWorkingDir, patternStore, toolRegistry, gatewayAuditLogger, gatewayPayloadLogPath, gatewayConfig, providerLoader, modelLoader, modelWindowLoader, resolveAgentTemplate, identityClaimStore, live, maintenanceAudit, analyticsRollups, analytics, metrics, pipelines, packs, } = deps;
62
+ const { dataDir, projectStore, sessionManager, eventBus, queueManager, processMessage, orchestrator, profilesStore, getDefaultAgentId, requestSessionService, contextOptimizer, protectedPathsStore, providerStore, providerCache, modelStore, modelCache, agentStore, agentRegistry, contextConfig, sshKeyStore, commandService, bundleStore, dictionaries, serviceApiKeyStore, snippetService, eventIngress, eventBindingStore, eventJournal, routeRuleStore, eventApiKeyStore, schedulerService, scheduleStore, jobStore, webhookStore, webhookDeliveryStore, webhookService, webhooksConfig, eventHub, mcpManager, mcpRegistryStore, skillService, settingsStore, egressResolver, securityAudit, egressRequests, commandAuditLog, defaultWorkingDir, patternStore, toolRegistry, gatewayAuditLogger, gatewayPayloadLogPath, gatewayConfig, providerLoader, modelLoader, modelWindowLoader, resolveAgentTemplate, identityClaimStore, live, maintenanceAudit, analyticsRollups, analytics, metrics, pipelines, packs, } = deps;
42
63
  /**
43
64
  * Fallback-пара «модель по умолчанию» из config (`llm.defaultProvider` +
44
65
  * `llm.defaultModel`) — только если заданы оба.
@@ -59,8 +80,51 @@ export function mountBackendRoutes(app, auth, ctx) {
59
80
  // ADR-052 (этап I): публичный OpenAPI-документ (spike) за requireAuth;
60
81
  // публичную выдачу без auth согласуем отдельно.
61
82
  app.get('/api/v2/openapi.json', auth.requireAuth, (c) => c.json(getPublicOpenApiDocument()));
83
+ // RBAC-хелперы проекта (ADR-089 §5.5/§5.8): владелец/участник/LEAD/ADMIN.
84
+ // Объявлены до монтирования проектов — их используют и контур плана/журнала
85
+ // (PROP-054), и FS/git-роуты.
86
+ const projectAccess = createProjectAccess(auth);
87
+ // PROP-135 Ф6a: снимок каталога профилей исполнения — валидация
88
+ // `project.executor` (PUT проекта) и `settings.executorProfile` (PATCH сессии).
89
+ const executionProfiles = executionProfileCatalog(deps.executionRouter);
90
+ // PROP-135 (браузерный контур): каталог браузерных профилей — валидация
91
+ // `browser_profile`/`allowedBrowserProfiles` у агента/проекта/сессии.
92
+ const browserProfiles = browserProfileCatalog(deps.executionRouter);
62
93
  // Projects routes
63
- app.route('/api/v2/projects', createProjectRoutes(auth, projectStore, sessionManager, config.workspacesRoot, mcpManager, skillService, settingsStore, mcpRegistryStore, deps.worktreeService, eventBus));
94
+ // ADR-140 Ф2: хаб подписок — при смене состояния доступа к проекту
95
+ // пересчитываются подписки уже подключённых клиентов (WS/SSE).
96
+ app.route('/api/v2/projects', createProjectRoutes(auth, projectStore, sessionManager, config.workspacesRoot, mcpManager, skillService, settingsStore, mcpRegistryStore, deps.worktreeService, eventBus, executionProfiles, browserProfiles, securityAudit, eventHub, profilesStore));
97
+ // PROP-054: точечные операции плана проекта (`/projects/:id/plan*`) —
98
+ // core-фабрика, RBAC — те же правила проекта (чтение — право чтения,
99
+ // мутации — право изменения содержимого; `VIEWER` читает, но не мутирует).
100
+ app.route('/api/v2/projects', createProjectPlanRoutes({ requireAuth: auth.requireAuth }, projectStore, {
101
+ canRead: async (c, project, userId) => projectAccess.canReadProject(c, project, userId),
102
+ canEditContent: async (c, project, userId) => projectAccess.canEditProjectContent(c, project, userId),
103
+ getCurrentUserId: async (c) => (await auth.getCurrentUser(c))?.id ?? '',
104
+ messages: {
105
+ notFound: (c) => t('errors.notFound.project', undefined, c),
106
+ forbidden: (c) => t('auth.forbidden', undefined, c),
107
+ invalidBody: (c) => t('errors.validation.invalidPlanBody', undefined, c),
108
+ remoteUnavailable: (c) => t('errors.unavailable.remoteProject', undefined, c),
109
+ },
110
+ sessionManager,
111
+ eventBus,
112
+ }));
113
+ // PROP-054: журнал проекта и инварианты (`/projects/:id/log*`,
114
+ // `/projects/:id/invariants`). Журнал вынесен из детали проекта.
115
+ app.route('/api/v2/projects', createProjectLogRoutes({ requireAuth: auth.requireAuth }, projectStore, {
116
+ canRead: async (c, project, userId) => projectAccess.canReadProject(c, project, userId),
117
+ canEditContent: async (c, project, userId) => projectAccess.canEditProjectContent(c, project, userId),
118
+ getCurrentUserId: async (c) => (await auth.getCurrentUser(c))?.id ?? '',
119
+ messages: {
120
+ notFound: (c) => t('errors.notFound.project', undefined, c),
121
+ forbidden: (c) => t('auth.forbidden', undefined, c),
122
+ invalidBody: (c) => t('errors.validation.invalidLogBody', undefined, c),
123
+ remoteUnavailable: (c) => t('errors.unavailable.remoteProject', undefined, c),
124
+ },
125
+ sessionManager,
126
+ eventBus,
127
+ }));
64
128
  // ADR-091 (этап 2): портативный экспорт/импорт проекта (скачать/загрузить архив).
65
129
  // Managed RBAC: скачивание — право чтения проекта (owner/участник/LEAD/ADMIN),
66
130
  // импорт в существующий проект (`mergeInto`) — право редактирования; создание
@@ -124,7 +188,7 @@ export function mountBackendRoutes(app, auth, ctx) {
124
188
  },
125
189
  // Этап 1 roadmap 0.13 (блок 3): сервис «вопрос пользователю» (`ask_user`).
126
190
  deps.questionService,
127
- // ADR-114: сервис worktree'ов — привязка сессии к worktree
191
+ // ADR-114: сервис worktree — привязка сессии к worktree
128
192
  // (`PATCH /api/v2/sessions/:id { worktreeId }`).
129
193
  deps.worktreeService,
130
194
  // ADR-115: вложения сообщений — blob-порт, учёт ссылок; лимиты читаются
@@ -166,7 +230,38 @@ export function mountBackendRoutes(app, auth, ctx) {
166
230
  }
167
231
  return model ? model.enabled !== false : undefined;
168
232
  },
169
- }));
233
+ },
234
+ // Лимит тяжёлых операций ресурса сессий (`limits.sessionOpsPerMinute`) —
235
+ // live-геттер: резолвится на каждый запрос (0 — без лимита).
236
+ () => deps.sessionOpsPerMinuteSettings.getValue(),
237
+ // PROP-135 Ф6a: каталог профилей — валидация `settings.executorProfile`.
238
+ executionProfiles,
239
+ // PROP-135 (браузерный контур): каталог браузерных профилей сессии.
240
+ browserProfiles,
241
+ // ADR-126 §4: сниппеты (`#`) — раскрытие в приёме промпта (до очереди).
242
+ snippetService,
243
+ // Рабочий каталог проекта — project-уровень сниппетов. Резолв тот же,
244
+ // что у snippet-routes (относительный workspace — от `workspacesRoot`).
245
+ async (projectId) => {
246
+ const project = await projectStore.load(projectId);
247
+ if (!project?.workspace)
248
+ return undefined;
249
+ return isAbsolute(project.workspace)
250
+ ? normalize(project.workspace)
251
+ : resolve(config.workspacesRoot, project.workspace);
252
+ },
253
+ // ADR-126 §5: реестр скриптов проекта (`!`-запуск) — контур
254
+ // `/api/v2/sessions/:id/scripts*` (внутри сессий — под prefix-guard'ом).
255
+ deps.scriptService,
256
+ // Правила прав инстанса — fallback для `permission.rules.script`.
257
+ config.synth.permission,
258
+ // ADR-136: журнал исполнений — запись `script.run` (только метаданные).
259
+ deps.commandAuditLog,
260
+ // ADR-126 §5: реестр скриптов для сессии без проекта — default workspace.
261
+ defaultWorkingDir,
262
+ // PROP-141 (Часть D): сервис переноса сессии между проектами (единый шов:
263
+ // блокеры, согласие `move_consent`, порядок эффектов).
264
+ deps.moveService));
170
265
  // Messages routes
171
266
  app.route('/api/v2/messages', createMessageRoutes(auth, sessionManager, contextOptimizer, eventBus, projectStore,
172
267
  // ADR-115: удаление сообщения снимает ссылки на объекты вложений.
@@ -174,11 +269,20 @@ export function mountBackendRoutes(app, auth, ctx) {
174
269
  // Queue routes
175
270
  app.route('/api/v2/queue', createQueueRoutes(auth, sessionManager, queueManager, eventBus, processMessage, projectStore,
176
271
  // ADR-036: обфускация user-сообщения при /queue/:sessionId/steer.
177
- (sessionId, message) => orchestrator.obfuscateUserMessageForHistory(sessionId, message)));
272
+ (sessionId, message) => orchestrator.obfuscateUserMessageForHistory(sessionId, message),
273
+ // ADR-111 §detach: вклинивание из очереди — вмешательство пользователя,
274
+ // поэтому блокирующие прогоны сессии уходят в фон (как steer в prompt-роуте).
275
+ // Гейт `background.enabled` читается живым геттером оркестратора.
276
+ ({ sessionId, enabled, reason }) => autoDetachOnSteer({
277
+ orchestrator,
278
+ sessionId,
279
+ enabled: enabled ?? orchestrator.isBackgroundEnabled?.(),
280
+ reason: reason ?? 'message',
281
+ eventBus,
282
+ })));
178
283
  // FS routes (ADR-075): core-фабрика, managed поверх workspace проекта.
179
284
  // ADR-089 (P0): доступ к проекту обязателен — иначе любой USER читал/писал бы
180
285
  // файлы чужого проекта по id (IDOR). Чтение — canRead, мутации — canEditContent.
181
- const projectAccess = createProjectAccess(auth);
182
286
  app.route('/api/v2/fs', createFsRoutes(auth, config.workspacesRoot, undefined, {
183
287
  requireProjectId: true,
184
288
  getOutsideRootPolicy: () => 'deny',
@@ -234,13 +338,23 @@ export function mountBackendRoutes(app, auth, ctx) {
234
338
  setDefaultModel: (pair) => settingsStore.setDefaultModel(pair),
235
339
  }));
236
340
  // Agents routes
237
- // ADR-046/ADR-089: ролевой промпт агента (`role_prompt` в теле POST)
341
+ // ADR-126/ADR-089: ролевой промпт агента (`role_prompt` в теле POST)
238
342
  // пишется портом файлов контекста — `{dataDir}/context/roles/<contextFile>`.
239
- app.route('/api/v2/agents', createAgentRoutes(auth, agentStore, agentRegistry, getDefaultAgentId, contextConfig));
240
- // Context routes (глобальные identity-файлы; админ-мутации)
241
- app.route('/api/v2/context', createContextFileRoutes(auth, contextConfig));
343
+ // PROP-135 Ф6a: каталог профилей — проверка `executor_profile`/`allowed_profiles`.
344
+ app.route('/api/v2/agents', createAgentRoutes(auth, agentStore, agentRegistry, getDefaultAgentId, contextConfig, executionProfiles, browserProfiles));
345
+ // Context routes (файлы контекста/промптов инстанца; админ-мутации) — core-фабрика.
346
+ app.route('/api/v2/context', createContextFileRoutes(auth, contextConfig, {
347
+ adminGuard: auth.requireAdmin,
348
+ messages: {
349
+ fileNotFound: (c) => t('errors.notFound.file', undefined, c),
350
+ expectedFilesArray: (c) => t('errors.validation.expectedFilesArray', undefined, c),
351
+ },
352
+ }));
242
353
  // User admin routes
243
- app.route('/api/v2/users', createUserRoutes(auth, profilesStore));
354
+ // ADR-140 Ф2: `GET /api/v2/users/groups` — каталог групп из allowlist
355
+ // `auth.oidc.groups.allow` (env `SYNTH_OIDC_GROUPS_ALLOW` перекрывает конфиг;
356
+ // пустой allowlist → групп нет, fail-closed).
357
+ app.route('/api/v2/users', createUserRoutes(auth, profilesStore, { groups: config.auth.oidc?.groups?.allow ?? [] }));
244
358
  // Git routes (ADR-076 §T4): core-фабрика + managed RBAC. Write-эндпоинты
245
359
  // (init/clone/register/remove/fetch) требуют прав на изменение контента
246
360
  // проекта (owner/EDITOR/LEAD/ADMIN); read-only (scan/log/commit) — права
@@ -330,20 +444,56 @@ export function mountBackendRoutes(app, auth, ctx) {
330
444
  eventsDisabled: (c) => t('errors.unavailable.eventsDisabled', undefined, c),
331
445
  },
332
446
  }));
333
- // ADR-051 / ADR-089: CRUD расписаний, принудительный запуск и Job-история.
334
- // Чтение — requireAuth (дефолт core-фабрики), мутации — ADMIN. `run` —
335
- // ADMIN + rate limit (образец — ingest внешних событий): 10 запусков / 60 c
336
- // на ключ, т.к. каждый запуск ингестит событие в Router.
447
+ // ADR-051 / ADR-089 / PROP-141 (этап 5, B-1): CRUD расписаний, принудительный
448
+ // запуск и Job-история. Права — **по проекту расписания** (ADR-089 §5.5/§5.8):
449
+ // читать — владелец/участник/`LEAD`/`ADMIN`, изменять — `OWNER`/`EDITOR`/
450
+ // `LEAD`/`ADMIN` (`VIEWER` читает, но не мутирует — инвариант 21). Прежний
451
+ // `requireAdmin` на все мутации снят (PROP-141, решение владельца 2026-11-17).
452
+ // Проверка — граничная (инвариант 16): `authorizeProject`/`listVisibleProjectIds`
453
+ // из `routes/schedules.ts` (тот же `createProjectAccess`, что у процессов).
454
+ // `run` — `requireAuth` + rate limit (образец — ingest внешних событий):
455
+ // 10 запусков / 60 c на ключ, т.к. каждый запуск ингестит событие в Router.
456
+ const scheduleAccess = createBackendScheduleAccess({ auth, projectStore });
337
457
  app.route('/api/v2/schedules', createSchedulerRoutes(auth, { scheduleStore, scheduler: schedulerService, jobStore }, {
338
- writeGuard: auth.requireAdmin,
339
- runGuard: auth.requireAdmin,
458
+ writeGuard: auth.requireAuth,
459
+ runGuard: auth.requireAuth,
340
460
  runMiddleware: [createRateLimiter(10, 60_000)],
341
461
  // ADR-052 (этап I): scope-гейт, проектная проекция и резолвинг
342
462
  // projectId `bound`/`queue`-целей расписания.
343
463
  scopeGuard,
344
464
  serviceProjectProjection,
345
465
  resolveSessionProject: async (id) => (await sessionManager.getSession(id))?.projectId,
466
+ // PROP-141 (этап 5): права — по проекту расписания; список ограничен
467
+ // видимыми проектами и собственными расписаниями.
468
+ authorizeProject: scheduleAccess.authorizeProject,
469
+ listVisibleProjectIds: scheduleAccess.listVisibleProjectIds,
346
470
  }));
471
+ // PROP-141 (этап 5, B-2): HTTP-контур таймеров и будильников
472
+ // (`/api/v2/timers`). Права — **по проекту таймера** (ADR-089 §5.5/§5.8):
473
+ // читать — владелец/участник/`LEAD`/`ADMIN`, изменять — `OWNER`/`EDITOR`/
474
+ // `LEAD`/`ADMIN` (`VIEWER` читает, но не мутирует — инвариант 21). Проверка —
475
+ // граничная (инвариант 16): `authorizeProject`/`listVisibleProjectIds` из
476
+ // `routes/project-access.ts` (общий хелпер с расписаниями — правило одно).
477
+ // Мутации — под rate limit 10/60 c (как принудительный запуск расписания).
478
+ // Движок не создан в деградированном режиме хранилища — тогда контура нет.
479
+ if (deps.timerService) {
480
+ const timerAccess = createBackendProjectAccess({ auth, projectStore });
481
+ app.route('/api/v2/timers', createTimerRoutes(auth, {
482
+ timerService: deps.timerService,
483
+ timers: deps.storageContext.timers,
484
+ firings: deps.storageContext.timerFirings,
485
+ }, {
486
+ writeGuard: auth.requireAuth,
487
+ writeMiddleware: [createRateLimiter(10, 60_000)],
488
+ // ADR-052 (этап I): scope-гейт service-key и проектная проекция.
489
+ scopeGuard,
490
+ serviceProjectProjection,
491
+ // Проект таймера выводится из сессии (инстансных автоматизаций нет).
492
+ resolveSessionProject: async (id) => (await sessionManager.getSession(id))?.projectId,
493
+ authorizeProject: timerAccess.authorizeProject,
494
+ listVisibleProjectIds: timerAccess.listVisibleProjectIds,
495
+ }));
496
+ }
347
497
  // ADR-051/ADR-100: API пайплайнов — определения (ставит установщик пакета),
348
498
  // экземпляры и ручной запуск. Чтение — ADMIN (реестр автоматов инстанса),
349
499
  // ручной запуск — ADMIN или service-key со scope `automation:install`.
@@ -410,6 +560,35 @@ export function mountBackendRoutes(app, auth, ctx) {
410
560
  background: deps.backgroundService,
411
561
  processes: deps.processService,
412
562
  sessionManager,
563
+ // ADR-111 §detach: блокирующие (foreground) прогоны видны во вкладке
564
+ // «Процессы» и останавливаются отдельно. Seam'ы читают **живой**
565
+ // реестр оркестратора (ленивый геттер, не снимок).
566
+ getBlocking: (sessionIds) => orchestrator.activeRuns
567
+ .listForSessions(sessionIds)
568
+ .filter((run) => !!run.sessionId)
569
+ .map((run) => toBlockingRunDto(run)),
570
+ stopBlocking: async (sessionIds, id) => {
571
+ const run = orchestrator.activeRuns.find(sessionIds, id);
572
+ if (typeof run?.stop !== 'function')
573
+ return false;
574
+ await run.stop();
575
+ return true;
576
+ },
577
+ readBlockingLog: async (sessionIds, id, logOpts) => {
578
+ const run = orchestrator.activeRuns.find(sessionIds, id);
579
+ if (!run?.logPath || !deps.processService)
580
+ return null;
581
+ const segment = await deps.processService.readLogAtPath(run.logPath, logOpts);
582
+ if (!segment)
583
+ return null;
584
+ return {
585
+ output: segment.content,
586
+ truncated: segment.truncated === true,
587
+ logPath: run.logPath,
588
+ size: segment.totalBytes,
589
+ nextOffset: segment.nextOffset,
590
+ };
591
+ },
413
592
  }, {
414
593
  isAllowed: createBackendProcessAccess({ auth, projectStore }),
415
594
  resolveUserId: async (c) => (await auth.getCurrentUser(c))?.id ?? '',
@@ -426,6 +605,26 @@ export function mountBackendRoutes(app, auth, ctx) {
426
605
  },
427
606
  }));
428
607
  }
608
+ // PROP-132 (Ф3б): HTTP-контур интерактивных терминалов
609
+ // (`/api/v2/terminals*`): список, создание, снимок, правка, закрытие,
610
+ // вывод (снимок + NDJSON-поток), ввод и размер. Права — **по правилам
611
+ // проекта** (ADR-089 §5.5/§5.8): чтение — `canReadProject`, мутации —
612
+ // `canEditProjectContent` (`VIEWER` читает, но не мутирует — инвариант 21);
613
+ // проверка — граничные guard'ы фабрики (инвариант 16), в обработчиках её нет.
614
+ //
615
+ // Сервис терминалов собирается в `deps.ts` (Ф3в): один экземпляр на
616
+ // процесс, мастер-выключатель `terminal.enabled` (`/api/v2/settings/terminal`)
617
+ // и остановка на graceful shutdown — там.
618
+ app.route('/api/v2/terminals', createTerminalRoutes({ requireAuth: auth.requireAuth }, {
619
+ terminal: deps.terminalService,
620
+ projects: { load: (id) => projectStore.load(id) },
621
+ sessions: { getSession: (id) => sessionManager.getSession(id) },
622
+ }, {
623
+ getCurrentUserId: async (c) => (await auth.getCurrentUser(c))?.id ?? '',
624
+ canReadProject: async (c, project, userId) => projectAccess.canReadProject(c, project, userId),
625
+ canEditProjectContent: async (c, project, userId) => projectAccess.canEditProjectContent(c, project, userId),
626
+ workspacesRoot: config.workspacesRoot,
627
+ }));
429
628
  // ADR-086 §5: установка пакетов расширений (скиллы/MCP/агенты/пайплайны) и
430
629
  // реестр установок. Managed RBAC: установка — ADMIN или service-key со
431
630
  // scope `automation:install`; одобрение и снятие — **только ADMIN** (снимают
@@ -546,6 +745,19 @@ export function mountBackendRoutes(app, auth, ctx) {
546
745
  readGuard: auth.requirePermission('ADMIN'),
547
746
  writeGuard: auth.requirePermission('ADMIN'),
548
747
  }));
748
+ // Лимит тяжёлых операций с сессиями (`limits.sessionOpsPerMinute`):
749
+ // instance-wide, `0` — без лимита; лимитеры читают резолвер на каждый запрос,
750
+ // поэтому runtime-настройка применяется без рестарта. Managed — ADMIN.
751
+ app.route('/api/v2/settings', createRequestLimitsSettingsRoutes({ requireAuth: auth.requireAuth }, {
752
+ settingsStore,
753
+ config: config.synth.limits.sessionOpsPerMinute,
754
+ live: deps.sessionOpsPerMinuteSettings,
755
+ securityAudit,
756
+ env: process.env,
757
+ }, {
758
+ readGuard: auth.requirePermission('ADMIN'),
759
+ writeGuard: auth.requirePermission('ADMIN'),
760
+ }));
549
761
  // Дефолты оптимизации контекста для новых сессий (`context.defaults`):
550
762
  // instance-wide, применяются при создании сессии. Managed RBAC — ADMIN
551
763
  // (чтение и запись): это настройка инстанса.
@@ -570,6 +782,32 @@ export function mountBackendRoutes(app, auth, ctx) {
570
782
  readGuard: auth.requirePermission('ADMIN'),
571
783
  writeGuard: auth.requirePermission('ADMIN'),
572
784
  }));
785
+ // PROP-124: режим инстанса для SSH-ключей (`ssh.mode`): `tools`|`agent`.
786
+ // Runtime-override, применяется сразу. Managed RBAC — ADMIN (чтение и
787
+ // запись): это настройка инстанса.
788
+ app.route('/api/v2/settings', createSshSettingsRoutes({ requireAuth: auth.requireAuth }, {
789
+ settingsStore,
790
+ config: config.synth.ssh?.mode,
791
+ live: deps.sshModeSettings,
792
+ securityAudit,
793
+ env: process.env,
794
+ }, {
795
+ readGuard: auth.requirePermission('ADMIN'),
796
+ writeGuard: auth.requirePermission('ADMIN'),
797
+ }));
798
+ // Этап 1 roadmap 0.13 (блок 4): настройки секции `background` (реестр фоновых
799
+ // прогонов) — тумблер, лимиты, предел лога, retention. Применяются **сразу**
800
+ // (сервисы и pruner'ы читают живой резолвер). Managed RBAC — ADMIN.
801
+ app.route('/api/v2/settings', createBackgroundSettingsRoutes({ requireAuth: auth.requireAuth }, {
802
+ settingsStore,
803
+ config: config.synth.background,
804
+ live: deps.backgroundSettings,
805
+ securityAudit,
806
+ env: process.env,
807
+ }, {
808
+ readGuard: auth.requirePermission('ADMIN'),
809
+ writeGuard: auth.requirePermission('ADMIN'),
810
+ }));
573
811
  // ADR-115: staging-загрузка без сессии — `POST /api/v2/attachments`
574
812
  // (шлюзы принимают файл из внешнего канала, пайплайны — из шага). Managed:
575
813
  // `requireAuth` + scope-гейт service-key `events:ingest` (у шлюзов он уже
@@ -765,6 +1003,9 @@ export function mountBackendRoutes(app, auth, ctx) {
765
1003
  // MCP routes (единый реестр; legacy /servers — адаптеры над ним)
766
1004
  app.route('/api/v2/mcp', createMcpRoutes(auth, mcpManager, sessionManager, {
767
1005
  registry: mcpRegistryStore,
1006
+ // Переподключение сервера (`POST /servers/:name/reconnect`) — снять и
1007
+ // заново зарегистрировать MCP-инструменты в общем реестре.
1008
+ toolRegistry,
768
1009
  // Политика резолвится на каждый запрос (live; исключения/режим — из стора).
769
1010
  getNetworkPolicy: () => egressResolver.resolveMcp(),
770
1011
  // ADR-105 (Ф3): порт слоя внешних доступов — право привязать доступ
@@ -829,7 +1070,7 @@ export function mountBackendRoutes(app, auth, ctx) {
829
1070
  await syncMcpManagerFromRegistry(mcpManager, deps.mcpRegistryStore);
830
1071
  },
831
1072
  }));
832
- // Скиллы (ADR-046 §9.1/§9.2): core-фабрика + RBAC ADMIN на запись.
1073
+ // Скиллы (ADR-126 §9): core-фабрика + RBAC ADMIN на запись.
833
1074
  app.route('/api/v2/skills', createSkillRoutes(auth, {
834
1075
  skillService,
835
1076
  resolveProjectWorkspace: async (projectId) => {
@@ -841,7 +1082,27 @@ export function mountBackendRoutes(app, auth, ctx) {
841
1082
  : resolve(config.workspacesRoot, project.workspace);
842
1083
  },
843
1084
  }, { writeGuard: requireAdminOrScope('addons:install') }));
844
- // ADR-046 §7/§9.1: команды и bundles (mirror core, мутации — ADMIN).
1085
+ // ADR-126 §4: сниппеты (`#`) — core-фабрика. Права: инстанс-уровень —
1086
+ // ADMIN (`writeGuard`), user-уровень — только свой, проектный — право
1087
+ // изменения содержимого проекта (`OWNER`/`EDITOR`, инвариант 21).
1088
+ app.route('/api/v2/snippets', createSnippetRoutes(auth, {
1089
+ snippetService,
1090
+ projectStore,
1091
+ resolveProjectWorkspace: async (projectId) => {
1092
+ const project = await projectStore.load(projectId);
1093
+ if (!project?.workspace)
1094
+ return undefined;
1095
+ return isAbsolute(project.workspace)
1096
+ ? normalize(project.workspace)
1097
+ : resolve(config.workspacesRoot, project.workspace);
1098
+ },
1099
+ }, {
1100
+ writeGuard: auth.requireAdmin,
1101
+ resolveUserId: async (c) => (await auth.getCurrentUser(c))?.id ?? '',
1102
+ canReadProject: (c, project, userId) => projectAccess.canReadProject(c, project, userId),
1103
+ canEditProject: (c, project, userId) => projectAccess.canEditProjectContent(c, project, userId),
1104
+ }));
1105
+ // ADR-126 §1/§14: команды и bundles (mirror core, мутации — ADMIN); скиллов в каталоге нет.
845
1106
  app.route('/api/v2/commands', createCommandRoutes(auth, {
846
1107
  commandService,
847
1108
  resolveProjectWorkspace: async (projectId) => {
@@ -864,7 +1125,7 @@ export function mountBackendRoutes(app, auth, ctx) {
864
1125
  return missing;
865
1126
  },
866
1127
  }, { writeGuard: auth.requireAdmin }));
867
- // ADR-046 §4.5: scope-API скиллов. Доступ к сессии — та же семантика, что у
1128
+ // ADR-126 §11: scope-API скиллов. Доступ к сессии — та же семантика, что у
868
1129
  // `createSessionRoutes` (единая точка истины на ресурс сессии): владелец|ADMIN
869
1130
  // (`canAccess`), участник проекта (`resolveCanAccessExtra`), сквозной обзор
870
1131
  // ADMIN/LEAD (`resolveElevated`); проект — owner/LEAD/ADMIN.
@@ -880,6 +1141,12 @@ export function mountBackendRoutes(app, auth, ctx) {
880
1141
  sessionManager, skillService, settingsStore, projectStore,
881
1142
  permissionConfig: config.synth.permission,
882
1143
  resolveProjectWorkspace: resolveSkillWorkspace,
1144
+ // ADR-126 §10: capability-гейт сессии — по capabilities её агента
1145
+ // (legacy-роль резолвится алиасом, как в рантайме оркестратора).
1146
+ resolveAgentCapabilities: (role) => {
1147
+ const resolved = role ? (resolveAgentRoleAlias(role) ?? role) : undefined;
1148
+ return resolved ? agentRegistry.get(resolved)?.capabilities : undefined;
1149
+ },
883
1150
  }, {
884
1151
  writeGuard: auth.requireAuth,
885
1152
  resolveUserId: async (c) => (await auth.getCurrentUser(c))?.id ?? '',
@@ -908,7 +1175,7 @@ export function mountBackendRoutes(app, auth, ctx) {
908
1175
  permissionConfig: config.synth.permission,
909
1176
  resolveProjectWorkspace: resolveSkillWorkspace,
910
1177
  }, {
911
- // ADR-046 §4.5: проектным уровнем управляют owner/LEAD/ADMIN — как в
1178
+ // ADR-126 §11: проектным уровнем управляют owner/LEAD/ADMIN — как в
912
1179
  // project-MCP (`canManageProjectMcp`), поэтому writeGuard не requireAdmin;
913
1180
  // владение проверяет canAccessProject (403 не-членам, 404 — нет проекта).
914
1181
  writeGuard: auth.requireAuth,
@@ -918,7 +1185,10 @@ export function mountBackendRoutes(app, auth, ctx) {
918
1185
  || project.ownerId === userId
919
1186
  || project.members?.[userId] === ProjectRole.OWNER,
920
1187
  }));
921
- app.route('/api/v2/settings', createSkillSettingsRoutes(auth, { settingsStore }, {
1188
+ app.route('/api/v2/settings', createSkillSettingsRoutes(auth, {
1189
+ settingsStore,
1190
+ trustedProjectDirsDefaults: config.synth.skills.trustedProjectDirs ?? [],
1191
+ }, {
922
1192
  writeGuard: auth.requireAdmin,
923
1193
  onSkillsDisabledChange: (disabled) => orchestrator.setSkillsDisabled(disabled),
924
1194
  }));
@@ -949,22 +1219,40 @@ export function mountBackendRoutes(app, auth, ctx) {
949
1219
  unauthorized: (c) => t('auth.unauthorized', undefined, c),
950
1220
  },
951
1221
  }));
952
- // LLM Gateway audit routes (ADR-036) — GET только ADMIN/AUDITOR, POST /revealed — все авторизованные
1222
+ // LLM Gateway audit routes (ADR-036) — GET только ADMIN/AUDITOR, POST /revealed — все авторизованные.
1223
+ // Одна core-фабрика на весь префикс `/api/v2/audit`: голый аудит Gateway (`/`),
1224
+ // `POST /revealed`, журнал безопасности (`/security`) и журнал egress (`/egress`).
953
1225
  app.route('/api/v2/audit', createAuditRoutes(auth, {
954
- auditLogPath: gatewayAuditLogger.logPath,
955
- sessionExists: async (sessionId) => {
956
- const session = await sessionManager.getSession(sessionId);
957
- return session !== null;
1226
+ securityAudit,
1227
+ egressRequests,
1228
+ // PROP-136 (слайс 136a): журнал исполнений команд (`/audit/commands`).
1229
+ commandAudit: commandAuditLog,
1230
+ gatewayAudit: {
1231
+ auditLogPath: gatewayAuditLogger.logPath,
1232
+ sessionExists: async (sessionId) => {
1233
+ const session = await sessionManager.getSession(sessionId);
1234
+ return session !== null;
1235
+ },
1236
+ logger: gatewayAuditLogger,
958
1237
  },
959
- logger: gatewayAuditLogger,
1238
+ }, {
1239
+ readGuard: auth.requirePermission('ADMIN', 'AUDITOR'),
1240
+ gatewayReadGuard: auth.requirePermission('ADMIN', 'AUDITOR'),
1241
+ revealedGuard: auth.requireAuth,
1242
+ // Retention-очистка журнала исполнений — только ADMIN (изменяет данные журнала).
1243
+ commandsAdminGuard: auth.requireAdmin,
960
1244
  }));
961
1245
  // Логи сервисов (core/ui/backend) + полный лог запросов/ответов LLM — чтение, только ADMIN/AUDITOR
962
1246
  app.route('/api/v2/logs', createLogsRoutes(auth, {
963
1247
  logDir: resolveLogDir(),
964
1248
  payloadLogPath: gatewayPayloadLogPath,
1249
+ }, {
1250
+ readGuard: auth.requirePermission('ADMIN', 'AUDITOR'),
965
1251
  }));
966
1252
  // LLM Gateway patterns routes (ADR-036) — управление regex-паттернами детекции секретов, только ADMIN
967
- app.route('/api/v2/gateway', createGatewayPatternsRoutes(auth, patternStore));
1253
+ app.route('/api/v2/gateway', createGatewayPatternsRoutes(auth, patternStore, {
1254
+ adminGuard: auth.requireAdmin,
1255
+ }));
968
1256
  // LLM Proxy (гибридный режим, Часть 5) — OpenAI-совместимый POST /api/v2/llm/chat/completions.
969
1257
  // Локальный core гоняет LLM-запросы централизованно через LLM Gateway (ADR-036):
970
1258
  // обфускация/блокировка секретов, rate limit, аудит, полный payload-лог.
@@ -1020,6 +1308,8 @@ export function mountBackendRoutes(app, auth, ctx) {
1020
1308
  // ADR-029: askTimeoutMs живёт в permission-секции конфига (не в security).
1021
1309
  askTimeoutMs: config.synth.permission?.askTimeoutMs,
1022
1310
  },
1311
+ // ADR-023: база `security.promptInjection` (config.yaml) — GET/DELETE и env-резолвер.
1312
+ fallbackPromptInjection: config.synth.security.promptInjection,
1023
1313
  // ADR-036: live-применение тумблера LLM Gateway из UI — без рестарта сервера.
1024
1314
  onLlmGatewayChange: async (runtime) => {
1025
1315
  const merged = mergeLlmGatewayConfig(config.synth.llmGateway, runtime);
@@ -1028,6 +1318,10 @@ export function mountBackendRoutes(app, auth, ctx) {
1028
1318
  // live-применение тумблера защищённых путей из UI — без рестарта сервера.
1029
1319
  onSecurityChange: async (runtime) => {
1030
1320
  const merged = mergeSecurityConfig(config.synth.security, runtime);
1321
+ if (merged) {
1322
+ // ADR-023: env `SYNTH_SECURITY_PROMPT_INJECTION_*` перекрывает runtime/config.
1323
+ merged.promptInjection = resolvePromptInjection(config.synth.security.promptInjection, runtime.promptInjection).config;
1324
+ }
1031
1325
  orchestrator.setSecurityConfig(merged);
1032
1326
  },
1033
1327
  // ADR-071 §2.3: live-применение политики встроенных инструментов из админки.
@@ -1058,6 +1352,10 @@ export function mountBackendRoutes(app, auth, ctx) {
1058
1352
  fallbackEgressWebhooks: config.synth.egress.webhooks,
1059
1353
  // ADR-099: прокси — config-уровень, runtime-override и файл пароля.
1060
1354
  fallbackProxy: config.synth.proxy,
1355
+ // ADR-135: runtime-каталог профилей исполнения — config-уровень (база) и
1356
+ // секция, с которой работает процесс (`restartRequired`).
1357
+ fallbackExecution: deps.fallbackExecutionConfig,
1358
+ getRunningExecution: () => deps.executionConfig,
1061
1359
  // ADR-099: TLS/CA — config-уровень (read-only в UI; runtime — bootstrap).
1062
1360
  fallbackTls: config.synth.security?.tls,
1063
1361
  dataDir,
@@ -1089,6 +1387,43 @@ export function mountBackendRoutes(app, auth, ctx) {
1089
1387
  // События/decision наследуют тот же guard (если не заданы отдельно).
1090
1388
  settingsWriteGuard: auth.requirePermission('ADMIN'),
1091
1389
  }));
1390
+ // ADR-133: обновления (`/api/v2/updates`) — проверка по каналам и SSE-установка.
1391
+ // Managed RBAC: проверка и применение — только ADMIN (как обслуживание инстанса).
1392
+ // Admission-гейт внутри роута: в managed/Docker/K8s self-update → 409
1393
+ // `UPDATE_UNSUPPORTED` (обновление выполняется образом/выпуском).
1394
+ app.route('/api/v2/updates', createUpdateRoutes(auth, dataDir, {
1395
+ updates: config.synth.updates,
1396
+ audit: maintenanceAudit,
1397
+ // ADR-099: дочерний npm получает доверие CA и прокси-маршрут инстанса.
1398
+ npmEnvironment: resolveNpmInstallEnvironment,
1399
+ }, {
1400
+ readGuard: auth.requirePermission('ADMIN'),
1401
+ writeGuard: auth.requirePermission('ADMIN'),
1402
+ }));
1403
+ // PROP-135 Ф6b-1: профили и пулы исполнения (`/api/v2/execution/*`).
1404
+ // Managed RBAC: каталог профилей — любой аутентифицированный (владелец проекта
1405
+ // выбирает профиль в настройках, роль у него может быть USER); список пулов —
1406
+ // ADMIN|LEAD (обзор инстанса); `drain`/`release` — только ADMIN (управление
1407
+ // ресурсами provisioner'а). Адреса и токены пулов наружу не отдаются (инвариант 13).
1408
+ app.route('/api/v2/execution', createExecutionRoutes({ requireAuth: auth.requireAuth }, {
1409
+ ...(deps.executionConfig ? { executionConfig: deps.executionConfig } : {}),
1410
+ executionRouter: deps.executionRouter,
1411
+ }, {
1412
+ profilesReadGuard: auth.requireAuth,
1413
+ poolsReadGuard: auth.requirePermission('ADMIN', 'LEAD'),
1414
+ writeGuard: auth.requirePermission('ADMIN'),
1415
+ messages: {
1416
+ invalidKey: (c) => t('errors.validation.executionPoolKey', undefined, c),
1417
+ providerUnavailable: (c) => t('errors.unavailable.executionProvider', undefined, c),
1418
+ poolNotFound: (c, key) => `${t('errors.notFound.executionPool', undefined, c)} (${key})`,
1419
+ },
1420
+ }));
1421
+ // ADR-133: админ-раздел «Обновления» — runtime-тумблер автопроверки.
1422
+ // Managed RBAC: чтение и запись — только ADMIN.
1423
+ app.route('/api/v2/settings', createUpdatesSettingsRoutes({ requireAuth: auth.requireAuth }, { settingsStore, dataDir, config: config.synth.updates, env: process.env }, {
1424
+ readGuard: auth.requirePermission('ADMIN'),
1425
+ writeGuard: auth.requirePermission('ADMIN'),
1426
+ }));
1092
1427
  // ADR-094: админ-раздел «Наблюдаемость» — runtime `metrics.enabled` (рестарт),
1093
1428
  // live-статус и bearer-токен `/metrics` (write-only, применяется сразу).
1094
1429
  // Managed RBAC: чтение и мутации — только ADMIN.
@@ -1106,14 +1441,23 @@ export function mountBackendRoutes(app, auth, ctx) {
1106
1441
  readGuard: auth.requirePermission('ADMIN'),
1107
1442
  writeGuard: auth.requirePermission('ADMIN'),
1108
1443
  }));
1109
- // Журналы безопасности: аудит изменений политик + внешние запросы (egress).
1110
- // Managed RBAC: чтение только ADMIN/AUDITOR.
1111
- app.route('/api/v2/audit', createSecurityAuditRoutes(auth, {
1112
- securityAudit,
1113
- egressRequests,
1444
+ // PROP-132 (Ф3в): настройки терминалов — мастер-выключатель, восстановление
1445
+ // из снимков и параметры выполнения (`idleMinutes`/`maxPerProject`/
1446
+ // `maxPerInstance`/`shell`/`auditInput`). Применяются **сразу**
1447
+ // (`setEnabled`/`setAutoRestore`/`setLimits`/`setDefaultShell`/
1448
+ // `setAuditInput` — рестарт не нужен).
1449
+ // Managed RBAC: чтение и мутации — только ADMIN.
1450
+ app.route('/api/v2/settings', createTerminalSettingsRoutes({ requireAuth: auth.requireAuth }, {
1451
+ settingsStore,
1452
+ ...(config.synth.terminal ? { config: config.synth.terminal } : {}),
1453
+ terminalService: deps.terminalService,
1454
+ env: process.env,
1114
1455
  }, {
1115
- readGuard: auth.requirePermission('ADMIN', 'AUDITOR'),
1456
+ readGuard: auth.requirePermission('ADMIN'),
1457
+ writeGuard: auth.requirePermission('ADMIN'),
1116
1458
  }));
1459
+ // Журналы безопасности (аудит политик + egress) и голый аудит LLM Gateway
1460
+ // смонтированы **одной** core-фабрикой выше (префикс `/api/v2/audit`).
1117
1461
  // ADR-102 (волна 1): отчёты аналитики — только чтение, данных без локализации.
1118
1462
  // Managed RBAC (§7): ADMIN/LEAD — сквозной обзор; AUDITOR — чтение всех отчётов;
1119
1463
  // обычный USER — принудительный фильтр оси `user` по себе (+ 403 на `decision`/`summary`).
@@ -1143,7 +1487,7 @@ export function mountBackendRoutes(app, auth, ctx) {
1143
1487
  config: config.synth.instructions,
1144
1488
  dictionaryStore: dictionaries,
1145
1489
  dataDir,
1146
- trustedProjectDirs: config.synth.skills.trustedProjectDirs,
1490
+ trustedProjectDirs: deps.skillsTrustedProjectDirs,
1147
1491
  // ADR-069 R3: авто-trust workspace внутри workspacesRoot (managed-каталоги).
1148
1492
  workspacesRoot: config.workspacesRoot,
1149
1493
  // ADR-077: `git rev-parse` — через порт исполнения (тот же, что у тулов).
@@ -1169,9 +1513,24 @@ export function mountBackendRoutes(app, auth, ctx) {
1169
1513
  // ADR-118 §8: возможности инстанса (`GET /api/v2/meta`) — **без
1170
1514
  // аутентификации** (как `GET /health`): публичная информация о протоколе,
1171
1515
  // по ней клиент сверяет модель сообщений (fail-closed гейт транспорта).
1172
- app.route('/api/v2', createMetaRoutes({ getAttachments: () => deps.attachmentsSettings.getConfig() }));
1516
+ app.route('/api/v2', createMetaRoutes({
1517
+ getAttachments: () => deps.attachmentsSettings.getConfig(),
1518
+ // PROP-125: сервер гибрида умеет удалённый MCP (`/api/v2/mcp/remote/*`
1519
+ // и relay) — клиент читает признак из `/api/v2/meta`.
1520
+ // `users: true` — маршрут `/api/v2/users*` (управление пользователями)
1521
+ // смонтирован в backend (`src/routes/users.ts`), поэтому контур есть
1522
+ // всегда; в core standalone его нет, а в core в гибриде он есть лишь
1523
+ // пока подключён удалённый backend (там — прокси).
1524
+ getFeatures: () => ({ remoteMcp: true, users: true }),
1525
+ }));
1173
1526
  // Глобальный SSE-хаб для всех сессий пользователя (ADR-052: `events:watch`).
1174
1527
  registerEventsSse(app, { auth, eventHub, scopeGuard });
1175
1528
  // Admin routes (кроме graceful shutdown — он живёт в main.ts, т.к. требует server)
1176
- app.route('/api/v2/admin/debug', createDebugRoutes(auth));
1529
+ app.route('/api/v2/admin/debug', createDebugRoutes(auth, {
1530
+ adminGuard: auth.requireAdmin,
1531
+ messages: {
1532
+ groupsRequired: (c) => t('errors.validation.groupsRequired', undefined, c),
1533
+ generic: (c) => t('errors.generic', undefined, c),
1534
+ },
1535
+ }));
1177
1536
  }