@itphx/synth-backend 0.9.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/dist/app/bootstrap.d.ts +11 -0
  2. package/dist/app/bootstrap.js +19 -0
  3. package/dist/app/deps.d.ts +106 -0
  4. package/dist/app/deps.js +617 -0
  5. package/dist/app/listen.d.ts +29 -0
  6. package/dist/app/listen.js +298 -0
  7. package/dist/app/mount-routes.d.ts +18 -0
  8. package/dist/app/mount-routes.js +466 -0
  9. package/dist/app/sse-events.d.ts +15 -0
  10. package/dist/app/sse-events.js +83 -0
  11. package/dist/app.d.ts +29 -3
  12. package/dist/app.js +110 -900
  13. package/dist/auth/guards.d.ts +20 -0
  14. package/dist/auth/guards.js +65 -0
  15. package/dist/auth/middleware.d.ts +20 -1
  16. package/dist/auth/middleware.js +53 -1
  17. package/dist/auth/oidc.d.ts +15 -0
  18. package/dist/auth/oidc.js +41 -3
  19. package/dist/auth/service-scope.d.ts +14 -0
  20. package/dist/auth/service-scope.js +40 -0
  21. package/dist/events/hub.d.ts +9 -0
  22. package/dist/events/hub.js +29 -0
  23. package/dist/lib/cors.d.ts +23 -0
  24. package/dist/lib/cors.js +24 -0
  25. package/dist/lib/i18n.js +64 -0
  26. package/dist/main.js +10 -1
  27. package/dist/middleware/rate-limiter.d.ts +4 -1
  28. package/dist/middleware/rate-limiter.js +4 -2
  29. package/dist/routes/audit.d.ts +1 -1
  30. package/dist/routes/audit.js +2 -2
  31. package/dist/routes/auth.js +35 -5
  32. package/dist/routes/gateway-patterns.d.ts +1 -1
  33. package/dist/routes/gateway-patterns.js +1 -1
  34. package/dist/routes/llm.js +7 -4
  35. package/dist/routes/mcp-registry.d.ts +3 -3
  36. package/dist/routes/mcp-registry.js +40 -17
  37. package/dist/routes/mcp.d.ts +1 -1
  38. package/dist/routes/mcp.js +1 -1
  39. package/dist/routes/projects.d.ts +7 -4
  40. package/dist/routes/projects.js +17 -7
  41. package/dist/routes/providers.js +1 -0
  42. package/dist/routes/sessions.d.ts +7 -1
  43. package/dist/routes/sessions.js +119 -8
  44. package/dist/routes/users.js +17 -4
  45. package/package.json +4 -4
  46. package/dist/agents/definitions/admin.json +0 -24
  47. package/dist/agents/definitions/analyst.json +0 -20
  48. package/dist/agents/definitions/assistant.json +0 -25
  49. package/dist/agents/definitions/auditor.json +0 -19
  50. package/dist/agents/definitions/developer.json +0 -23
  51. package/dist/agents/definitions/devops.json +0 -23
  52. package/dist/agents/definitions/explore.json +0 -15
  53. package/dist/agents/definitions/general.json +0 -15
  54. package/dist/agents/definitions/pm.json +0 -20
  55. package/dist/agents/definitions/qa.json +0 -22
@@ -0,0 +1,466 @@
1
+ // Монтирование HTTP-роутов API v2 backend (Hono API Hub).
2
+ // Порядок `app.route`/`app.get` сохраняется 1:1 с прежним `app.ts` — он
3
+ // определяет приоритеты маршрутов (статические сегменты раньше параметрических,
4
+ // SSE-хаб `/api/v2/events` после роутов событий, но до admin-роутов).
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';
9
+ import { createProjectRoutes, createProjectAccess } from '../routes/projects.js';
10
+ import { createSessionRoutes } from '../routes/sessions.js';
11
+ import { createMessageRoutes } from '../routes/messages.js';
12
+ import { createQueueRoutes } from '../routes/queue.js';
13
+ import { createProviderRoutes } from '../routes/providers.js';
14
+ import { createModelRoutes } from '../routes/models.js';
15
+ import { createAgentRoutes } from '../routes/agents.js';
16
+ import { createMcpRoutes } from '../routes/mcp.js';
17
+ import { createContextRoutes as createContextFileRoutes } from '../routes/context.js';
18
+ import { createDebugRoutes } from '../routes/debug.js';
19
+ import { createUserRoutes } from '../routes/users.js';
20
+ import { createAuditRoutes } from '../routes/audit.js';
21
+ import { createLogsRoutes, resolveLogDir } from '../routes/logs.js';
22
+ import { createGatewayPatternsRoutes } from '../routes/gateway-patterns.js';
23
+ import { createLlmRoutes } from '../routes/llm.js';
24
+ import { createRateLimiter } from '../middleware/rate-limiter.js';
25
+ import { scopeGuard, projectGuard } from '../auth/service-scope.js';
26
+ import { requireAdminOrScope } from '../auth/guards.js';
27
+ import { t, getTranslations } from '../lib/i18n.js';
28
+ import { registerEventsSse } from './sse-events.js';
29
+ /**
30
+ * Смонтировать все `/api/v2/*`-роуты и служебные заглушки (`/api/config/themes`,
31
+ * i18n-эндпоинты) в порядке, идентичном прежнему `createBackendApp`.
32
+ */
33
+ 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;
36
+ // API-заглушки для UI
37
+ app.get('/api/config/themes', (c) => c.json({ themes: [] }));
38
+ // i18n endpoints
39
+ app.get('/api/v2/i18n/current', (c) => {
40
+ const header = c.req.header('Accept-Language');
41
+ const lang = header?.split(',')[0]?.trim()?.slice(0, 2) === 'en' ? 'en' : 'ru';
42
+ return c.json({ language: lang, locale: lang });
43
+ });
44
+ app.get('/api/v2/i18n/translations/ru', (c) => c.json(getTranslations('ru')));
45
+ app.get('/api/v2/i18n/translations/en', (c) => c.json(getTranslations('en')));
46
+ // ADR-052 (этап I): публичный OpenAPI-документ (spike) за requireAuth;
47
+ // публичную выдачу без auth согласуем отдельно.
48
+ app.get('/api/v2/openapi.json', auth.requireAuth, (c) => c.json(getPublicOpenApiDocument()));
49
+ // Projects routes
50
+ app.route('/api/v2/projects', createProjectRoutes(auth, projectStore, sessionManager, config.workspacesRoot, mcpManager, skillService, settingsStore, mcpRegistryStore));
51
+ // Sessions routes
52
+ app.route('/api/v2/sessions', createSessionRoutes(auth, sessionManager, eventBus, queueManager, processMessage, orchestrator, eventHub, contextOptimizer, projectStore, profilesStore, getDefaultAgentId, requestSessionService));
53
+ // Messages routes
54
+ app.route('/api/v2/messages', createMessageRoutes(auth, sessionManager, contextOptimizer, eventBus));
55
+ // Queue routes
56
+ app.route('/api/v2/queue', createQueueRoutes(auth, sessionManager, queueManager, eventBus, processMessage));
57
+ // FS routes (ADR-075): core-фабрика, managed поверх workspace проекта.
58
+ // ADR-089 (P0): доступ к проекту обязателен — иначе любой USER читал/писал бы
59
+ // файлы чужого проекта по id (IDOR). Чтение — canRead, мутации — canEditContent.
60
+ const projectAccess = createProjectAccess(auth);
61
+ app.route('/api/v2/fs', createFsRoutes(auth, config.workspacesRoot, undefined, {
62
+ requireProjectId: true,
63
+ getOutsideRootPolicy: () => 'deny',
64
+ getProtectedPathsPolicy: () => protectedPathsStore.getPolicy(),
65
+ authorizeProject: async (c, projectId) => {
66
+ const user = await auth.getCurrentUser(c);
67
+ if (!user)
68
+ return false;
69
+ const project = await projectStore.load(projectId);
70
+ if (!project)
71
+ return false;
72
+ return c.req.method === 'GET'
73
+ ? projectAccess.canReadProject(c, project, user.id)
74
+ : projectAccess.canEditProjectContent(c, project, user.id);
75
+ },
76
+ getProjectWorkspace: (projectId) => resolveProjectWorkspace(projectId, {
77
+ workspacesRoot: config.workspacesRoot,
78
+ getProject: (id) => projectStore.load(id),
79
+ outsideRootPolicy: () => 'deny',
80
+ strict: true,
81
+ }),
82
+ }));
83
+ // Providers routes
84
+ app.route('/api/v2/providers', createProviderRoutes(auth, providerStore, providerCache));
85
+ // Models routes
86
+ app.route('/api/v2/models', createModelRoutes(auth, modelStore, providerStore, modelCache, providerCache));
87
+ // Agents routes
88
+ app.route('/api/v2/agents', createAgentRoutes(auth, agentStore, agentRegistry, getDefaultAgentId));
89
+ // Context routes (глобальные identity-файлы; админ-мутации)
90
+ app.route('/api/v2/context', createContextFileRoutes(auth, contextConfig));
91
+ // User admin routes
92
+ app.route('/api/v2/users', createUserRoutes(auth, profilesStore));
93
+ // Git routes (ADR-076 §T4): core-фабрика + managed RBAC. Write-эндпоинты
94
+ // (init/clone/register/remove/fetch) требуют прав на изменение контента
95
+ // проекта (owner/EDITOR/LEAD/ADMIN); read-only (scan/log/commit) — requireAuth.
96
+ app.route('/api/v2/git', createGitRoutes(auth, projectStore, config.workspacesRoot, {
97
+ sshKeyStore,
98
+ authorizeProject: async (c, projectId) => {
99
+ const user = await auth.getCurrentUser(c);
100
+ if (!user)
101
+ return false;
102
+ const project = await projectStore.load(projectId);
103
+ if (!project)
104
+ return false;
105
+ return projectAccess.canEditProjectContent(c, project, user.id);
106
+ },
107
+ }));
108
+ // SSH-ключи агентов (ADR-076 §T5): core-фабрика + managed RBAC.
109
+ // Ключи — секреты: чтение — requireAuth (глобально), запись — только ADMIN.
110
+ app.route('/api/v2/ssh-keys', createSshKeyRoutes(auth, sshKeyStore, {
111
+ writeGuard: auth.requireAdmin,
112
+ }));
113
+ app.route('/api/v2/agents/:agentId/ssh-keys', createAgentSshKeyRoutes(auth, sshKeyStore, {
114
+ writeGuard: auth.requireAdmin,
115
+ }));
116
+ // ADR-089: приём внешних событий (ingress), биндинги и журнал. Ingress —
117
+ // requireAuth + rate limit (внешние сервисы до ADR-052 используют общий ключ);
118
+ // чтение биндингов/журнала — requireAuth; мутации биндингов — ADMIN.
119
+ // `GET /` не переопределяем — на этом пути SSE-хаб ниже.
120
+ app.route('/api/v2/events', createEventRoutes({ requireAuth: auth.requireAuth }, { ingress: eventIngress, bindingStore: eventBindingStore, journal: eventJournal, routeRuleStore, apiKeyStore: eventApiKeyStore }, {
121
+ // Rate limit — до решения о способе аутентификации; fallback-креды —
122
+ // requireAuth (приём по API-ключу привязки креды пользователя не требует).
123
+ ingestPreGuard: createRateLimiter(120, 60_000),
124
+ ingestGuard: auth.requireAuth,
125
+ // ADR-089/ADR-052: мутации bindings/routes/keys — LEAD и ADMIN; чтение
126
+ // ключей привязки — тоже LEAD и ADMIN (чувствительные метаданные).
127
+ writeGuard: auth.requirePermission('ADMIN', 'LEAD'),
128
+ keyReadGuard: auth.requirePermission('ADMIN', 'LEAD'),
129
+ // ADR-052 (этап I): scope-гейт и проектная проекция service-key (i18n-403).
130
+ scopeGuard,
131
+ projectGuard,
132
+ // ADR-089/ADR-052: per-key rate limit и мастер-выключатель приёма (live).
133
+ getKeyRateLimitPerMinute: () => live.getEvents().keyRateLimitPerMinute,
134
+ isEnabled: () => live.getEvents().enabled,
135
+ resolveAgentTemplate,
136
+ sessionExists: async (id) => (await sessionManager.getSession(id)) !== null,
137
+ resolveApiKeySecret: async (raw) => {
138
+ const resolved = await eventApiKeyStore.resolveBySecret(raw);
139
+ if (!resolved)
140
+ return null;
141
+ const binding = await eventBindingStore.get(resolved.credential.bindingId);
142
+ if (!binding)
143
+ return null;
144
+ return { binding, credential: resolved.credential };
145
+ },
146
+ touchApiKey: (id) => eventApiKeyStore.touch(id),
147
+ messages: {
148
+ invalidEvent: (c) => t('errors.validation.invalidEvent', undefined, c),
149
+ invalidBinding: (c) => t('errors.validation.invalidBinding', undefined, c),
150
+ bindingNotFound: (c) => t('errors.notFound.binding', undefined, c),
151
+ invalidRule: (c) => t('errors.validation.invalidRule', undefined, c),
152
+ ruleNotFound: (c) => t('errors.notFound.rule', undefined, c),
153
+ unknownAgent: (c) => t('errors.validation.unknownAgent', undefined, c),
154
+ invalidKey: (c) => t('errors.validation.invalidEventKey', undefined, c),
155
+ keyNotFound: (c) => t('errors.notFound.eventKey', undefined, c),
156
+ invalidKeyUpdate: (c) => t('errors.validation.invalidEventKeyUpdate', undefined, c),
157
+ keyLabelConflict: (c) => t('errors.conflict.eventKeyLabel', undefined, c),
158
+ rateLimitedKey: (c) => t('errors.rateLimited.eventKey', undefined, c),
159
+ eventsDisabled: (c) => t('errors.unavailable.eventsDisabled', undefined, c),
160
+ },
161
+ }));
162
+ // ADR-051 / ADR-089: CRUD расписаний, принудительный запуск и Job-история.
163
+ // Чтение — requireAuth (дефолт core-фабрики), мутации — ADMIN. `run` —
164
+ // ADMIN + rate limit (образец — ingest внешних событий): 10 запусков / 60 c
165
+ // на ключ, т.к. каждый запуск ингестит событие в Router.
166
+ app.route('/api/v2/schedules', createSchedulerRoutes(auth, { scheduleStore, scheduler: schedulerService, jobStore }, {
167
+ writeGuard: auth.requireAdmin,
168
+ runGuard: auth.requireAdmin,
169
+ runMiddleware: [createRateLimiter(10, 60_000)],
170
+ // ADR-052 (этап I): scope-гейт, проектная проекция и резолвинг
171
+ // projectId `bound`/`queue`-целей расписания.
172
+ scopeGuard,
173
+ projectGuard,
174
+ resolveSessionProject: async (id) => (await sessionManager.getSession(id))?.projectId,
175
+ }));
176
+ // ADR-052 (этап I): CRUD service-key инстанса (`synth_svc_…`). Managed RBAC:
177
+ // только ADMIN (ключи дают машинный доступ — управление админское), i18n.
178
+ app.route('/api/v2/service-keys', createServiceKeyRoutes({ requireAuth: auth.requireAuth }, { store: serviceApiKeyStore }, {
179
+ writeGuard: auth.requirePermission('ADMIN'),
180
+ readGuard: auth.requirePermission('ADMIN'),
181
+ // createdBy: `attachUser` уже положил пользователя в контекст — берём его id.
182
+ resolveUserId: (c) => {
183
+ const user = c.get('user');
184
+ return user?.id ?? '';
185
+ },
186
+ messages: {
187
+ invalidKey: (c) => t('errors.validation.invalidServiceKey', undefined, c),
188
+ keyNotFound: (c) => t('errors.notFound.serviceKey', undefined, c),
189
+ keyLabelConflict: (c) => t('errors.conflict.serviceKeyLabel', undefined, c),
190
+ },
191
+ }));
192
+ // ADR-052 (этап II): подписки на исходящие webhooks (CRUD + журнал + тест).
193
+ // Managed RBAC: только ADMIN (webhook может утекать данные на произвольный
194
+ // URL), i18n. Мастер-выключатель `webhooks.enabled` → 503 на мутации/тест.
195
+ app.route('/api/v2/webhooks', createWebhookRoutes({ requireAuth: auth.requireAuth }, { store: webhookStore, deliveryStore: webhookDeliveryStore, service: webhookService }, {
196
+ writeGuard: auth.requirePermission('ADMIN'),
197
+ readGuard: auth.requirePermission('ADMIN'),
198
+ resolveUserId: (c) => {
199
+ const user = c.get('user');
200
+ return user?.id ?? 'unknown';
201
+ },
202
+ isEnabled: () => webhooksConfig.enabled,
203
+ allowPrivateTargets: webhooksConfig.allowPrivateTargets,
204
+ messages: {
205
+ invalid: (c) => t('errors.validation.invalidWebhook', undefined, c),
206
+ notFound: (c) => t('errors.notFound.webhook', undefined, c),
207
+ labelConflict: (c) => t('errors.conflict.webhookLabel', undefined, c),
208
+ targetForbidden: (c) => t('errors.validation.webhookTargetForbidden', undefined, c),
209
+ disabled: (c) => t('errors.unavailable.webhooksDisabled', undefined, c),
210
+ },
211
+ }));
212
+ // MCP routes (единый реестр; legacy /servers — адаптеры над ним)
213
+ app.route('/api/v2/mcp', createMcpRoutes(auth, mcpManager, sessionManager, {
214
+ registry: mcpRegistryStore,
215
+ networkPolicy: live.getNetworkPolicy(),
216
+ getNetworkPolicy: () => live.getNetworkPolicy(),
217
+ }));
218
+ // Скиллы (ADR-046 §9.1/§9.2): core-фабрика + RBAC ADMIN на запись.
219
+ app.route('/api/v2/skills', createSkillRoutes(auth, {
220
+ skillService,
221
+ resolveProjectWorkspace: async (projectId) => {
222
+ const project = await projectStore.load(projectId);
223
+ if (!project?.workspace)
224
+ return undefined;
225
+ return isAbsolute(project.workspace)
226
+ ? normalize(project.workspace)
227
+ : resolve(config.workspacesRoot, project.workspace);
228
+ },
229
+ }, { writeGuard: requireAdminOrScope('addons:install') }));
230
+ // ADR-046 §7/§9.1: команды и bundles (mirror core, мутации — ADMIN).
231
+ app.route('/api/v2/commands', createCommandRoutes(auth, {
232
+ commandService,
233
+ resolveProjectWorkspace: async (projectId) => {
234
+ const project = await projectStore.load(projectId);
235
+ if (!project?.workspace)
236
+ return undefined;
237
+ return isAbsolute(project.workspace)
238
+ ? normalize(project.workspace)
239
+ : resolve(config.workspacesRoot, project.workspace);
240
+ },
241
+ }));
242
+ app.route('/api/v2/skill-bundles', createSkillBundleRoutes(auth, {
243
+ bundleStore,
244
+ validateSkills: async (names) => {
245
+ const missing = [];
246
+ for (const name of names) {
247
+ if (!(await skillService.get(name)))
248
+ missing.push(name);
249
+ }
250
+ return missing;
251
+ },
252
+ }, { writeGuard: auth.requireAdmin }));
253
+ // ADR-046 §4.5: scope-API скиллов. Доступ к сессии — владелец|ADMIN
254
+ // (canAccess, как в session-роутах); проект — owner/LEAD/ADMIN.
255
+ const resolveSkillWorkspace = async (projectId) => {
256
+ const project = await projectStore.load(projectId);
257
+ if (!project?.workspace)
258
+ return undefined;
259
+ return isAbsolute(project.workspace)
260
+ ? normalize(project.workspace)
261
+ : resolve(config.workspacesRoot, project.workspace);
262
+ };
263
+ app.route('/api/v2/sessions', createSessionSkillScopeRoutes(auth, {
264
+ sessionManager, skillService, settingsStore, projectStore,
265
+ permissionConfig: config.synth.permission,
266
+ resolveProjectWorkspace: resolveSkillWorkspace,
267
+ }, {
268
+ writeGuard: auth.requireAuth,
269
+ resolveUserId: async (c) => (await auth.getCurrentUser(c))?.id ?? '',
270
+ canAccess: (session, c, userId) => (session.ownerId ?? session.userId) === userId
271
+ || auth.isAdmin(c),
272
+ }));
273
+ app.route('/api/v2/projects', createProjectSkillScopeRoutes(auth, {
274
+ sessionManager, skillService, settingsStore, projectStore,
275
+ permissionConfig: config.synth.permission,
276
+ resolveProjectWorkspace: resolveSkillWorkspace,
277
+ }, {
278
+ // ADR-046 §4.5: проектным уровнем управляют owner/LEAD/ADMIN — как в
279
+ // project-MCP (`canManageProjectMcp`), поэтому writeGuard не requireAdmin;
280
+ // владение проверяет canAccessProject (403 не-членам, 404 — нет проекта).
281
+ writeGuard: auth.requireAuth,
282
+ resolveUserId: async (c) => (await auth.getCurrentUser(c))?.id ?? '',
283
+ canAccessProject: (project, c, userId) => auth.isAdmin(c)
284
+ || auth.hasRole(c, 'LEAD')
285
+ || project.ownerId === userId
286
+ || project.members?.[userId] === ProjectRole.OWNER,
287
+ }));
288
+ app.route('/api/v2/settings', createSkillSettingsRoutes(auth, { settingsStore }, {
289
+ writeGuard: auth.requireAdmin,
290
+ onSkillsDisabledChange: (disabled) => orchestrator.setSkillsDisabled(disabled),
291
+ }));
292
+ // ADR-089: идентичности текущего пользователя (`GET/DELETE /api/v2/me/identities`).
293
+ // RBAC: аутентифицированный пользователь (только свои); линковка — claim-flow
294
+ // (`POST /api/v2/me/identities/claim`).
295
+ // Резолвим **id профиля** по `username` аутентифицированного пользователя
296
+ // (OIDC `sub` — не id профиля: профили хранятся под сгенерированным id).
297
+ // Не передаём `roles` — чтобы не перезаписывать роли существующего профиля.
298
+ app.route('/api/v2/me', createIdentityRoutes(auth, profilesStore, {
299
+ resolveProfileId: async (c) => {
300
+ const u = await auth.getCurrentUser(c);
301
+ if (!u)
302
+ return '';
303
+ const profile = (await profilesStore.getProfileByUsername(u.username))
304
+ ?? (await profilesStore.getOrCreateProfile({ username: u.username, email: u.email }));
305
+ return profile.id;
306
+ },
307
+ claimStore: identityClaimStore,
308
+ // ADR-089 (claim-flow): анти-брутфорс одноразового кода (6 символов, TTL 10 мин) —
309
+ // per-user fixed window 60 c (ключ — Authorization-токен, не IP).
310
+ rateLimitGuard: createRateLimiter(10, 60_000, (c) => t('errors.rateLimited.identityClaim', undefined, c)),
311
+ messages: {
312
+ identityNotFound: (c) => t('errors.notFound.identity', undefined, c),
313
+ claimNotFound: (c) => t('errors.notFound.identityClaim', undefined, c),
314
+ claimConflict: (c) => t('errors.conflict.identityClaim', undefined, c),
315
+ claimCodeRequired: (c) => t('errors.validation.claimCodeRequired', undefined, c),
316
+ unauthorized: (c) => t('auth.unauthorized', undefined, c),
317
+ },
318
+ }));
319
+ // LLM Gateway audit routes (ADR-036) — GET только ADMIN/AUDITOR, POST /revealed — все авторизованные
320
+ app.route('/api/v2/audit', createAuditRoutes(auth, {
321
+ auditLogPath: gatewayAuditLogger.logPath,
322
+ sessionExists: async (sessionId) => {
323
+ const session = await sessionManager.getSession(sessionId);
324
+ return session !== null;
325
+ },
326
+ logger: gatewayAuditLogger,
327
+ }));
328
+ // Логи сервисов (core/ui/backend) + полный лог запросов/ответов LLM — чтение, только ADMIN/AUDITOR
329
+ app.route('/api/v2/logs', createLogsRoutes(auth, {
330
+ logDir: resolveLogDir(),
331
+ payloadLogPath: gatewayPayloadLogPath,
332
+ }));
333
+ // LLM Gateway patterns routes (ADR-036) — управление regex-паттернами детекции секретов, только ADMIN
334
+ app.route('/api/v2/gateway', createGatewayPatternsRoutes(auth, patternStore));
335
+ // LLM Proxy (гибридный режим, Часть 5) — OpenAI-совместимый POST /api/v2/llm/chat/completions.
336
+ // Локальный core гоняет LLM-запросы централизованно через LLM Gateway (ADR-036):
337
+ // обфускация/блокировка секретов, rate limit, аудит, полный payload-лог.
338
+ app.route('/api/v2/llm', createLlmRoutes(auth, {
339
+ providerLoader,
340
+ modelLoader,
341
+ // mergeLlmGatewayConfig может вернуть undefined, если ни base, ни runtime не заданы —
342
+ // но schema с default({}) гарантирует base, поэтому подставляем его.
343
+ gatewayConfig: gatewayConfig ?? config.synth.llmGateway,
344
+ gatewayAuditLogger,
345
+ gatewayRateLimiter: new RateLimiter((gatewayConfig ?? config.synth.llmGateway).rateLimit.userPerMinute, (gatewayConfig ?? config.synth.llmGateway).rateLimit.providerPerMinute),
346
+ gatewayPayloadLogPath,
347
+ patternStore,
348
+ rateLimiter: createRateLimiter(120, 60_000),
349
+ }));
350
+ // Settings routes (runtime-настройки для UI: workspace + mcp; переиспользуем core-реализацию)
351
+ app.route('/api/v2/settings', createSettingsRoutes(auth, {
352
+ settingsStore,
353
+ fallbackWorkspace: defaultWorkingDir,
354
+ // ADR-075: managed-развёртывание — политика вне `workspacesRoot` всегда `deny`
355
+ // (enforcement — в `routes/projects.ts`); строго read-only: GET отдаёт
356
+ // fallback + readOnly, PUT/DELETE → 403 WORKSPACE_POLICY_READ_ONLY.
357
+ fallbackWorkspaceOutsideRootPolicy: 'deny',
358
+ workspacePolicyReadOnly: true,
359
+ // Агент по умолчанию при первом развёртывании (config.yaml не задаёт — DEFAULT_AGENT_ID).
360
+ fallbackDefaultAgent: DEFAULT_AGENT_ID,
361
+ // ADR-072 Ф2: дефолты из config.yaml (без runtime) — для GET/DELETE-сброса к умолчанию.
362
+ fallbackLlmGateway: {
363
+ enabled: config.synth.llmGateway.enabled,
364
+ inputMode: config.synth.llmGateway.inputMode,
365
+ logPayloads: config.synth.llmGateway.logPayloads,
366
+ rateLimit: {
367
+ userPerMinute: config.synth.llmGateway.rateLimit?.userPerMinute ?? DEFAULT_LLM_GATEWAY_RATE_LIMIT.userPerMinute,
368
+ providerPerMinute: config.synth.llmGateway.rateLimit?.providerPerMinute ?? DEFAULT_LLM_GATEWAY_RATE_LIMIT.providerPerMinute,
369
+ },
370
+ },
371
+ fallbackSecurity: {
372
+ protectedPaths: { enabled: config.synth.security.protectedPaths?.enabled ?? true },
373
+ // ADR-029: askTimeoutMs живёт в permission-секции конфига (не в security).
374
+ askTimeoutMs: config.synth.permission?.askTimeoutMs,
375
+ },
376
+ // ADR-036: live-применение тумблера LLM Gateway из UI — без рестарта сервера.
377
+ onLlmGatewayChange: async (runtime) => {
378
+ const merged = mergeLlmGatewayConfig(config.synth.llmGateway, runtime);
379
+ orchestrator.setGatewayConfig(merged);
380
+ },
381
+ // live-применение тумблера защищённых путей из UI — без рестарта сервера.
382
+ onSecurityChange: async (runtime) => {
383
+ const merged = mergeSecurityConfig(config.synth.security, runtime);
384
+ orchestrator.setSecurityConfig(merged);
385
+ },
386
+ // ADR-071 §2.3: live-применение политики встроенных инструментов из админки.
387
+ fallbackToolsPolicy: config.synth.tools.policy,
388
+ onToolsPolicyChange: async (policy) => {
389
+ orchestrator.setToolsPolicy(policy);
390
+ },
391
+ // ADR-071 §2.3: live-применение политики MCP-инструментов из админки.
392
+ fallbackMcpPolicy: config.synth.mcp.policy,
393
+ onMcpPolicyChange: async (policy) => {
394
+ orchestrator.setMcpPolicy(policy);
395
+ },
396
+ // ADR-071 §2.6: live-применение instance-wide отключения инструментов.
397
+ fallbackToolsDisabled: config.synth.tools.disabled,
398
+ onToolsDisabledChange: async (disabled) => {
399
+ orchestrator.setToolsDisabled(disabled);
400
+ },
401
+ knownTools: () => toolRegistry.list().map((tool) => ({
402
+ name: tool.name,
403
+ capabilities: [...tool.capabilities],
404
+ })),
405
+ // ADR-071 §2.3.1: live-применение политики сетевого доступа MCP из админки.
406
+ fallbackMcpNetworkPolicy: config.synth.mcp.networkPolicy,
407
+ onMcpNetworkPolicyChange: async (policy) => {
408
+ live.setNetworkPolicy(policy);
409
+ },
410
+ // ADR-089: дефолт config.yaml для GET/DELETE-сброса раздела «События».
411
+ fallbackEvents: config.synth.events,
412
+ // ADR-089: live-применение runtime-настроек «События» — Router/funnel/pruner.
413
+ onEventsChange: (effective) => {
414
+ live.setEvents(effective);
415
+ },
416
+ // ADR-084: дефолт config.yaml для GET/DELETE-сброса decision-слоя.
417
+ fallbackDecision: config.synth.decision,
418
+ // ADR-084: live-применение runtime-настроек decision-слоя — микро-каскад и
419
+ // роутер читают конфиг геттером оркестратора; события — через `live.setEvents`.
420
+ onDecisionChange: (effective) => {
421
+ live.setDecision(effective);
422
+ },
423
+ protectedPathsStore,
424
+ }, {
425
+ // ADR-089: мутации раздела «События» — только ADMIN (managed RBAC).
426
+ eventsWriteGuard: auth.requirePermission('ADMIN'),
427
+ // ADR-084: мутации decision-слоя — только ADMIN (managed RBAC).
428
+ decisionWriteGuard: auth.requirePermission('ADMIN'),
429
+ }));
430
+ // Словари классификации: чтение — все авторизованные, запись/сброс — ADMIN
431
+ // (тот же guard, что у users.ts). Реализация общая с core.
432
+ const dictionaryStore = new DictionaryStore(dataDir);
433
+ app.route('/api/v2/dictionaries', createDictionaryRoutes(auth, dictionaryStore, { writeGuard: auth.requireAdmin }));
434
+ // ADR-069 §9.3: прозрачность проектных инструкций — core-фабрика (резолвер не
435
+ // дублируется). RBAC: сессия — владелец|ADMIN (canAccess, как в session-роутах);
436
+ // проект — owner/LEAD/ADMIN (canAccessProject, как в project-скиллах).
437
+ const instructionsInfoResolver = createInstructionsInfoResolver(new ProjectInstructionsResolver({
438
+ config: config.synth.instructions,
439
+ dictionaryStore,
440
+ dataDir,
441
+ trustedProjectDirs: config.synth.skills.trustedProjectDirs,
442
+ // ADR-069 R3: авто-trust workspace внутри workspacesRoot (managed-каталоги).
443
+ workspacesRoot: config.workspacesRoot,
444
+ }), config.synth.instructions);
445
+ app.route('/api/v2/context', createCoreContextRoutes(auth, {
446
+ resolveInstructions: instructionsInfoResolver,
447
+ sessionManager,
448
+ projectStore,
449
+ resolveProjectWorkspace: resolveSkillWorkspace,
450
+ resolveContextWindow: (session) => {
451
+ const model = session?.settings.model;
452
+ return model ? modelWindowLoader(model) || undefined : undefined;
453
+ },
454
+ resolveUserId: async (c) => (await auth.getCurrentUser(c))?.id ?? '',
455
+ canAccess: (session, c, userId) => (session.ownerId ?? session.userId) === userId
456
+ || auth.isAdmin(c),
457
+ canAccessProject: (project, c, userId) => auth.isAdmin(c)
458
+ || auth.hasRole(c, 'LEAD')
459
+ || project.ownerId === userId
460
+ || project.members?.[userId] === ProjectRole.OWNER,
461
+ }));
462
+ // Глобальный SSE-хаб для всех сессий пользователя (ADR-052: `events:watch`).
463
+ registerEventsSse(app, { auth, eventHub, scopeGuard });
464
+ // Admin routes (кроме graceful shutdown — он живёт в main.ts, т.к. требует server)
465
+ app.route('/api/v2/admin/debug', createDebugRoutes(auth));
466
+ }
@@ -0,0 +1,15 @@
1
+ import type { Hono } from 'hono';
2
+ import type { ScopeGuardFactory } from '@itphx/synth-core';
3
+ import type { AuthKit } from '../auth/middleware.js';
4
+ import type { EventHub } from '../events/hub.js';
5
+ export interface EventsSseDeps {
6
+ auth: AuthKit;
7
+ eventHub: EventHub;
8
+ /** ADR-052: `events:watch` — scope-гейт service-key (для интерактивных кред — no-op). */
9
+ scopeGuard: ScopeGuardFactory;
10
+ }
11
+ /**
12
+ * Зарегистрировать SSE-хаб (`GET /api/v2/events`): подписка на события сессий
13
+ * пользователя (watch-all — для service-key и ADMIN/LEAD, ADR-052 этап IV).
14
+ */
15
+ export declare function registerEventsSse(app: Hono, deps: EventsSseDeps): void;
@@ -0,0 +1,83 @@
1
+ import { getServiceCredential } from '@itphx/synth-core';
2
+ /**
3
+ * Зарегистрировать SSE-хаб (`GET /api/v2/events`): подписка на события сессий
4
+ * пользователя (watch-all — для service-key и ADMIN/LEAD, ADR-052 этап IV).
5
+ */
6
+ export function registerEventsSse(app, deps) {
7
+ const { auth, eventHub, scopeGuard } = deps;
8
+ // Глобальный SSE-хаб для всех сессий пользователя.
9
+ // ADR-052: `events:watch` — scope service-key для подписки на поток событий.
10
+ app.get('/api/v2/events', auth.requireAuth, scopeGuard('events:watch'), async (c) => {
11
+ const user = (await auth.getCurrentUser(c));
12
+ const signal = c.req.raw.signal;
13
+ // ADR-052 (этап IV) / ADR-089: машинный watcher (service-key со scope
14
+ // `events:watch`) и роли сквозного обзора ADMIN/LEAD получают события ВСЕХ
15
+ // сессий (паритет со standalone-core `subscribeAll`), обычный пользователь —
16
+ // только своих. Без этого синтетический `service:<keyId>` шлюза не владеет
17
+ // сессиями → подписок 0 → ответы агента не доходят до Telegram.
18
+ const allSessions = Boolean(getServiceCredential(c)) || auth.hasRole(c, 'ADMIN', 'LEAD');
19
+ return new Response(new ReadableStream({
20
+ async start(controller) {
21
+ const encoder = new TextEncoder();
22
+ const sseClient = {
23
+ userId: user.id,
24
+ username: user.username,
25
+ allSessions,
26
+ send(event) {
27
+ try {
28
+ const line = `data: ${JSON.stringify(event)}\n\n`;
29
+ controller.enqueue(encoder.encode(line));
30
+ }
31
+ catch {
32
+ // client disconnected
33
+ }
34
+ },
35
+ };
36
+ try {
37
+ console.log(`[SSE /api/v2/events] Connected: user=${user.username} allSessions=${allSessions}`);
38
+ await eventHub.registerClient(sseClient);
39
+ // Keepalive: раз в 30 секунд отправляем комментарий для предотвращения разрыва
40
+ const keepalive = setInterval(() => {
41
+ try {
42
+ controller.enqueue(encoder.encode(':keepalive\n\n'));
43
+ }
44
+ catch {
45
+ clearInterval(keepalive);
46
+ }
47
+ }, 30_000);
48
+ // Keep connection alive until abort or disconnect
49
+ try {
50
+ await new Promise((resolve) => {
51
+ if (signal.aborted) {
52
+ resolve();
53
+ return;
54
+ }
55
+ signal.addEventListener('abort', () => resolve(), { once: true });
56
+ });
57
+ }
58
+ finally {
59
+ clearInterval(keepalive);
60
+ }
61
+ }
62
+ catch (err) {
63
+ console.error('[SSE /api/v2/events] Error:', err);
64
+ }
65
+ finally {
66
+ eventHub.unregisterClient(sseClient);
67
+ try {
68
+ controller.close();
69
+ }
70
+ catch { /* already closed */ }
71
+ }
72
+ },
73
+ }), {
74
+ status: 200,
75
+ headers: {
76
+ 'Content-Type': 'text/event-stream',
77
+ 'Cache-Control': 'no-cache',
78
+ 'Connection': 'keep-alive',
79
+ 'X-Accel-Buffering': 'no',
80
+ },
81
+ });
82
+ });
83
+ }
package/dist/app.d.ts CHANGED
@@ -1,11 +1,10 @@
1
1
  import { createServer } from 'node:http';
2
2
  import { WebSocketServer } from 'ws';
3
3
  import { Hono } from 'hono';
4
- import { SessionManager, EventBus, QueueProcessorManager, ChatOrchestrator, RuntimeSettingsStore } from '@itphx/synth-core';
4
+ import type { EventBus, SessionManager, QueueProcessorManager, ChatOrchestrator, ProjectStore, RuntimeSettingsStore, EventRouter, RequestSessionService, EventBindingStore, EventJournalStore, EventIngress, ScheduleStore, SchedulerService, WebhookStore, WebhookService } from '@itphx/synth-core';
5
5
  import type { BackendConfig } from './lib/app-config.js';
6
6
  import type { AuthKit } from './auth/middleware.js';
7
- import { ProjectStore } from '@itphx/synth-core';
8
- import { EventHub } from './events/hub.js';
7
+ import type { EventHub } from './events/hub.js';
9
8
  export interface CreateBackendAppOptions {
10
9
  /** Путь к config.yaml (по умолчанию — каскадный поиск, как в main.ts). */
11
10
  configPath?: string;
@@ -33,6 +32,28 @@ export interface BackendAppHandle {
33
32
  orchestrator: ChatOrchestrator;
34
33
  queueManager: QueueProcessorManager;
35
34
  settingsStore: RuntimeSettingsStore;
35
+ eventRouter: EventRouter;
36
+ requestSessionService: RequestSessionService;
37
+ eventBindingStore: EventBindingStore;
38
+ eventJournal: EventJournalStore;
39
+ /** ADR-089: ingress-точка приёма внешних событий. */
40
+ ingress: EventIngress;
41
+ scheduleStore: ScheduleStore;
42
+ scheduler: SchedulerService;
43
+ /** ADR-051 (срез): остановка планировщика (на graceful shutdown). */
44
+ stopScheduler: () => void;
45
+ /** ADR-089: остановка sweeper'а авто-архивации ephemeral-сессий. */
46
+ stopEphemeralSweeper: () => void;
47
+ /** ADR-089: остановка периодической retention-очистки журнала событий. */
48
+ stopEventJournalPruner: () => void;
49
+ /** ADR-052 (этап II): реестр подписок webhooks (для тестов/диагностики). */
50
+ webhookStore: WebhookStore;
51
+ /** ADR-052 (этап II): движок исходящих webhooks. */
52
+ webhookService: WebhookService;
53
+ /** ADR-052 (этап II): остановка движка webhooks (на graceful shutdown). */
54
+ stopWebhookService: () => void;
55
+ /** ADR-052 (этап II): остановка retention-очистки журнала доставок. */
56
+ stopWebhookDeliveryPruner: () => void;
36
57
  /**
37
58
  * Поднять HTTP-сервер (+ WebSocket /ws/events) на указанном порту.
38
59
  * Порт 0 → эфемерный; возвращает фактический порт.
@@ -43,4 +64,9 @@ export interface BackendAppHandle {
43
64
  port: number;
44
65
  }>;
45
66
  }
67
+ /**
68
+ * Backend-приложение Synth (managed): `createBackendApp` без прослушивания порта.
69
+ * Фасад-композиция: зависимости — `app/deps.ts`, порядок монтирования роутов —
70
+ * `app/mount-routes.ts`, SSE-хаб — `app/sse-events.ts`, HTTP/WS — `app/listen.ts`.
71
+ */
46
72
  export declare function createBackendApp(opts?: CreateBackendAppOptions): Promise<BackendAppHandle>;