@itphx/synth-backend 0.10.1 → 0.11.3
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.
- package/dist/app/bootstrap.d.ts +2 -2
- package/dist/app/deps.d.ts +50 -32
- package/dist/app/deps.js +233 -99
- package/dist/app/listen.d.ts +7 -2
- package/dist/app/listen.js +12 -1
- package/dist/app/mount-routes.d.ts +16 -3
- package/dist/app/mount-routes.js +258 -28
- package/dist/app.d.ts +16 -7
- package/dist/app.js +104 -11
- package/dist/auth/guards.d.ts +2 -1
- package/dist/auth/guards.js +9 -1
- package/dist/auth/middleware.d.ts +2 -12
- package/dist/auth/middleware.js +20 -2
- package/dist/auth/oidc.d.ts +7 -0
- package/dist/auth/oidc.js +27 -6
- package/dist/auth/service-scope.d.ts +7 -3
- package/dist/auth/service-scope.js +8 -4
- package/dist/events/hub.js +3 -38
- package/dist/lib/app-config.d.ts +2 -0
- package/dist/lib/app-config.js +3 -2
- package/dist/lib/defaults-store.d.ts +2 -25
- package/dist/lib/defaults-store.js +5 -87
- package/dist/lib/i18n.js +48 -0
- package/dist/main.js +19 -3
- package/dist/routes/agents.d.ts +2 -2
- package/dist/routes/auth.d.ts +2 -2
- package/dist/routes/context.d.ts +2 -2
- package/dist/routes/gateway-patterns.d.ts +2 -2
- package/dist/routes/llm.d.ts +8 -2
- package/dist/routes/llm.js +4 -1
- package/dist/routes/mcp-registry.d.ts +3 -3
- package/dist/routes/mcp-registry.js +2 -2
- package/dist/routes/messages.d.ts +5 -4
- package/dist/routes/messages.js +30 -3
- package/dist/routes/models.d.ts +7 -2
- package/dist/routes/models.js +3 -1
- package/dist/routes/projects.d.ts +3 -3
- package/dist/routes/providers.d.ts +15 -3
- package/dist/routes/providers.js +33 -21
- package/dist/routes/queue.d.ts +5 -4
- package/dist/routes/queue.js +30 -3
- package/dist/routes/sessions.d.ts +13 -3
- package/dist/routes/sessions.js +197 -73
- package/dist/test-helpers/close-server.d.ts +33 -0
- package/dist/test-helpers/close-server.js +50 -0
- package/package.json +3 -3
package/dist/app/mount-routes.js
CHANGED
|
@@ -4,8 +4,8 @@
|
|
|
4
4
|
// SSE-хаб `/api/v2/events` после роутов событий, но до admin-роутов).
|
|
5
5
|
// Вынесено из `app.ts` (ADR-095, шаг 4b) — «вынос по швам», без изменения поведения.
|
|
6
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,
|
|
7
|
+
import { DEFAULT_LLM_GATEWAY_RATE_LIMIT, ProjectRole, SYNTH_VERSION, resolveSecretKey, resolveStorageBackend, resolvePostgresConfig, resolvePostgresPassword } from '@itphx/synth-shared';
|
|
8
|
+
import { DEFAULT_AGENT_ID, RateLimiter, getPublicOpenApiDocument, createFsRoutes, createGitRoutes, createSshKeyRoutes, createAgentSshKeyRoutes, createEventRoutes, createSchedulerRoutes, createServiceKeyRoutes, createWebhookRoutes, mergeLlmGatewayConfig, mergeSecurityConfig, createSkillRoutes, createCommandRoutes, createSkillBundleRoutes, createSessionSkillScopeRoutes, createProjectSkillScopeRoutes, createSkillSettingsRoutes, createIdentityRoutes, createMaintenanceRoutes, createAnalyticsRoutes, AnalyticsService, createProjectPortableRoutes, createStorageContextAsync, ProjectInstructionsResolver, createInstructionsInfoResolver, createSettingsRoutes, createDictionaryRoutes, createAuditRoutes as createSecurityAuditRoutes, currentEgressLog, createContextRoutes as createCoreContextRoutes, createMetricsSettingsRoutes, resolveProjectWorkspace, } from '@itphx/synth-core';
|
|
9
9
|
import { createProjectRoutes, createProjectAccess } from '../routes/projects.js';
|
|
10
10
|
import { createSessionRoutes } from '../routes/sessions.js';
|
|
11
11
|
import { createMessageRoutes } from '../routes/messages.js';
|
|
@@ -22,7 +22,7 @@ import { createLogsRoutes, resolveLogDir } from '../routes/logs.js';
|
|
|
22
22
|
import { createGatewayPatternsRoutes } from '../routes/gateway-patterns.js';
|
|
23
23
|
import { createLlmRoutes } from '../routes/llm.js';
|
|
24
24
|
import { createRateLimiter } from '../middleware/rate-limiter.js';
|
|
25
|
-
import { scopeGuard,
|
|
25
|
+
import { scopeGuard, serviceProjectProjection } from '../auth/service-scope.js';
|
|
26
26
|
import { requireAdminOrScope } from '../auth/guards.js';
|
|
27
27
|
import { t, getTranslations } from '../lib/i18n.js';
|
|
28
28
|
import { registerEventsSse } from './sse-events.js';
|
|
@@ -31,8 +31,15 @@ import { registerEventsSse } from './sse-events.js';
|
|
|
31
31
|
* i18n-эндпоинты) в порядке, идентичном прежнему `createBackendApp`.
|
|
32
32
|
*/
|
|
33
33
|
export function mountBackendRoutes(app, auth, ctx) {
|
|
34
|
-
const { config, deps
|
|
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;
|
|
34
|
+
const { config, deps } = 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, 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, } = deps;
|
|
36
|
+
/**
|
|
37
|
+
* Fallback-пара «модель по умолчанию» из config (`llm.defaultProvider` +
|
|
38
|
+
* `llm.defaultModel`) — только если заданы оба.
|
|
39
|
+
*/
|
|
40
|
+
const backendConfigDefaultModel = () => config.synth.llm.defaultProvider && config.synth.llm.defaultModel
|
|
41
|
+
? { provider: config.synth.llm.defaultProvider, model: config.synth.llm.defaultModel }
|
|
42
|
+
: null;
|
|
36
43
|
// API-заглушки для UI
|
|
37
44
|
app.get('/api/config/themes', (c) => c.json({ themes: [] }));
|
|
38
45
|
// i18n endpoints
|
|
@@ -48,12 +55,65 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
48
55
|
app.get('/api/v2/openapi.json', auth.requireAuth, (c) => c.json(getPublicOpenApiDocument()));
|
|
49
56
|
// Projects routes
|
|
50
57
|
app.route('/api/v2/projects', createProjectRoutes(auth, projectStore, sessionManager, config.workspacesRoot, mcpManager, skillService, settingsStore, mcpRegistryStore));
|
|
58
|
+
// ADR-091 (этап 2): портативный экспорт/импорт проекта (скачать/загрузить архив).
|
|
59
|
+
// Managed RBAC: скачивание — право чтения проекта (owner/участник/LEAD/ADMIN),
|
|
60
|
+
// импорт в существующий проект (`mergeInto`) — право редактирования; создание
|
|
61
|
+
// нового проекта — любая аутентифицированная роль. Владелец новых сущностей —
|
|
62
|
+
// текущий пользователь; хаб подписывается на импортированные сессии
|
|
63
|
+
// (ADR-089, инвариант 18).
|
|
64
|
+
app.route('/api/v2/projects', createProjectPortableRoutes({ requireAuth: auth.requireAuth }, {
|
|
65
|
+
dataDir,
|
|
66
|
+
// PROP-032: экспорт/импорт проекта работают через контекст хранения
|
|
67
|
+
// инстанса (иначе — свой файловый контекст, а на `backend=postgres`
|
|
68
|
+
// проект не найден бы).
|
|
69
|
+
storage: deps.storageContext,
|
|
70
|
+
getProject: (id) => projectStore.load(id),
|
|
71
|
+
canRead: async (c, projectId) => {
|
|
72
|
+
const user = await auth.getCurrentUser(c);
|
|
73
|
+
if (!user)
|
|
74
|
+
return false;
|
|
75
|
+
const project = await projectStore.load(projectId);
|
|
76
|
+
return project ? projectAccess.canReadProject(c, project, user.id) : false;
|
|
77
|
+
},
|
|
78
|
+
canEdit: async (c, projectId) => {
|
|
79
|
+
const user = await auth.getCurrentUser(c);
|
|
80
|
+
if (!user)
|
|
81
|
+
return false;
|
|
82
|
+
const project = await projectStore.load(projectId);
|
|
83
|
+
return project ? projectAccess.canEditProjectContent(c, project, user.id) : false;
|
|
84
|
+
},
|
|
85
|
+
// security-фикс 0.11.3: экспорт проекта по умолчанию БЕЗ секретов сессий
|
|
86
|
+
// (карта обфускации LLM Gateway + `metadata.secrets`). Явный opt-in
|
|
87
|
+
// `?withSecrets=true` — только elevated (ADMIN/LEAD): архив проекта
|
|
88
|
+
// содержит сессии других участников, а карта обфускации — это секрет.
|
|
89
|
+
canExportSecrets: (c) => auth.isAdmin(c) || auth.hasRole(c, 'LEAD'),
|
|
90
|
+
audit: maintenanceAudit,
|
|
91
|
+
maxUploadBytes: config.maxUploadBytes,
|
|
92
|
+
resolveOwnerId: (c) => {
|
|
93
|
+
const user = c.get('user');
|
|
94
|
+
return user?.id;
|
|
95
|
+
},
|
|
96
|
+
onSessionCreated: (sessionId, ownerId) => {
|
|
97
|
+
void eventHub.subscribeToSession(ownerId, sessionId);
|
|
98
|
+
},
|
|
99
|
+
messages: {
|
|
100
|
+
forbidden: (c) => t('auth.forbidden', undefined, c),
|
|
101
|
+
notFound: (c) => t('errors.notFound.project', undefined, c),
|
|
102
|
+
invalidBody: (c) => t('errors.validation.projectImportBody', undefined, c),
|
|
103
|
+
invalidArchive: (c) => t('errors.validation.invalidProjectArchive', undefined, c),
|
|
104
|
+
checksumMismatch: (c) => t('errors.validation.projectArchiveChecksum', undefined, c),
|
|
105
|
+
nameConflict: (c) => t('errors.conflict.projectNameInUse', undefined, c),
|
|
106
|
+
confirmRequired: (c) => t('errors.validation.maintenanceConfirmRequired', undefined, c),
|
|
107
|
+
workspaceError: (c) => t('errors.validation.projectWorkspaceRestore', undefined, c),
|
|
108
|
+
payloadTooLarge: (c) => t('errors.payloadTooLarge', undefined, c),
|
|
109
|
+
},
|
|
110
|
+
}));
|
|
51
111
|
// Sessions routes
|
|
52
|
-
app.route('/api/v2/sessions', createSessionRoutes(auth, sessionManager, eventBus, queueManager, processMessage, orchestrator, eventHub, contextOptimizer, projectStore, profilesStore, getDefaultAgentId, requestSessionService));
|
|
112
|
+
app.route('/api/v2/sessions', createSessionRoutes(auth, sessionManager, eventBus, queueManager, processMessage, orchestrator, eventHub, contextOptimizer, projectStore, profilesStore, getDefaultAgentId, requestSessionService, analytics));
|
|
53
113
|
// Messages routes
|
|
54
|
-
app.route('/api/v2/messages', createMessageRoutes(auth, sessionManager, contextOptimizer, eventBus));
|
|
114
|
+
app.route('/api/v2/messages', createMessageRoutes(auth, sessionManager, contextOptimizer, eventBus, projectStore));
|
|
55
115
|
// Queue routes
|
|
56
|
-
app.route('/api/v2/queue', createQueueRoutes(auth, sessionManager, queueManager, eventBus, processMessage));
|
|
116
|
+
app.route('/api/v2/queue', createQueueRoutes(auth, sessionManager, queueManager, eventBus, processMessage, projectStore));
|
|
57
117
|
// FS routes (ADR-075): core-фабрика, managed поверх workspace проекта.
|
|
58
118
|
// ADR-089 (P0): доступ к проекту обязателен — иначе любой USER читал/писал бы
|
|
59
119
|
// файлы чужого проекта по id (IDOR). Чтение — canRead, мутации — canEditContent.
|
|
@@ -62,6 +122,8 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
62
122
|
requireProjectId: true,
|
|
63
123
|
getOutsideRootPolicy: () => 'deny',
|
|
64
124
|
getProtectedPathsPolicy: () => protectedPathsStore.getPolicy(),
|
|
125
|
+
// Лимит загрузки: config/env (resolveMaxUploadBytes), иначе дефолт фабрики.
|
|
126
|
+
maxUploadBytes: config.maxUploadBytes,
|
|
65
127
|
authorizeProject: async (c, projectId) => {
|
|
66
128
|
const user = await auth.getCurrentUser(c);
|
|
67
129
|
if (!user)
|
|
@@ -81,9 +143,15 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
81
143
|
}),
|
|
82
144
|
}));
|
|
83
145
|
// Providers routes
|
|
84
|
-
app.route('/api/v2/providers', createProviderRoutes(auth, providerStore, providerCache
|
|
146
|
+
app.route('/api/v2/providers', createProviderRoutes(auth, providerStore, providerCache, {
|
|
147
|
+
resolvePolicy: () => egressResolver.resolveTools(),
|
|
148
|
+
log: currentEgressLog(),
|
|
149
|
+
}, async () => (await settingsStore.getDefaultModel()) ?? backendConfigDefaultModel()));
|
|
85
150
|
// Models routes
|
|
86
|
-
app.route('/api/v2/models', createModelRoutes(auth, modelStore, providerStore, modelCache, providerCache
|
|
151
|
+
app.route('/api/v2/models', createModelRoutes(auth, modelStore, providerStore, modelCache, providerCache, {
|
|
152
|
+
getDefaultModel: async () => (await settingsStore.getDefaultModel()) ?? backendConfigDefaultModel(),
|
|
153
|
+
setDefaultModel: (pair) => settingsStore.setDefaultModel(pair),
|
|
154
|
+
}));
|
|
87
155
|
// Agents routes
|
|
88
156
|
app.route('/api/v2/agents', createAgentRoutes(auth, agentStore, agentRegistry, getDefaultAgentId));
|
|
89
157
|
// Context routes (глобальные identity-файлы; админ-мутации)
|
|
@@ -92,7 +160,10 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
92
160
|
app.route('/api/v2/users', createUserRoutes(auth, profilesStore));
|
|
93
161
|
// Git routes (ADR-076 §T4): core-фабрика + managed RBAC. Write-эндпоинты
|
|
94
162
|
// (init/clone/register/remove/fetch) требуют прав на изменение контента
|
|
95
|
-
// проекта (owner/EDITOR/LEAD/ADMIN); read-only (scan/log/commit) —
|
|
163
|
+
// проекта (owner/EDITOR/LEAD/ADMIN); read-only (scan/log/commit) — права
|
|
164
|
+
// чтения проекта (owner/участник/LEAD/ADMIN). Проверка — граничный guard
|
|
165
|
+
// core-фабрики (ADR-089, инвариант 16): без неё любой аутентифицированный
|
|
166
|
+
// читал бы git-данные чужого проекта по его id.
|
|
96
167
|
app.route('/api/v2/git', createGitRoutes(auth, projectStore, config.workspacesRoot, {
|
|
97
168
|
sshKeyStore,
|
|
98
169
|
authorizeProject: async (c, projectId) => {
|
|
@@ -104,6 +175,15 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
104
175
|
return false;
|
|
105
176
|
return projectAccess.canEditProjectContent(c, project, user.id);
|
|
106
177
|
},
|
|
178
|
+
authorizeRead: async (c, projectId) => {
|
|
179
|
+
const user = await auth.getCurrentUser(c);
|
|
180
|
+
if (!user)
|
|
181
|
+
return false;
|
|
182
|
+
const project = await projectStore.load(projectId);
|
|
183
|
+
if (!project)
|
|
184
|
+
return false;
|
|
185
|
+
return projectAccess.canReadProject(c, project, user.id);
|
|
186
|
+
},
|
|
107
187
|
}));
|
|
108
188
|
// SSH-ключи агентов (ADR-076 §T5): core-фабрика + managed RBAC.
|
|
109
189
|
// Ключи — секреты: чтение — requireAuth (глобально), запись — только ADMIN.
|
|
@@ -128,7 +208,7 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
128
208
|
keyReadGuard: auth.requirePermission('ADMIN', 'LEAD'),
|
|
129
209
|
// ADR-052 (этап I): scope-гейт и проектная проекция service-key (i18n-403).
|
|
130
210
|
scopeGuard,
|
|
131
|
-
|
|
211
|
+
serviceProjectProjection,
|
|
132
212
|
// ADR-089/ADR-052: per-key rate limit и мастер-выключатель приёма (live).
|
|
133
213
|
getKeyRateLimitPerMinute: () => live.getEvents().keyRateLimitPerMinute,
|
|
134
214
|
isEnabled: () => live.getEvents().enabled,
|
|
@@ -170,7 +250,7 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
170
250
|
// ADR-052 (этап I): scope-гейт, проектная проекция и резолвинг
|
|
171
251
|
// projectId `bound`/`queue`-целей расписания.
|
|
172
252
|
scopeGuard,
|
|
173
|
-
|
|
253
|
+
serviceProjectProjection,
|
|
174
254
|
resolveSessionProject: async (id) => (await sessionManager.getSession(id))?.projectId,
|
|
175
255
|
}));
|
|
176
256
|
// ADR-052 (этап I): CRUD service-key инстанса (`synth_svc_…`). Managed RBAC:
|
|
@@ -200,7 +280,8 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
200
280
|
return user?.id ?? 'unknown';
|
|
201
281
|
},
|
|
202
282
|
isEnabled: () => webhooksConfig.enabled,
|
|
203
|
-
|
|
283
|
+
// Отдельный экземпляр политики (live; граница доверия не смешивается с tools).
|
|
284
|
+
resolvePolicy: () => egressResolver.resolveWebhooks(),
|
|
204
285
|
messages: {
|
|
205
286
|
invalid: (c) => t('errors.validation.invalidWebhook', undefined, c),
|
|
206
287
|
notFound: (c) => t('errors.notFound.webhook', undefined, c),
|
|
@@ -209,11 +290,69 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
209
290
|
disabled: (c) => t('errors.unavailable.webhooksDisabled', undefined, c),
|
|
210
291
|
},
|
|
211
292
|
}));
|
|
293
|
+
// ADR-091/ADR-092: обслуживание инстанса (backup/restore/doctor/migrate).
|
|
294
|
+
// Managed RBAC: только ADMIN — операции меняют/отдают данные всего инстанса
|
|
295
|
+
// (архивы могут содержать секреты), i18n.
|
|
296
|
+
// PROP-032: при backend=postgres doctor/migrations ходят в БД через read-only
|
|
297
|
+
// пробу (контекст в режиме `skip` — миграции не применяются).
|
|
298
|
+
const maintenanceBackend = resolveStorageBackend(config.synth, process.env);
|
|
299
|
+
const withPostgresContext = maintenanceBackend === 'postgres'
|
|
300
|
+
? async (fn) => {
|
|
301
|
+
const ctx = await createStorageContextAsync('postgres', {
|
|
302
|
+
dataDir,
|
|
303
|
+
secretKey: resolveSecretKey(config.synth),
|
|
304
|
+
env: process.env,
|
|
305
|
+
postgres: resolvePostgresConfig(config.synth, process.env),
|
|
306
|
+
postgresPassword: resolvePostgresPassword({ dataDir }, process.env),
|
|
307
|
+
postgresSchemaMode: 'skip',
|
|
308
|
+
});
|
|
309
|
+
try {
|
|
310
|
+
return await fn(ctx);
|
|
311
|
+
}
|
|
312
|
+
finally {
|
|
313
|
+
await ctx.close?.();
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
: undefined;
|
|
317
|
+
app.route('/api/v2/maintenance', createMaintenanceRoutes({ requireAuth: auth.requireAuth }, {
|
|
318
|
+
dataDir,
|
|
319
|
+
secretKey: resolveSecretKey(config.synth),
|
|
320
|
+
env: process.env,
|
|
321
|
+
audit: maintenanceAudit,
|
|
322
|
+
storageBackend: maintenanceBackend,
|
|
323
|
+
...(withPostgresContext
|
|
324
|
+
? {
|
|
325
|
+
dbHealth: () => withPostgresContext((ctx) => (ctx.health ? ctx.health() : Promise.resolve({ ok: false, error: 'нет health()' }))),
|
|
326
|
+
schemaMigrations: (o) => withPostgresContext((ctx) => ctx.schemaMigrations ? ctx.schemaMigrations(o) : Promise.reject(new Error('нет schemaMigrations()'))),
|
|
327
|
+
}
|
|
328
|
+
: {}),
|
|
329
|
+
}, {
|
|
330
|
+
writeGuard: auth.requirePermission('ADMIN'),
|
|
331
|
+
readGuard: auth.requirePermission('ADMIN'),
|
|
332
|
+
maxUploadBytes: config.maxUploadBytes,
|
|
333
|
+
resolveUserId: (c) => {
|
|
334
|
+
const user = c.get('user');
|
|
335
|
+
return user?.id ?? 'unknown';
|
|
336
|
+
},
|
|
337
|
+
messages: {
|
|
338
|
+
invalidBody: (c) => t('errors.validation.invalidMaintenanceBody', undefined, c),
|
|
339
|
+
confirmRequired: (c) => t('errors.validation.maintenanceConfirmRequired', undefined, c),
|
|
340
|
+
backupNotFound: (c) => t('errors.notFound.backup', undefined, c),
|
|
341
|
+
invalidBackupName: (c) => t('errors.validation.invalidBackupName', undefined, c),
|
|
342
|
+
payloadTooLarge: (c) => t('errors.payloadTooLarge', undefined, c),
|
|
343
|
+
invalidArchive: (c) => t('errors.validation.invalidRestoreArchive', undefined, c),
|
|
344
|
+
schemaTooNew: (c) => t('errors.conflict.schemaTooNew', undefined, c),
|
|
345
|
+
invalidAuditLimit: (c) => t('errors.validation.invalidAuditLimit', undefined, c),
|
|
346
|
+
invalidAuditOp: (c) => t('errors.validation.invalidAuditOp', undefined, c),
|
|
347
|
+
encryptedRestore: (c) => t('errors.validation.encryptedRestoreUnsupported', undefined, c),
|
|
348
|
+
restartUnsupported: (c) => t('errors.unavailable.restartUnsupported', undefined, c),
|
|
349
|
+
},
|
|
350
|
+
}));
|
|
212
351
|
// MCP routes (единый реестр; legacy /servers — адаптеры над ним)
|
|
213
352
|
app.route('/api/v2/mcp', createMcpRoutes(auth, mcpManager, sessionManager, {
|
|
214
353
|
registry: mcpRegistryStore,
|
|
215
|
-
|
|
216
|
-
getNetworkPolicy: () =>
|
|
354
|
+
// Политика резолвится на каждый запрос (live; исключения/режим — из стора).
|
|
355
|
+
getNetworkPolicy: () => egressResolver.resolveMcp(),
|
|
217
356
|
}));
|
|
218
357
|
// Скиллы (ADR-046 §9.1/§9.2): core-фабрика + RBAC ADMIN на запись.
|
|
219
358
|
app.route('/api/v2/skills', createSkillRoutes(auth, {
|
|
@@ -250,8 +389,10 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
250
389
|
return missing;
|
|
251
390
|
},
|
|
252
391
|
}, { writeGuard: auth.requireAdmin }));
|
|
253
|
-
// ADR-046 §4.5: scope-API скиллов. Доступ к сессии —
|
|
254
|
-
// (
|
|
392
|
+
// ADR-046 §4.5: scope-API скиллов. Доступ к сессии — та же семантика, что у
|
|
393
|
+
// `createSessionRoutes` (единая точка истины на ресурс сессии): владелец|ADMIN
|
|
394
|
+
// (`canAccess`), участник проекта (`resolveCanAccessExtra`), сквозной обзор
|
|
395
|
+
// ADMIN/LEAD (`resolveElevated`); проект — owner/LEAD/ADMIN.
|
|
255
396
|
const resolveSkillWorkspace = async (projectId) => {
|
|
256
397
|
const project = await projectStore.load(projectId);
|
|
257
398
|
if (!project?.workspace)
|
|
@@ -269,6 +410,23 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
269
410
|
resolveUserId: async (c) => (await auth.getCurrentUser(c))?.id ?? '',
|
|
270
411
|
canAccess: (session, c, userId) => (session.ownerId ?? session.userId) === userId
|
|
271
412
|
|| auth.isAdmin(c),
|
|
413
|
+
resolveElevated: (c) => auth.isAdmin(c) || auth.hasRole(c, 'LEAD'),
|
|
414
|
+
// read/write по роли в проекте (та же модель `createProjectAccess`, что и в
|
|
415
|
+
// session/message/queue-фабриках): GET — owner/любой участник, PUT — owner/EDITOR.
|
|
416
|
+
resolveCanAccessExtra: (() => {
|
|
417
|
+
const { canReadProject, canEditProjectContent } = createProjectAccess(auth);
|
|
418
|
+
return async (session, c, userId, access) => {
|
|
419
|
+
if (!session.projectId)
|
|
420
|
+
return false;
|
|
421
|
+
const project = await projectStore.load(session.projectId);
|
|
422
|
+
if (!project)
|
|
423
|
+
return false;
|
|
424
|
+
const ctx = c;
|
|
425
|
+
return access === 'read'
|
|
426
|
+
? canReadProject(ctx, project, userId)
|
|
427
|
+
: canEditProjectContent(ctx, project, userId);
|
|
428
|
+
};
|
|
429
|
+
})(),
|
|
272
430
|
}));
|
|
273
431
|
app.route('/api/v2/projects', createProjectSkillScopeRoutes(auth, {
|
|
274
432
|
sessionManager, skillService, settingsStore, projectStore,
|
|
@@ -346,6 +504,8 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
346
504
|
gatewayPayloadLogPath,
|
|
347
505
|
patternStore,
|
|
348
506
|
rateLimiter: createRateLimiter(120, 60_000),
|
|
507
|
+
// ADR-094: LLM-прокси учитывается в метриках (undefined — выключено).
|
|
508
|
+
metrics,
|
|
349
509
|
}));
|
|
350
510
|
// Settings routes (runtime-настройки для UI: workspace + mcp; переиспользуем core-реализацию)
|
|
351
511
|
app.route('/api/v2/settings', createSettingsRoutes(auth, {
|
|
@@ -358,6 +518,18 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
358
518
|
workspacePolicyReadOnly: true,
|
|
359
519
|
// Агент по умолчанию при первом развёртывании (config.yaml не задаёт — DEFAULT_AGENT_ID).
|
|
360
520
|
fallbackDefaultAgent: DEFAULT_AGENT_ID,
|
|
521
|
+
// Модель по умолчанию: fallback из config (только если заданы оба поля);
|
|
522
|
+
// runtime-пара приоритетнее. Валидация — провайдер в каталоге + модель `provider/model`.
|
|
523
|
+
fallbackDefaultModel: backendConfigDefaultModel(),
|
|
524
|
+
validateDefaultModel: async (pair) => {
|
|
525
|
+
const provider = await providerStore.load(pair.provider);
|
|
526
|
+
if (!provider)
|
|
527
|
+
return `провайдер "${pair.provider}" не найден`;
|
|
528
|
+
const model = await modelStore.load(`${pair.provider}/${pair.model}`);
|
|
529
|
+
if (!model)
|
|
530
|
+
return `модель "${pair.provider}/${pair.model}" не найдена`;
|
|
531
|
+
return true;
|
|
532
|
+
},
|
|
361
533
|
// ADR-072 Ф2: дефолты из config.yaml (без runtime) — для GET/DELETE-сброса к умолчанию.
|
|
362
534
|
fallbackLlmGateway: {
|
|
363
535
|
enabled: config.synth.llmGateway.enabled,
|
|
@@ -404,8 +576,21 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
404
576
|
})),
|
|
405
577
|
// ADR-071 §2.3.1: live-применение политики сетевого доступа MCP из админки.
|
|
406
578
|
fallbackMcpNetworkPolicy: config.synth.mcp.networkPolicy,
|
|
407
|
-
|
|
408
|
-
|
|
579
|
+
// ADR-071 §2.3.1: колбэк не нужен — `McpManager` резолвит политику из стора
|
|
580
|
+
// при каждом connect/probe (live, без стартового снимка).
|
|
581
|
+
// Egress: дефолты config.yaml для GET/DELETE-сброса + аудит изменений.
|
|
582
|
+
fallbackEgressTools: config.synth.egress.tools,
|
|
583
|
+
fallbackEgressWebhooks: config.synth.egress.webhooks,
|
|
584
|
+
// ADR-099: прокси — config-уровень, runtime-override и файл пароля.
|
|
585
|
+
fallbackProxy: config.synth.proxy,
|
|
586
|
+
// ADR-099: TLS/CA — config-уровень (read-only в UI; runtime — bootstrap).
|
|
587
|
+
fallbackTls: config.synth.security?.tls,
|
|
588
|
+
dataDir,
|
|
589
|
+
env: process.env,
|
|
590
|
+
securityAudit,
|
|
591
|
+
resolveActor: (c) => {
|
|
592
|
+
const user = c.get('user');
|
|
593
|
+
return typeof user?.id === 'string' && user.id ? user.id : 'unknown';
|
|
409
594
|
},
|
|
410
595
|
// ADR-089: дефолт config.yaml для GET/DELETE-сброса раздела «События».
|
|
411
596
|
fallbackEvents: config.synth.events,
|
|
@@ -422,21 +607,66 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
422
607
|
},
|
|
423
608
|
protectedPathsStore,
|
|
424
609
|
}, {
|
|
425
|
-
// ADR-
|
|
426
|
-
|
|
427
|
-
//
|
|
428
|
-
|
|
610
|
+
// Instance-wide настройки (ADR-072): все мутации `/api/v2/settings/*`
|
|
611
|
+
// (workspace, mcp, llm-gateway, security, tools-policy, mcp-policy,
|
|
612
|
+
// mcp-network-policy, default-agent, workspace-policy, tools-disabled,
|
|
613
|
+
// protected-paths, events, decision) — только ADMIN (managed RBAC).
|
|
614
|
+
// События/decision наследуют тот же guard (если не заданы отдельно).
|
|
615
|
+
settingsWriteGuard: auth.requirePermission('ADMIN'),
|
|
616
|
+
}));
|
|
617
|
+
// ADR-094: админ-раздел «Наблюдаемость» — runtime `metrics.enabled` (рестарт),
|
|
618
|
+
// live-статус и bearer-токен `/metrics` (write-only, применяется сразу).
|
|
619
|
+
// Managed RBAC: чтение и мутации — только ADMIN.
|
|
620
|
+
app.route('/api/v2/settings', createMetricsSettingsRoutes({ requireAuth: auth.requireAuth }, {
|
|
621
|
+
settingsStore,
|
|
622
|
+
dataDir,
|
|
623
|
+
configEnabled: config.synth.metrics.enabled,
|
|
624
|
+
runningEnabled: ctx.metrics.runningEnabled,
|
|
625
|
+
getRegistry: ctx.metrics.getRegistry,
|
|
626
|
+
getReadiness: ctx.metrics.getReadiness,
|
|
627
|
+
getStorageBackend: () => ctx.metrics.storageBackend,
|
|
628
|
+
getUptimeSec: ctx.metrics.getUptimeSec,
|
|
629
|
+
version: SYNTH_VERSION,
|
|
630
|
+
}, {
|
|
631
|
+
readGuard: auth.requirePermission('ADMIN'),
|
|
632
|
+
writeGuard: auth.requirePermission('ADMIN'),
|
|
633
|
+
}));
|
|
634
|
+
// Журналы безопасности: аудит изменений политик + внешние запросы (egress).
|
|
635
|
+
// Managed RBAC: чтение только ADMIN/AUDITOR.
|
|
636
|
+
app.route('/api/v2/audit', createSecurityAuditRoutes(auth, {
|
|
637
|
+
securityAudit,
|
|
638
|
+
egressRequests,
|
|
639
|
+
}, {
|
|
640
|
+
readGuard: auth.requirePermission('ADMIN', 'AUDITOR'),
|
|
641
|
+
}));
|
|
642
|
+
// PROP-102 (волна 1): отчёты аналитики — только чтение, данных без локализации.
|
|
643
|
+
// Managed RBAC (§7): ADMIN/LEAD — сквозной обзор; AUDITOR — чтение всех отчётов;
|
|
644
|
+
// обычный USER — принудительный фильтр оси `user` по себе (+ 403 на `decision`/`summary`).
|
|
645
|
+
app.route('/api/v2/analytics', createAnalyticsRoutes({ requireAuth: auth.requireAuth }, { service: new AnalyticsService({ repo: analyticsRollups }) }, {
|
|
646
|
+
resolveElevated: (c) => auth.isAdmin(c) || auth.hasRole(c, 'LEAD'),
|
|
647
|
+
resolveAuditor: (c) => auth.hasRole(c, 'AUDITOR'),
|
|
648
|
+
// `attachUser` уже положил пользователя в контекст — берём его id.
|
|
649
|
+
resolveUserId: (c) => {
|
|
650
|
+
const user = c.get('user');
|
|
651
|
+
return user?.id ?? '';
|
|
652
|
+
},
|
|
653
|
+
messages: {
|
|
654
|
+
invalidPeriod: (c) => t('errors.validation.invalidAnalyticsPeriod', undefined, c),
|
|
655
|
+
invalidRange: (c) => t('errors.validation.invalidAnalyticsRange', undefined, c),
|
|
656
|
+
invalidGroupBy: (c) => t('errors.validation.invalidAnalyticsGroupBy', undefined, c),
|
|
657
|
+
invalidOption: (c) => t('errors.validation.invalidAnalyticsOption', undefined, c),
|
|
658
|
+
forbidden: (c) => t('errors.forbidden.analytics', undefined, c),
|
|
659
|
+
},
|
|
429
660
|
}));
|
|
430
661
|
// Словари классификации: чтение — все авторизованные, запись/сброс — ADMIN
|
|
431
|
-
// (тот же guard, что у users.ts). Реализация общая с core
|
|
432
|
-
|
|
433
|
-
app.route('/api/v2/dictionaries', createDictionaryRoutes(auth, dictionaryStore, { writeGuard: auth.requireAdmin }));
|
|
662
|
+
// (тот же guard, что у users.ts). Реализация общая с core; порт — из контекста хранения.
|
|
663
|
+
app.route('/api/v2/dictionaries', createDictionaryRoutes(auth, dictionaries, { writeGuard: auth.requireAdmin }));
|
|
434
664
|
// ADR-069 §9.3: прозрачность проектных инструкций — core-фабрика (резолвер не
|
|
435
665
|
// дублируется). RBAC: сессия — владелец|ADMIN (canAccess, как в session-роутах);
|
|
436
666
|
// проект — owner/LEAD/ADMIN (canAccessProject, как в project-скиллах).
|
|
437
667
|
const instructionsInfoResolver = createInstructionsInfoResolver(new ProjectInstructionsResolver({
|
|
438
668
|
config: config.synth.instructions,
|
|
439
|
-
dictionaryStore,
|
|
669
|
+
dictionaryStore: dictionaries,
|
|
440
670
|
dataDir,
|
|
441
671
|
trustedProjectDirs: config.synth.skills.trustedProjectDirs,
|
|
442
672
|
// ADR-069 R3: авто-trust workspace внутри workspacesRoot (managed-каталоги).
|
package/dist/app.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { createServer } from 'node:http';
|
|
2
2
|
import { WebSocketServer } from 'ws';
|
|
3
3
|
import { Hono } from 'hono';
|
|
4
|
-
import
|
|
4
|
+
import { MetricsRegistry } from '@itphx/synth-core';
|
|
5
|
+
import type { EventBus, SessionManager, QueueProcessorManager, ChatOrchestrator, ProjectRepository, SettingsRepository, EventRouter, RequestSessionService, EventBindingRepository, EventJournalRepository, EventIngress, ScheduleRepository, SchedulerService, WebhookRepository, WebhookService } from '@itphx/synth-core';
|
|
5
6
|
import type { BackendConfig } from './lib/app-config.js';
|
|
6
7
|
import type { AuthKit } from './auth/middleware.js';
|
|
7
8
|
import type { EventHub } from './events/hub.js';
|
|
@@ -28,17 +29,21 @@ export interface BackendAppHandle {
|
|
|
28
29
|
eventBus: EventBus;
|
|
29
30
|
eventHub: EventHub;
|
|
30
31
|
sessionManager: SessionManager;
|
|
31
|
-
projectStore:
|
|
32
|
+
projectStore: ProjectRepository;
|
|
32
33
|
orchestrator: ChatOrchestrator;
|
|
33
34
|
queueManager: QueueProcessorManager;
|
|
34
|
-
settingsStore:
|
|
35
|
+
settingsStore: SettingsRepository;
|
|
36
|
+
/** ADR-094: реестр метрик (HTTP/процесс и доменные коллекторы). */
|
|
37
|
+
metrics: MetricsRegistry;
|
|
38
|
+
/** ADR-094: остановка процессных метрик и фоновых доменных коллекторов на shutdown. */
|
|
39
|
+
stopMetrics: () => void;
|
|
35
40
|
eventRouter: EventRouter;
|
|
36
41
|
requestSessionService: RequestSessionService;
|
|
37
|
-
eventBindingStore:
|
|
38
|
-
eventJournal:
|
|
42
|
+
eventBindingStore: EventBindingRepository;
|
|
43
|
+
eventJournal: EventJournalRepository;
|
|
39
44
|
/** ADR-089: ingress-точка приёма внешних событий. */
|
|
40
45
|
ingress: EventIngress;
|
|
41
|
-
scheduleStore:
|
|
46
|
+
scheduleStore: ScheduleRepository;
|
|
42
47
|
scheduler: SchedulerService;
|
|
43
48
|
/** ADR-051 (срез): остановка планировщика (на graceful shutdown). */
|
|
44
49
|
stopScheduler: () => void;
|
|
@@ -46,14 +51,18 @@ export interface BackendAppHandle {
|
|
|
46
51
|
stopEphemeralSweeper: () => void;
|
|
47
52
|
/** ADR-089: остановка периодической retention-очистки журнала событий. */
|
|
48
53
|
stopEventJournalPruner: () => void;
|
|
54
|
+
/** PROP-102: остановка retention-очистки суточных роллапов аналитики. */
|
|
55
|
+
stopAnalyticsRollupPruner: () => void;
|
|
49
56
|
/** ADR-052 (этап II): реестр подписок webhooks (для тестов/диагностики). */
|
|
50
|
-
webhookStore:
|
|
57
|
+
webhookStore: WebhookRepository;
|
|
51
58
|
/** ADR-052 (этап II): движок исходящих webhooks. */
|
|
52
59
|
webhookService: WebhookService;
|
|
53
60
|
/** ADR-052 (этап II): остановка движка webhooks (на graceful shutdown). */
|
|
54
61
|
stopWebhookService: () => void;
|
|
55
62
|
/** ADR-052 (этап II): остановка retention-очистки журнала доставок. */
|
|
56
63
|
stopWebhookDeliveryPruner: () => void;
|
|
64
|
+
/** Egress: остановка retention-очистки журнала внешних запросов. */
|
|
65
|
+
stopEgressLogPruner: () => void;
|
|
57
66
|
/**
|
|
58
67
|
* Поднять HTTP-сервер (+ WebSocket /ws/events) на указанном порту.
|
|
59
68
|
* Порт 0 → эфемерный; возвращает фактический порт.
|