@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
@@ -3,10 +3,14 @@
3
3
  // определяет приоритеты маршрутов (статические сегменты раньше параметрических,
4
4
  // SSE-хаб `/api/v2/events` после роутов событий, но до admin-роутов).
5
5
  // Вынесено из `app.ts` (ADR-095, шаг 4b) — «вынос по швам», без изменения поведения.
6
- import { isAbsolute, normalize, resolve } from 'node:path';
7
- import { DEFAULT_LLM_GATEWAY_RATE_LIMIT, ProjectRole } from '@itphx/synth-shared';
8
- import { DEFAULT_AGENT_ID, DictionaryStore, RateLimiter, getPublicOpenApiDocument, createFsRoutes, createGitRoutes, createSshKeyRoutes, createAgentSshKeyRoutes, createEventRoutes, createSchedulerRoutes, createServiceKeyRoutes, createWebhookRoutes, mergeLlmGatewayConfig, mergeSecurityConfig, createSkillRoutes, createCommandRoutes, createSkillBundleRoutes, createSessionSkillScopeRoutes, createProjectSkillScopeRoutes, createSkillSettingsRoutes, createIdentityRoutes, ProjectInstructionsResolver, createInstructionsInfoResolver, createSettingsRoutes, createDictionaryRoutes, createContextRoutes as createCoreContextRoutes, resolveProjectWorkspace, } from '@itphx/synth-core';
6
+ import { isAbsolute, join, normalize, resolve } from 'node:path';
7
+ import { randomUUID } from 'node:crypto';
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,
10
+ // ADR-115: админ-раздел «Вложения» — runtime-настройки мультимодального ввода.
11
+ createAttachmentsSettingsRoutes, createModalityModelLookup, createStagingAttachmentRoutes, AttachmentService, createPacksRoutes, createPipelinesRoutes, createPipelineProjectRoutes, createProcessRoutes, createPluginsRoutes, createPluginSettingsRoutes, createMemoryRoutes, MEMORY_PLUGIN_NAME, MemoryProviderUnavailableError, executeToolDef, createOAuthRoutes, bindCredentialToConnector, syncMcpManagerFromRegistry, resolveProjectWorkspace, resolvePluginServerPolicy, } from '@itphx/synth-core';
9
12
  import { createProjectRoutes, createProjectAccess } from '../routes/projects.js';
13
+ import { createBackendProcessAccess } from '../routes/processes.js';
10
14
  import { createSessionRoutes } from '../routes/sessions.js';
11
15
  import { createMessageRoutes } from '../routes/messages.js';
12
16
  import { createQueueRoutes } from '../routes/queue.js';
@@ -22,8 +26,8 @@ import { createLogsRoutes, resolveLogDir } from '../routes/logs.js';
22
26
  import { createGatewayPatternsRoutes } from '../routes/gateway-patterns.js';
23
27
  import { createLlmRoutes } from '../routes/llm.js';
24
28
  import { createRateLimiter } from '../middleware/rate-limiter.js';
25
- import { scopeGuard, projectGuard } from '../auth/service-scope.js';
26
- import { requireAdminOrScope } from '../auth/guards.js';
29
+ import { scopeGuard, serviceProjectProjection } from '../auth/service-scope.js';
30
+ import { requireAdminOrScope, requireAdminRoleOrScope } from '../auth/guards.js';
27
31
  import { t, getTranslations } from '../lib/i18n.js';
28
32
  import { registerEventsSse } from './sse-events.js';
29
33
  /**
@@ -31,8 +35,15 @@ import { registerEventsSse } from './sse-events.js';
31
35
  * i18n-эндпоинты) в порядке, идентичном прежнему `createBackendApp`.
32
36
  */
33
37
  export function mountBackendRoutes(app, auth, ctx) {
34
- const { config, deps, serviceApiKeyStore } = ctx;
35
- const { dataDir, projectStore, sessionManager, eventBus, queueManager, processMessage, orchestrator, profilesStore, getDefaultAgentId, requestSessionService, contextOptimizer, protectedPathsStore, providerStore, providerCache, modelStore, modelCache, agentStore, agentRegistry, contextConfig, sshKeyStore, commandService, bundleStore, eventIngress, eventBindingStore, eventJournal, routeRuleStore, eventApiKeyStore, schedulerService, scheduleStore, jobStore, webhookStore, webhookDeliveryStore, webhookService, webhooksConfig, eventHub, mcpManager, mcpRegistryStore, skillService, settingsStore, defaultWorkingDir, patternStore, toolRegistry, gatewayAuditLogger, gatewayPayloadLogPath, gatewayConfig, providerLoader, modelLoader, modelWindowLoader, resolveAgentTemplate, identityClaimStore, live, } = deps;
38
+ const { config, deps } = ctx;
39
+ 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;
40
+ /**
41
+ * Fallback-пара «модель по умолчанию» из config (`llm.defaultProvider` +
42
+ * `llm.defaultModel`) — только если заданы оба.
43
+ */
44
+ const backendConfigDefaultModel = () => config.synth.llm.defaultProvider && config.synth.llm.defaultModel
45
+ ? { provider: config.synth.llm.defaultProvider, model: config.synth.llm.defaultModel }
46
+ : null;
36
47
  // API-заглушки для UI
37
48
  app.get('/api/config/themes', (c) => c.json({ themes: [] }));
38
49
  // i18n endpoints
@@ -47,13 +58,86 @@ export function mountBackendRoutes(app, auth, ctx) {
47
58
  // публичную выдачу без auth согласуем отдельно.
48
59
  app.get('/api/v2/openapi.json', auth.requireAuth, (c) => c.json(getPublicOpenApiDocument()));
49
60
  // Projects routes
50
- app.route('/api/v2/projects', createProjectRoutes(auth, projectStore, sessionManager, config.workspacesRoot, mcpManager, skillService, settingsStore, mcpRegistryStore));
61
+ app.route('/api/v2/projects', createProjectRoutes(auth, projectStore, sessionManager, config.workspacesRoot, mcpManager, skillService, settingsStore, mcpRegistryStore, deps.worktreeService));
62
+ // ADR-091 (этап 2): портативный экспорт/импорт проекта (скачать/загрузить архив).
63
+ // Managed RBAC: скачивание — право чтения проекта (owner/участник/LEAD/ADMIN),
64
+ // импорт в существующий проект (`mergeInto`) — право редактирования; создание
65
+ // нового проекта — любая аутентифицированная роль. Владелец новых сущностей —
66
+ // текущий пользователь; хаб подписывается на импортированные сессии
67
+ // (ADR-089, инвариант 18).
68
+ app.route('/api/v2/projects', createProjectPortableRoutes({ requireAuth: auth.requireAuth }, {
69
+ dataDir,
70
+ // ADR-096: экспорт/импорт проекта работают через контекст хранения
71
+ // инстанса (иначе — свой файловый контекст, а на `backend=postgres`
72
+ // проект не найден бы).
73
+ storage: deps.storageContext,
74
+ getProject: (id) => projectStore.load(id),
75
+ canRead: async (c, projectId) => {
76
+ const user = await auth.getCurrentUser(c);
77
+ if (!user)
78
+ return false;
79
+ const project = await projectStore.load(projectId);
80
+ return project ? projectAccess.canReadProject(c, project, user.id) : false;
81
+ },
82
+ canEdit: async (c, projectId) => {
83
+ const user = await auth.getCurrentUser(c);
84
+ if (!user)
85
+ return false;
86
+ const project = await projectStore.load(projectId);
87
+ return project ? projectAccess.canEditProjectContent(c, project, user.id) : false;
88
+ },
89
+ // security-фикс 0.11.3: экспорт проекта по умолчанию БЕЗ секретов сессий
90
+ // (карта обфускации LLM Gateway + `metadata.secrets`). Явный opt-in
91
+ // `?withSecrets=true` — только elevated (ADMIN/LEAD): архив проекта
92
+ // содержит сессии других участников, а карта обфускации — это секрет.
93
+ canExportSecrets: (c) => auth.isAdmin(c) || auth.hasRole(c, 'LEAD'),
94
+ audit: maintenanceAudit,
95
+ maxUploadBytes: config.maxUploadBytes,
96
+ resolveOwnerId: (c) => {
97
+ const user = c.get('user');
98
+ return user?.id;
99
+ },
100
+ onSessionCreated: (sessionId, ownerId) => {
101
+ void eventHub.subscribeToSession(ownerId, sessionId);
102
+ },
103
+ messages: {
104
+ forbidden: (c) => t('auth.forbidden', undefined, c),
105
+ notFound: (c) => t('errors.notFound.project', undefined, c),
106
+ invalidBody: (c) => t('errors.validation.projectImportBody', undefined, c),
107
+ invalidArchive: (c) => t('errors.validation.invalidProjectArchive', undefined, c),
108
+ checksumMismatch: (c) => t('errors.validation.projectArchiveChecksum', undefined, c),
109
+ nameConflict: (c) => t('errors.conflict.projectNameInUse', undefined, c),
110
+ confirmRequired: (c) => t('errors.validation.maintenanceConfirmRequired', undefined, c),
111
+ workspaceError: (c) => t('errors.validation.projectWorkspaceRestore', undefined, c),
112
+ payloadTooLarge: (c) => t('errors.payloadTooLarge', undefined, c),
113
+ },
114
+ }));
51
115
  // Sessions routes
52
- app.route('/api/v2/sessions', createSessionRoutes(auth, sessionManager, eventBus, queueManager, processMessage, orchestrator, eventHub, contextOptimizer, projectStore, profilesStore, getDefaultAgentId, requestSessionService));
116
+ app.route('/api/v2/sessions', createSessionRoutes(auth, sessionManager, eventBus, queueManager, processMessage, orchestrator, eventHub, contextOptimizer, projectStore, profilesStore, getDefaultAgentId, requestSessionService, analytics,
117
+ // ADR-107: агрегаты памяти сессии для вкладки «Память».
118
+ {
119
+ facts: deps.storageContext.memoryFacts,
120
+ indexes: deps.storageContext.memoryIndexes,
121
+ isPluginActive: () => deps.pluginRuntime.host.isActive(MEMORY_PLUGIN_NAME),
122
+ },
123
+ // Этап 1 roadmap 0.13 (блок 3): сервис «вопрос пользователю» (`ask_user`).
124
+ deps.questionService,
125
+ // ADR-114: сервис worktree'ов — привязка сессии к worktree
126
+ // (`PATCH /api/v2/sessions/:id { worktreeId }`).
127
+ deps.worktreeService,
128
+ // ADR-115: вложения сообщений — blob-порт, учёт ссылок; лимиты читаются
129
+ // резолвером на каждый запрос (runtime-настройки из админки без рестарта).
130
+ {
131
+ blobs: deps.storageContext.blobs,
132
+ blobRefs: deps.storageContext.blobRefs,
133
+ config: () => deps.attachmentsSettings.getConfig(),
134
+ }));
53
135
  // Messages routes
54
- app.route('/api/v2/messages', createMessageRoutes(auth, sessionManager, contextOptimizer, eventBus));
136
+ app.route('/api/v2/messages', createMessageRoutes(auth, sessionManager, contextOptimizer, eventBus, projectStore,
137
+ // ADR-115: удаление сообщения снимает ссылки на объекты вложений.
138
+ deps.storageContext.blobRefs));
55
139
  // Queue routes
56
- app.route('/api/v2/queue', createQueueRoutes(auth, sessionManager, queueManager, eventBus, processMessage));
140
+ app.route('/api/v2/queue', createQueueRoutes(auth, sessionManager, queueManager, eventBus, processMessage, projectStore));
57
141
  // FS routes (ADR-075): core-фабрика, managed поверх workspace проекта.
58
142
  // ADR-089 (P0): доступ к проекту обязателен — иначе любой USER читал/писал бы
59
143
  // файлы чужого проекта по id (IDOR). Чтение — canRead, мутации — canEditContent.
@@ -62,6 +146,8 @@ export function mountBackendRoutes(app, auth, ctx) {
62
146
  requireProjectId: true,
63
147
  getOutsideRootPolicy: () => 'deny',
64
148
  getProtectedPathsPolicy: () => protectedPathsStore.getPolicy(),
149
+ // Лимит загрузки: config/env (resolveMaxUploadBytes), иначе дефолт фабрики.
150
+ maxUploadBytes: config.maxUploadBytes,
65
151
  authorizeProject: async (c, projectId) => {
66
152
  const user = await auth.getCurrentUser(c);
67
153
  if (!user)
@@ -81,20 +167,32 @@ export function mountBackendRoutes(app, auth, ctx) {
81
167
  }),
82
168
  }));
83
169
  // Providers routes
84
- app.route('/api/v2/providers', createProviderRoutes(auth, providerStore, providerCache));
170
+ app.route('/api/v2/providers', createProviderRoutes(auth, providerStore, providerCache, {
171
+ resolvePolicy: () => egressResolver.resolveTools(),
172
+ log: currentEgressLog(),
173
+ }, async () => (await settingsStore.getDefaultModel()) ?? backendConfigDefaultModel()));
85
174
  // Models routes
86
- app.route('/api/v2/models', createModelRoutes(auth, modelStore, providerStore, modelCache, providerCache));
175
+ app.route('/api/v2/models', createModelRoutes(auth, modelStore, providerStore, modelCache, providerCache, {
176
+ getDefaultModel: async () => (await settingsStore.getDefaultModel()) ?? backendConfigDefaultModel(),
177
+ setDefaultModel: (pair) => settingsStore.setDefaultModel(pair),
178
+ }));
87
179
  // Agents routes
88
- app.route('/api/v2/agents', createAgentRoutes(auth, agentStore, agentRegistry, getDefaultAgentId));
180
+ // ADR-046/ADR-089: ролевой промпт агента (`role_prompt` в теле POST)
181
+ // пишется портом файлов контекста — `{dataDir}/context/roles/<contextFile>`.
182
+ app.route('/api/v2/agents', createAgentRoutes(auth, agentStore, agentRegistry, getDefaultAgentId, contextConfig));
89
183
  // Context routes (глобальные identity-файлы; админ-мутации)
90
184
  app.route('/api/v2/context', createContextFileRoutes(auth, contextConfig));
91
185
  // User admin routes
92
186
  app.route('/api/v2/users', createUserRoutes(auth, profilesStore));
93
187
  // Git routes (ADR-076 §T4): core-фабрика + managed RBAC. Write-эндпоинты
94
188
  // (init/clone/register/remove/fetch) требуют прав на изменение контента
95
- // проекта (owner/EDITOR/LEAD/ADMIN); read-only (scan/log/commit) — requireAuth.
189
+ // проекта (owner/EDITOR/LEAD/ADMIN); read-only (scan/log/commit) — права
190
+ // чтения проекта (owner/участник/LEAD/ADMIN). Проверка — граничный guard
191
+ // core-фабрики (ADR-089, инвариант 16): без неё любой аутентифицированный
192
+ // читал бы git-данные чужого проекта по его id.
96
193
  app.route('/api/v2/git', createGitRoutes(auth, projectStore, config.workspacesRoot, {
97
194
  sshKeyStore,
195
+ execution: deps.executionPort,
98
196
  authorizeProject: async (c, projectId) => {
99
197
  const user = await auth.getCurrentUser(c);
100
198
  if (!user)
@@ -104,6 +202,15 @@ export function mountBackendRoutes(app, auth, ctx) {
104
202
  return false;
105
203
  return projectAccess.canEditProjectContent(c, project, user.id);
106
204
  },
205
+ authorizeRead: async (c, projectId) => {
206
+ const user = await auth.getCurrentUser(c);
207
+ if (!user)
208
+ return false;
209
+ const project = await projectStore.load(projectId);
210
+ if (!project)
211
+ return false;
212
+ return projectAccess.canReadProject(c, project, user.id);
213
+ },
107
214
  }));
108
215
  // SSH-ключи агентов (ADR-076 §T5): core-фабрика + managed RBAC.
109
216
  // Ключи — секреты: чтение — requireAuth (глобально), запись — только ADMIN.
@@ -128,7 +235,7 @@ export function mountBackendRoutes(app, auth, ctx) {
128
235
  keyReadGuard: auth.requirePermission('ADMIN', 'LEAD'),
129
236
  // ADR-052 (этап I): scope-гейт и проектная проекция service-key (i18n-403).
130
237
  scopeGuard,
131
- projectGuard,
238
+ serviceProjectProjection,
132
239
  // ADR-089/ADR-052: per-key rate limit и мастер-выключатель приёма (live).
133
240
  getKeyRateLimitPerMinute: () => live.getEvents().keyRateLimitPerMinute,
134
241
  isEnabled: () => live.getEvents().enabled,
@@ -170,9 +277,282 @@ export function mountBackendRoutes(app, auth, ctx) {
170
277
  // ADR-052 (этап I): scope-гейт, проектная проекция и резолвинг
171
278
  // projectId `bound`/`queue`-целей расписания.
172
279
  scopeGuard,
173
- projectGuard,
280
+ serviceProjectProjection,
174
281
  resolveSessionProject: async (id) => (await sessionManager.getSession(id))?.projectId,
175
282
  }));
283
+ // ADR-051/ADR-100: API пайплайнов — определения (ставит установщик пакета),
284
+ // экземпляры и ручной запуск. Чтение — ADMIN (реестр автоматов инстанса),
285
+ // ручной запуск — ADMIN или service-key со scope `automation:install`.
286
+ app.route('/api/v2/pipelines', createPipelinesRoutes({ requireAuth: auth.requireAuth }, { pipelines }, {
287
+ readGuard: auth.requirePermission('ADMIN'),
288
+ writeGuard: requireAdminRoleOrScope('automation:install'),
289
+ scopeGuard,
290
+ }));
291
+ // ADR-101 (Э6): пайплайны проекта (черновик/публикация), прогоны и журнал,
292
+ // HITL-действия и шаблоны инстанса (инстанцирование в проект).
293
+ // Права — по правилам проекта (ADR-089 §5.5/§5.8): читать — владелец/
294
+ // участник/LEAD/ADMIN, изменять — OWNER/EDITOR/LEAD/ADMIN (VIEWER читает,
295
+ // но не мутирует — инвариант 21). Шаблоны инстанса — ADMIN.
296
+ app.route('/api/v2', createPipelineProjectRoutes({ requireAuth: auth.requireAuth }, {
297
+ pipelines: deps.storageContext.projectPipelines,
298
+ runs: deps.storageContext.pipelineRuns,
299
+ engine: deps.pipelineEngine,
300
+ projects: projectStore,
301
+ templates: pipelines,
302
+ // ADR-101: общий реестр активных прогонов (soft-lock + отмена) —
303
+ // тот же экземпляр, что у встроенных тулов агента.
304
+ runControl: deps.pipelineRunControl,
305
+ // ADR-116: раздача артефактов прогона (blob-порт) — тот же store, что у
306
+ // выхода `file` движка пайплайнов (без него route всегда 404).
307
+ artifacts: deps.pipelineArtifacts,
308
+ // ADR-115 × ADR-101: вложения прогона — проверка ссылок в теле запуска
309
+ // (тот же сервис вложений, что у приёма событий) и учёт в `blob_refs`.
310
+ attachments: deps.pipelineAttachments,
311
+ blobRefs: deps.storageContext.blobRefs,
312
+ }, {
313
+ writeGuard: auth.requireAuth,
314
+ adminGuard: auth.requirePermission('ADMIN'),
315
+ canReadProject: async (c, project, userId) => projectAccess.canReadProject(c, project, userId),
316
+ canEditProject: async (c, project, userId) => projectAccess.canEditProjectContent(c, project, userId),
317
+ getCurrentUserId: async (c) => (await auth.getCurrentUser(c))?.id ?? '',
318
+ scopeGuard,
319
+ serviceProjectProjection,
320
+ messages: {
321
+ pipelineNotFound: (c) => t('errors.notFound.pipeline', undefined, c),
322
+ runNotFound: (c) => t('errors.notFound.pipelineRun', undefined, c),
323
+ projectNotFound: (c) => t('errors.notFound.project', undefined, c),
324
+ templateNotFound: (c) => t('errors.notFound.pipelineTemplate', undefined, c),
325
+ forbidden: (c) => t('auth.forbidden', undefined, c),
326
+ invalidBody: (c) => t('errors.validation.invalidPipelineBody', undefined, c),
327
+ invalidSpec: (c) => t('errors.validation.invalidPipelineSpec', undefined, c),
328
+ notPublished: (c) => t('errors.conflict.pipelineNotPublished', undefined, c),
329
+ invalidState: (c) => t('errors.conflict.pipelineInvalidState', undefined, c),
330
+ nothingToPublish: (c) => t('errors.conflict.pipelineNothingToPublish', undefined, c),
331
+ runFinished: (c) => t('errors.conflict.pipelineRunFinished', undefined, c),
332
+ templateNotInstantiable: (c) => t('errors.conflict.pipelineTemplateUnsupported', undefined, c),
333
+ projectIdRequired: (c) => t('errors.validation.projectIdRequired', undefined, c),
334
+ },
335
+ }));
336
+ // PROP-096/097: HTTP-контур единого реестра фоновых прогонов (список,
337
+ // деталь, лог, остановка, удаление). Право на прогон — право на его
338
+ // сессию-владельца: владелец|ADMIN, участник проекта (read — любая роль,
339
+ // write — OWNER/EDITOR/LEAD/ADMIN; `VIEWER` читает, но не мутирует —
340
+ // инвариант 21). Проверка — граничный guard core-фабрики (инвариант 16),
341
+ // в обработчиках проверок нет. Сервисы фоновой работы в деградированном
342
+ // режиме хранилища не создаются — тогда контура нет.
343
+ if (deps.backgroundService && deps.processService) {
344
+ app.route('/api/v2/processes', createProcessRoutes({ requireAuth: auth.requireAuth }, {
345
+ backgroundRuns: deps.storageContext.backgroundRuns,
346
+ background: deps.backgroundService,
347
+ processes: deps.processService,
348
+ sessionManager,
349
+ }, {
350
+ isAllowed: createBackendProcessAccess({ auth, projectStore }),
351
+ resolveUserId: async (c) => (await auth.getCurrentUser(c))?.id ?? '',
352
+ messages: {
353
+ runNotFound: (c) => t('errors.notFound.backgroundRun', undefined, c),
354
+ sessionNotFound: (c) => t('errors.notFound.backgroundRunSession', undefined, c),
355
+ forbidden: (c) => t('auth.forbidden', undefined, c),
356
+ invalidQuery: (c) => t('errors.validation.invalidBackgroundRunQuery', undefined, c),
357
+ invalidKind: (c) => t('errors.validation.backgroundRunLogKind', undefined, c),
358
+ logNotFound: (c) => t('errors.notFound.processLog', undefined, c),
359
+ alreadyFinished: (c) => t('errors.conflict.backgroundRunFinished', undefined, c),
360
+ notStoppable: (c) => t('errors.conflict.backgroundRunNotStoppable', undefined, c),
361
+ runActive: (c) => t('errors.conflict.backgroundRunActive', undefined, c),
362
+ },
363
+ }));
364
+ }
365
+ // ADR-086 §5: установка пакетов расширений (скиллы/MCP/агенты/пайплайны) и
366
+ // реестр установок. Managed RBAC: установка — ADMIN или service-key со
367
+ // scope `automation:install`; одобрение и снятие — **только ADMIN** (снимают
368
+ // чужие артефакты инстанса).
369
+ app.route('/api/v2/packs', createPacksRoutes({ requireAuth: auth.requireAuth }, {
370
+ packs,
371
+ pipelines,
372
+ skills: skillService,
373
+ mcpRegistry: mcpRegistryStore,
374
+ agents: agentStore,
375
+ roleFiles: contextConfig,
376
+ routes: routeRuleStore,
377
+ // ADR-106 Ф5: контент полномочий пакета активируется в политике
378
+ // инстанса при одобрении и снимается при снятии установки.
379
+ authorityPolicy: deps.storageContext.authorityPolicy,
380
+ registerAgent: (agent) => agentRegistry.register(agent),
381
+ unregisterAgent: (id) => agentRegistry.unregister(id),
382
+ resolveUserId: (c) => {
383
+ const user = c.get('user');
384
+ return user?.id;
385
+ },
386
+ }, {
387
+ readGuard: auth.requirePermission('ADMIN'),
388
+ writeGuard: requireAdminRoleOrScope('automation:install'),
389
+ approveGuard: auth.requirePermission('ADMIN'),
390
+ uninstallGuard: auth.requirePermission('ADMIN'),
391
+ scopeGuard,
392
+ }));
393
+ // ADR-090 (Ф5б-2): управление плагинами инстанса. Managed RBAC:
394
+ // чтение — ADMIN (реестр инстанса), установка/активация/деактивация —
395
+ // ADMIN или service-key со scope `addons:install` (установка аддонов —
396
+ // зонтичный scope реестра расширений), подтверждение карантина и снятие —
397
+ // **только ADMIN** (снятие гасит код в процессе ядра). Установка из
398
+ // локального каталога/архива запрещена (`localInstall: false` → 403
399
+ // `LOCAL_INSTALL_DISABLED`): путь с ФС хоста в managed не принимается.
400
+ // Сетевые источники (`npm`/`url`) разрешены — это не локальный путь, а
401
+ // доставка бандла с проверкой целостности (SRI/sha256).
402
+ app.route('/api/v2/plugins', createPluginsRoutes({ requireAuth: auth.requireAuth }, {
403
+ runtime: deps.pluginRuntime,
404
+ config: mergePluginsConfig(config.synth.plugins, {}),
405
+ settings: settingsStore,
406
+ localInstall: false,
407
+ // Ф7 (ADR-090): реестр service-key — для выдачи server-scoped токена
408
+ // плагину (`POST /api/v2/plugins/token`).
409
+ serviceKeys: serviceApiKeyStore,
410
+ // Ф7: серверная политика (allow-list) из работающего рантайма.
411
+ serverPolicy: () => resolvePluginServerPolicy(deps.pluginRuntime.config),
412
+ resolveUserId: (c) => {
413
+ const user = c.get('user');
414
+ return user?.id;
415
+ },
416
+ }, {
417
+ readGuard: auth.requirePermission('ADMIN'),
418
+ writeGuard: requireAdminRoleOrScope('addons:install'),
419
+ approveGuard: auth.requirePermission('ADMIN'),
420
+ uninstallGuard: auth.requirePermission('ADMIN'),
421
+ // Ф7 (Уровень 2): выдача server-scoped токена — только ADMIN (токен даёт
422
+ // плагину машинный доступ к серверу).
423
+ tokenGuard: auth.requirePermission('ADMIN'),
424
+ }));
425
+ // ADR-090 (Ф5б-2): runtime-настройки слоя плагинов. Managed RBAC —
426
+ // ADMIN (чтение и запись): политика доверия/скана/исполнения — инстанс-уровневая.
427
+ // `restartRequired` — всегда true (рантайм собирается при старте, инвариант 24).
428
+ app.route('/api/v2/settings', createPluginSettingsRoutes({ requireAuth: auth.requireAuth }, {
429
+ config: mergePluginsConfig(config.synth.plugins, {}),
430
+ settings: settingsStore,
431
+ running: deps.pluginRuntime.config,
432
+ // Долги Д3: бюджеты (`promptBlockMaxChars`, `llmFilterTimeoutMs`) —
433
+ // живые; остальные ключи — после рестарта (инвариант 24).
434
+ onPluginsChange: (effective) => {
435
+ deps.orchestrator.setPromptBlockMaxChars(effective.promptBlockMaxChars);
436
+ deps.orchestrator.setLlmFilterTimeoutMs(effective.llmFilterTimeoutMs);
437
+ },
438
+ }, {
439
+ readGuard: auth.requirePermission('ADMIN'),
440
+ writeGuard: auth.requirePermission('ADMIN'),
441
+ }));
442
+ // ADR-115: админ-раздел «Вложения» — runtime-настройки мультимодального
443
+ // ввода. Managed RBAC — **ADMIN** (чтение и запись): мастер-выключатель,
444
+ // семейства MIME и лимиты — политика инстанса. Применяется сразу
445
+ // (`restartRequired: false`): сервис вложений, промпт и GC читают резолвер
446
+ // на каждый вызов.
447
+ app.route('/api/v2/settings', createAttachmentsSettingsRoutes({ requireAuth: auth.requireAuth }, {
448
+ settingsStore,
449
+ config: config.synth.attachments,
450
+ live: deps.attachmentsSettings,
451
+ securityAudit,
452
+ env: process.env,
453
+ // ADR-115: проверка `modalityModels` по каталогу (провайдер + модель +
454
+ // модальности модели) — до записи runtime-патча.
455
+ lookupModel: createModalityModelLookup({ providers: providerStore, models: modelStore }),
456
+ }, {
457
+ readGuard: auth.requirePermission('ADMIN'),
458
+ writeGuard: auth.requirePermission('ADMIN'),
459
+ }));
460
+ // ADR-115: staging-загрузка без сессии — `POST /api/v2/attachments`
461
+ // (шлюзы принимают файл из внешнего канала, пайплайны — из шага). Managed:
462
+ // `requireAuth` + scope-гейт service-key `events:ingest` (у шлюзов он уже
463
+ // есть; для интерактивных кред — no-op). Объект не привязан к сессии: без
464
+ // ссылки `blob_refs` живёт `attachments.gcDays` до GC.
465
+ app.route('/api/v2/attachments', createStagingAttachmentRoutes({ requireAuth: auth.requireAuth, getCurrentUser: auth.getCurrentUser }, {
466
+ service: new AttachmentService({
467
+ blobs: deps.storageContext.blobs,
468
+ config: () => deps.attachmentsSettings.getConfig(),
469
+ }),
470
+ config: () => deps.attachmentsSettings.getConfig(),
471
+ }, { guard: scopeGuard('events:ingest') }));
472
+ // ADR-107 / PROP-047 §2.1: портал памяти в ядре — чтение фактов и индексов
473
+ // через доменные порты памяти. Managed RBAC: **только ADMIN** — портал
474
+ // админский (данные памяти видны целиком, без проектной проекции).
475
+ // Namespace плагина памяти подставляет сервер — клиент его не задаёт.
476
+ app.route('/api/v2/memory', createMemoryRoutes({ requireAuth: auth.requireAuth }, {
477
+ memory: {
478
+ facts: deps.storageContext.memoryFacts,
479
+ indexes: deps.storageContext.memoryIndexes,
480
+ },
481
+ guard: auth.requirePermission('ADMIN'),
482
+ // Проектная авторизация (инвариант 16, ADR-089 §5.8): проверка прав на
483
+ // границе — до обращения к порту/тулу. `read` — право чтения проекта
484
+ // (владелец/участник/`LEAD`/`ADMIN`), `write` — право изменения
485
+ // содержимого (владелец/`EDITOR`/`LEAD`/`ADMIN`; `VIEWER` только
486
+ // читает, инвариант 21). Нет проекта/прав → отказ (fail-closed).
487
+ authorizeProject: async (c, projectId, mode) => {
488
+ const user = await auth.getCurrentUser(c);
489
+ if (!user)
490
+ return false;
491
+ const project = await projectStore.load(projectId);
492
+ if (!project)
493
+ return false;
494
+ return mode === 'read'
495
+ ? projectAccess.canReadProject(c, project, user.id)
496
+ : projectAccess.canEditProjectContent(c, project, user.id);
497
+ },
498
+ // Активен ли плагин памяти в процессе — реестр активаций хоста (ADR-090).
499
+ isPluginActive: () => deps.pluginRuntime.host.isActive(MEMORY_PLUGIN_NAME),
500
+ // М2: мутации индексов — через админ-тул плагина памяти (реестр тулов).
501
+ // Контекст вызова (sessionId/messageId) создаёт вызывающая сторона:
502
+ // сессии у портала нет — это служебный вызов инстанса.
503
+ invokeTool: async ({ tool, params, projectId, workingDir }) => {
504
+ const def = toolRegistry.get(tool);
505
+ if (!def)
506
+ throw new MemoryProviderUnavailableError(tool);
507
+ return executeToolDef(def, params, {
508
+ sessionId: `system:memory-portal:${randomUUID()}`,
509
+ messageId: `system:memory-portal:${randomUUID()}`,
510
+ workingDir,
511
+ ...(projectId ? { projectId } : {}),
512
+ }, tool);
513
+ },
514
+ // Проект и его workspace (ADR-075): относительный workspace резолвится
515
+ // от `workspacesRoot`, абсолютный — как есть.
516
+ resolveProject: async (projectId) => {
517
+ const project = await deps.storageContext.projects.load(projectId);
518
+ if (!project)
519
+ return null;
520
+ if (!project.workspace)
521
+ return { id: project.id };
522
+ const root = config.workspacesRoot ?? join(dataDir, 'workspaces');
523
+ const workspace = isAbsolute(project.workspace)
524
+ ? normalize(project.workspace)
525
+ : resolve(root, project.workspace);
526
+ return { id: project.id, workspace };
527
+ },
528
+ // Каталог данных — рабочий каталог для источника `facts` (нет workspace).
529
+ dataDir,
530
+ messages: {
531
+ invalidStatus: (c) => t('errors.validation.invalidMemoryStatus', undefined, c),
532
+ invalidState: (c) => t('errors.validation.invalidMemoryState', undefined, c),
533
+ invalidLimit: (c) => t('errors.validation.invalidMemoryLimit', undefined, c),
534
+ invalidOffset: (c) => t('errors.validation.invalidMemoryOffset', undefined, c),
535
+ factNotFound: (c) => t('errors.notFound.memoryFact', undefined, c),
536
+ unavailable: (c) => t('errors.unavailable.memory', undefined, c),
537
+ invalidBody: (c) => t('errors.validation.invalidMemoryBody', undefined, c),
538
+ invalidSource: (c) => t('errors.validation.invalidMemorySource', undefined, c),
539
+ projectRequired: (c) => t('errors.validation.memoryProjectRequired', undefined, c),
540
+ projectNotFound: (c) => t('errors.notFound.memoryProject', undefined, c),
541
+ workspaceRequired: (c) => t('errors.validation.memoryWorkspaceRequired', undefined, c),
542
+ providerUnavailable: (c) => t('errors.unavailable.memoryProvider', undefined, c),
543
+ indexNotFound: (c) => t('errors.notFound.memoryIndex', undefined, c),
544
+ indexFailed: (c) => t('errors.failed.memoryIndex', undefined, c),
545
+ indexCreated: (c) => t('memory.indexCreated', undefined, c),
546
+ invalidThreshold: (c) => t('errors.validation.invalidMemoryThreshold', undefined, c),
547
+ consolidationFailed: (c) => t('errors.failed.memoryConsolidation', undefined, c),
548
+ consolidated: (c) => t('memory.consolidated', undefined, c),
549
+ invalidGraphDepth: (c) => t('errors.validation.invalidMemoryGraphDepth', undefined, c),
550
+ invalidGraphLimit: (c) => t('errors.validation.invalidMemoryGraphLimit', undefined, c),
551
+ invalidGraphEntity: (c) => t('errors.validation.invalidMemoryGraphEntity', undefined, c),
552
+ graphFailed: (c) => t('errors.failed.memoryGraph', undefined, c),
553
+ forbidden: (c) => t('auth.forbidden', undefined, c),
554
+ },
555
+ }));
176
556
  // ADR-052 (этап I): CRUD service-key инстанса (`synth_svc_…`). Managed RBAC:
177
557
  // только ADMIN (ключи дают машинный доступ — управление админское), i18n.
178
558
  app.route('/api/v2/service-keys', createServiceKeyRoutes({ requireAuth: auth.requireAuth }, { store: serviceApiKeyStore }, {
@@ -200,7 +580,8 @@ export function mountBackendRoutes(app, auth, ctx) {
200
580
  return user?.id ?? 'unknown';
201
581
  },
202
582
  isEnabled: () => webhooksConfig.enabled,
203
- allowPrivateTargets: webhooksConfig.allowPrivateTargets,
583
+ // Отдельный экземпляр политики (live; граница доверия не смешивается с tools).
584
+ resolvePolicy: () => egressResolver.resolveWebhooks(),
204
585
  messages: {
205
586
  invalid: (c) => t('errors.validation.invalidWebhook', undefined, c),
206
587
  notFound: (c) => t('errors.notFound.webhook', undefined, c),
@@ -209,11 +590,130 @@ export function mountBackendRoutes(app, auth, ctx) {
209
590
  disabled: (c) => t('errors.unavailable.webhooksDisabled', undefined, c),
210
591
  },
211
592
  }));
593
+ // ADR-091/ADR-092: обслуживание инстанса (backup/restore/doctor/migrate).
594
+ // Managed RBAC: только ADMIN — операции меняют/отдают данные всего инстанса
595
+ // (архивы могут содержать секреты), i18n.
596
+ // ADR-097: при backend=postgres doctor/migrations ходят в БД через read-only
597
+ // пробу (контекст в режиме `skip` — миграции не применяются).
598
+ const maintenanceBackend = resolveStorageBackend(config.synth, process.env);
599
+ const withPostgresContext = maintenanceBackend === 'postgres'
600
+ ? async (fn) => {
601
+ const ctx = await createStorageContextAsync('postgres', {
602
+ dataDir,
603
+ secretKey: resolveSecretKey(config.synth),
604
+ env: process.env,
605
+ postgres: resolvePostgresConfig(config.synth, process.env),
606
+ postgresPassword: resolvePostgresPassword({ dataDir }, process.env),
607
+ postgresSchemaMode: 'skip',
608
+ });
609
+ try {
610
+ return await fn(ctx);
611
+ }
612
+ finally {
613
+ await ctx.close?.();
614
+ }
615
+ }
616
+ : undefined;
617
+ app.route('/api/v2/maintenance', createMaintenanceRoutes({ requireAuth: auth.requireAuth }, {
618
+ dataDir,
619
+ secretKey: resolveSecretKey(config.synth),
620
+ env: process.env,
621
+ audit: maintenanceAudit,
622
+ storageBackend: maintenanceBackend,
623
+ ...(withPostgresContext
624
+ ? {
625
+ dbHealth: () => withPostgresContext((ctx) => (ctx.health ? ctx.health() : Promise.resolve({ ok: false, error: 'нет health()' }))),
626
+ schemaMigrations: (o) => withPostgresContext((ctx) => ctx.schemaMigrations ? ctx.schemaMigrations(o) : Promise.reject(new Error('нет schemaMigrations()'))),
627
+ }
628
+ : {}),
629
+ }, {
630
+ writeGuard: auth.requirePermission('ADMIN'),
631
+ readGuard: auth.requirePermission('ADMIN'),
632
+ maxUploadBytes: config.maxUploadBytes,
633
+ resolveUserId: (c) => {
634
+ const user = c.get('user');
635
+ return user?.id ?? 'unknown';
636
+ },
637
+ messages: {
638
+ invalidBody: (c) => t('errors.validation.invalidMaintenanceBody', undefined, c),
639
+ confirmRequired: (c) => t('errors.validation.maintenanceConfirmRequired', undefined, c),
640
+ backupNotFound: (c) => t('errors.notFound.backup', undefined, c),
641
+ invalidBackupName: (c) => t('errors.validation.invalidBackupName', undefined, c),
642
+ payloadTooLarge: (c) => t('errors.payloadTooLarge', undefined, c),
643
+ invalidArchive: (c) => t('errors.validation.invalidRestoreArchive', undefined, c),
644
+ schemaTooNew: (c) => t('errors.conflict.schemaTooNew', undefined, c),
645
+ invalidAuditLimit: (c) => t('errors.validation.invalidAuditLimit', undefined, c),
646
+ invalidAuditOp: (c) => t('errors.validation.invalidAuditOp', undefined, c),
647
+ encryptedRestore: (c) => t('errors.validation.encryptedRestoreUnsupported', undefined, c),
648
+ restartUnsupported: (c) => t('errors.unavailable.restartUnsupported', undefined, c),
649
+ },
650
+ }));
212
651
  // MCP routes (единый реестр; legacy /servers — адаптеры над ним)
213
652
  app.route('/api/v2/mcp', createMcpRoutes(auth, mcpManager, sessionManager, {
214
653
  registry: mcpRegistryStore,
215
- networkPolicy: live.getNetworkPolicy(),
216
- getNetworkPolicy: () => live.getNetworkPolicy(),
654
+ // Политика резолвится на каждый запрос (live; исключения/режим — из стора).
655
+ getNetworkPolicy: () => egressResolver.resolveMcp(),
656
+ // ADR-105 (Ф3): порт слоя внешних доступов — право привязать доступ
657
+ // к коннектору проверяется на границе (инвариант 16).
658
+ credentials: deps.storageContext.externalCredentials,
659
+ // ADR-105 (Ф3): проектный доступ привязывает участник проекта с правом
660
+ // изменения содержимого (OWNER/EDITOR + LEAD/ADMIN; VIEWER — нет).
661
+ canEditProject: async (c, projectId) => {
662
+ const user = c.get('user');
663
+ if (!user?.id)
664
+ return false;
665
+ const project = await projectStore.load(projectId);
666
+ return project ? projectAccess.canEditProjectContent(c, project, user.id) : false;
667
+ },
668
+ }));
669
+ // ADR-105 (Ф4): HTTP-контур слоя внешних доступов. Managed RBAC:
670
+ // чтение — свои доступы (владелец/участник проекта), `ADMIN`/`LEAD` — все;
671
+ // мутации — владелец доступа (инстансные — `ADMIN`/`LEAD`); право
672
+ // распоряжения доступом проверяется на границе (инвариант 16).
673
+ app.route('/api/v2/oauth', createOAuthRoutes({ requireAuth: auth.requireAuth }, {
674
+ credentials: deps.storageContext.externalCredentials,
675
+ service: deps.oauthCredentialService,
676
+ providers: deps.oauthProviders,
677
+ // ADR-105 (Ф4): журнал операций со слоем доступов (привязка к коннектору).
678
+ audit: deps.storageContext.credentialAudit,
679
+ ownerKind: 'user',
680
+ resolveActor: (c) => {
681
+ const user = c.get('user');
682
+ return { userId: user?.id ?? '', roles: user?.roles ?? [] };
683
+ },
684
+ canReadProject: async (c, projectId) => {
685
+ const user = await auth.getCurrentUser(c);
686
+ if (!user)
687
+ return false;
688
+ const project = await projectStore.load(projectId);
689
+ return project ? projectAccess.canReadProject(c, project, user.id) : false;
690
+ },
691
+ canEditProject: async (c, projectId) => {
692
+ const user = await auth.getCurrentUser(c);
693
+ if (!user)
694
+ return false;
695
+ const project = await projectStore.load(projectId);
696
+ return project ? projectAccess.canEditProjectContent(c, project, user.id) : false;
697
+ },
698
+ bindConnector: async ({ connectorId, credentialId, actor, c }) => {
699
+ await bindCredentialToConnector({
700
+ registry: deps.mcpRegistryStore,
701
+ connectorId,
702
+ credentialId,
703
+ // Запись реестра меняет автор записи или `ADMIN` (как в `mcp-registry`).
704
+ canModify: (entry) => {
705
+ const user = c.get('user');
706
+ if (auth.isAdmin(c))
707
+ return true;
708
+ if (entry.author?.userId && user?.id && entry.author.userId === user.id)
709
+ return true;
710
+ return actor.roles.includes('ADMIN') || actor.roles.includes('LEAD');
711
+ },
712
+ });
713
+ // Реестр — источник истины для конфигурации серверов (ADR-071 §2.5):
714
+ // без синхронизации менеджер остался бы со старым конфигом (без `auth`).
715
+ await syncMcpManagerFromRegistry(mcpManager, deps.mcpRegistryStore);
716
+ },
217
717
  }));
218
718
  // Скиллы (ADR-046 §9.1/§9.2): core-фабрика + RBAC ADMIN на запись.
219
719
  app.route('/api/v2/skills', createSkillRoutes(auth, {
@@ -250,8 +750,10 @@ export function mountBackendRoutes(app, auth, ctx) {
250
750
  return missing;
251
751
  },
252
752
  }, { writeGuard: auth.requireAdmin }));
253
- // ADR-046 §4.5: scope-API скиллов. Доступ к сессии — владелец|ADMIN
254
- // (canAccess, как в session-роутах); проект — owner/LEAD/ADMIN.
753
+ // ADR-046 §4.5: scope-API скиллов. Доступ к сессии — та же семантика, что у
754
+ // `createSessionRoutes` (единая точка истины на ресурс сессии): владелец|ADMIN
755
+ // (`canAccess`), участник проекта (`resolveCanAccessExtra`), сквозной обзор
756
+ // ADMIN/LEAD (`resolveElevated`); проект — owner/LEAD/ADMIN.
255
757
  const resolveSkillWorkspace = async (projectId) => {
256
758
  const project = await projectStore.load(projectId);
257
759
  if (!project?.workspace)
@@ -269,6 +771,23 @@ export function mountBackendRoutes(app, auth, ctx) {
269
771
  resolveUserId: async (c) => (await auth.getCurrentUser(c))?.id ?? '',
270
772
  canAccess: (session, c, userId) => (session.ownerId ?? session.userId) === userId
271
773
  || auth.isAdmin(c),
774
+ resolveElevated: (c) => auth.isAdmin(c) || auth.hasRole(c, 'LEAD'),
775
+ // read/write по роли в проекте (та же модель `createProjectAccess`, что и в
776
+ // session/message/queue-фабриках): GET — owner/любой участник, PUT — owner/EDITOR.
777
+ resolveCanAccessExtra: (() => {
778
+ const { canReadProject, canEditProjectContent } = createProjectAccess(auth);
779
+ return async (session, c, userId, access) => {
780
+ if (!session.projectId)
781
+ return false;
782
+ const project = await projectStore.load(session.projectId);
783
+ if (!project)
784
+ return false;
785
+ const ctx = c;
786
+ return access === 'read'
787
+ ? canReadProject(ctx, project, userId)
788
+ : canEditProjectContent(ctx, project, userId);
789
+ };
790
+ })(),
272
791
  }));
273
792
  app.route('/api/v2/projects', createProjectSkillScopeRoutes(auth, {
274
793
  sessionManager, skillService, settingsStore, projectStore,
@@ -346,6 +865,8 @@ export function mountBackendRoutes(app, auth, ctx) {
346
865
  gatewayPayloadLogPath,
347
866
  patternStore,
348
867
  rateLimiter: createRateLimiter(120, 60_000),
868
+ // ADR-094: LLM-прокси учитывается в метриках (undefined — выключено).
869
+ metrics,
349
870
  }));
350
871
  // Settings routes (runtime-настройки для UI: workspace + mcp; переиспользуем core-реализацию)
351
872
  app.route('/api/v2/settings', createSettingsRoutes(auth, {
@@ -358,6 +879,18 @@ export function mountBackendRoutes(app, auth, ctx) {
358
879
  workspacePolicyReadOnly: true,
359
880
  // Агент по умолчанию при первом развёртывании (config.yaml не задаёт — DEFAULT_AGENT_ID).
360
881
  fallbackDefaultAgent: DEFAULT_AGENT_ID,
882
+ // Модель по умолчанию: fallback из config (только если заданы оба поля);
883
+ // runtime-пара приоритетнее. Валидация — провайдер в каталоге + модель `provider/model`.
884
+ fallbackDefaultModel: backendConfigDefaultModel(),
885
+ validateDefaultModel: async (pair) => {
886
+ const provider = await providerStore.load(pair.provider);
887
+ if (!provider)
888
+ return `провайдер "${pair.provider}" не найден`;
889
+ const model = await modelStore.load(`${pair.provider}/${pair.model}`);
890
+ if (!model)
891
+ return `модель "${pair.provider}/${pair.model}" не найдена`;
892
+ return true;
893
+ },
361
894
  // ADR-072 Ф2: дефолты из config.yaml (без runtime) — для GET/DELETE-сброса к умолчанию.
362
895
  fallbackLlmGateway: {
363
896
  enabled: config.synth.llmGateway.enabled,
@@ -404,8 +937,21 @@ export function mountBackendRoutes(app, auth, ctx) {
404
937
  })),
405
938
  // ADR-071 §2.3.1: live-применение политики сетевого доступа MCP из админки.
406
939
  fallbackMcpNetworkPolicy: config.synth.mcp.networkPolicy,
407
- onMcpNetworkPolicyChange: async (policy) => {
408
- live.setNetworkPolicy(policy);
940
+ // ADR-071 §2.3.1: колбэк не нужен — `McpManager` резолвит политику из стора
941
+ // при каждом connect/probe (live, без стартового снимка).
942
+ // Egress: дефолты config.yaml для GET/DELETE-сброса + аудит изменений.
943
+ fallbackEgressTools: config.synth.egress.tools,
944
+ fallbackEgressWebhooks: config.synth.egress.webhooks,
945
+ // ADR-099: прокси — config-уровень, runtime-override и файл пароля.
946
+ fallbackProxy: config.synth.proxy,
947
+ // ADR-099: TLS/CA — config-уровень (read-only в UI; runtime — bootstrap).
948
+ fallbackTls: config.synth.security?.tls,
949
+ dataDir,
950
+ env: process.env,
951
+ securityAudit,
952
+ resolveActor: (c) => {
953
+ const user = c.get('user');
954
+ return typeof user?.id === 'string' && user.id ? user.id : 'unknown';
409
955
  },
410
956
  // ADR-089: дефолт config.yaml для GET/DELETE-сброса раздела «События».
411
957
  fallbackEvents: config.synth.events,
@@ -422,25 +968,72 @@ export function mountBackendRoutes(app, auth, ctx) {
422
968
  },
423
969
  protectedPathsStore,
424
970
  }, {
425
- // ADR-089: мутации раздела «События» — только ADMIN (managed RBAC).
426
- eventsWriteGuard: auth.requirePermission('ADMIN'),
427
- // ADR-084: мутации decision-слоя — только ADMIN (managed RBAC).
428
- decisionWriteGuard: auth.requirePermission('ADMIN'),
971
+ // Instance-wide настройки (ADR-072): все мутации `/api/v2/settings/*`
972
+ // (workspace, mcp, llm-gateway, security, tools-policy, mcp-policy,
973
+ // mcp-network-policy, default-agent, workspace-policy, tools-disabled,
974
+ // protected-paths, events, decision) — только ADMIN (managed RBAC).
975
+ // События/decision наследуют тот же guard (если не заданы отдельно).
976
+ settingsWriteGuard: auth.requirePermission('ADMIN'),
977
+ }));
978
+ // ADR-094: админ-раздел «Наблюдаемость» — runtime `metrics.enabled` (рестарт),
979
+ // live-статус и bearer-токен `/metrics` (write-only, применяется сразу).
980
+ // Managed RBAC: чтение и мутации — только ADMIN.
981
+ app.route('/api/v2/settings', createMetricsSettingsRoutes({ requireAuth: auth.requireAuth }, {
982
+ settingsStore,
983
+ dataDir,
984
+ configEnabled: config.synth.metrics.enabled,
985
+ runningEnabled: ctx.metrics.runningEnabled,
986
+ getRegistry: ctx.metrics.getRegistry,
987
+ getReadiness: ctx.metrics.getReadiness,
988
+ getStorageBackend: () => ctx.metrics.storageBackend,
989
+ getUptimeSec: ctx.metrics.getUptimeSec,
990
+ version: SYNTH_VERSION,
991
+ }, {
992
+ readGuard: auth.requirePermission('ADMIN'),
993
+ writeGuard: auth.requirePermission('ADMIN'),
994
+ }));
995
+ // Журналы безопасности: аудит изменений политик + внешние запросы (egress).
996
+ // Managed RBAC: чтение только ADMIN/AUDITOR.
997
+ app.route('/api/v2/audit', createSecurityAuditRoutes(auth, {
998
+ securityAudit,
999
+ egressRequests,
1000
+ }, {
1001
+ readGuard: auth.requirePermission('ADMIN', 'AUDITOR'),
1002
+ }));
1003
+ // ADR-102 (волна 1): отчёты аналитики — только чтение, данных без локализации.
1004
+ // Managed RBAC (§7): ADMIN/LEAD — сквозной обзор; AUDITOR — чтение всех отчётов;
1005
+ // обычный USER — принудительный фильтр оси `user` по себе (+ 403 на `decision`/`summary`).
1006
+ app.route('/api/v2/analytics', createAnalyticsRoutes({ requireAuth: auth.requireAuth }, { service: new AnalyticsService({ repo: analyticsRollups }) }, {
1007
+ resolveElevated: (c) => auth.isAdmin(c) || auth.hasRole(c, 'LEAD'),
1008
+ resolveAuditor: (c) => auth.hasRole(c, 'AUDITOR'),
1009
+ // `attachUser` уже положил пользователя в контекст — берём его id.
1010
+ resolveUserId: (c) => {
1011
+ const user = c.get('user');
1012
+ return user?.id ?? '';
1013
+ },
1014
+ messages: {
1015
+ invalidPeriod: (c) => t('errors.validation.invalidAnalyticsPeriod', undefined, c),
1016
+ invalidRange: (c) => t('errors.validation.invalidAnalyticsRange', undefined, c),
1017
+ invalidGroupBy: (c) => t('errors.validation.invalidAnalyticsGroupBy', undefined, c),
1018
+ invalidOption: (c) => t('errors.validation.invalidAnalyticsOption', undefined, c),
1019
+ forbidden: (c) => t('errors.forbidden.analytics', undefined, c),
1020
+ },
429
1021
  }));
430
1022
  // Словари классификации: чтение — все авторизованные, запись/сброс — ADMIN
431
- // (тот же guard, что у users.ts). Реализация общая с core.
432
- const dictionaryStore = new DictionaryStore(dataDir);
433
- app.route('/api/v2/dictionaries', createDictionaryRoutes(auth, dictionaryStore, { writeGuard: auth.requireAdmin }));
1023
+ // (тот же guard, что у users.ts). Реализация общая с core; порт — из контекста хранения.
1024
+ app.route('/api/v2/dictionaries', createDictionaryRoutes(auth, dictionaries, { writeGuard: auth.requireAdmin }));
434
1025
  // ADR-069 §9.3: прозрачность проектных инструкций — core-фабрика (резолвер не
435
1026
  // дублируется). RBAC: сессия — владелец|ADMIN (canAccess, как в session-роутах);
436
1027
  // проект — owner/LEAD/ADMIN (canAccessProject, как в project-скиллах).
437
1028
  const instructionsInfoResolver = createInstructionsInfoResolver(new ProjectInstructionsResolver({
438
1029
  config: config.synth.instructions,
439
- dictionaryStore,
1030
+ dictionaryStore: dictionaries,
440
1031
  dataDir,
441
1032
  trustedProjectDirs: config.synth.skills.trustedProjectDirs,
442
1033
  // ADR-069 R3: авто-trust workspace внутри workspacesRoot (managed-каталоги).
443
1034
  workspacesRoot: config.workspacesRoot,
1035
+ // ADR-077: `git rev-parse` — через порт исполнения (тот же, что у тулов).
1036
+ execution: deps.executionPort,
444
1037
  }), config.synth.instructions);
445
1038
  app.route('/api/v2/context', createCoreContextRoutes(auth, {
446
1039
  resolveInstructions: instructionsInfoResolver,