@itphx/synth-backend 0.13.4 → 0.13.8
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/deps.d.ts +8 -0
- package/dist/app/deps.js +126 -9
- package/dist/app/mount-routes.js +155 -32
- package/dist/app/public-routes.d.ts +2 -0
- package/dist/app/public-routes.js +11 -0
- package/dist/app.d.ts +1 -1
- package/dist/app.js +31 -0
- package/dist/auth/api-key.d.ts +19 -0
- package/dist/auth/api-key.js +56 -0
- package/dist/auth/middleware.js +7 -3
- package/dist/events/hub.js +4 -1
- package/dist/init.d.ts +1 -0
- package/dist/init.js +96 -0
- package/dist/lib/app-config.js +12 -1
- package/dist/lib/bind-host.d.ts +10 -0
- package/dist/lib/bind-host.js +32 -0
- package/dist/lib/i18n.js +10 -0
- package/dist/main.js +4 -1
- package/dist/middleware/rate-limiter.d.ts +4 -1
- package/dist/middleware/rate-limiter.js +15 -2
- package/dist/routes/auth.js +5 -20
- package/dist/routes/llm.js +65 -7
- package/dist/routes/mcp-remote.d.ts +23 -0
- package/dist/routes/mcp-remote.js +152 -0
- package/dist/routes/mcp.d.ts +11 -6
- package/dist/routes/mcp.js +35 -6
- package/dist/routes/projects.d.ts +1 -1
- package/dist/routes/projects.js +11 -2
- package/dist/routes/providers.d.ts +4 -1
- package/dist/routes/providers.js +19 -99
- package/dist/routes/sessions.d.ts +15 -6
- package/dist/routes/sessions.js +257 -183
- package/package.json +4 -4
- package/dist/routes/audit.d.ts +0 -17
- package/dist/routes/audit.js +0 -64
- package/dist/routes/context.d.ts +0 -4
- package/dist/routes/context.js +0 -93
- package/dist/routes/debug.d.ts +0 -3
- package/dist/routes/debug.js +0 -30
- package/dist/routes/gateway-patterns.d.ts +0 -9
- package/dist/routes/gateway-patterns.js +0 -57
- package/dist/routes/logs.d.ts +0 -24
- package/dist/routes/logs.js +0 -100
- package/dist/routes/mcp-registry.d.ts +0 -28
- package/dist/routes/mcp-registry.js +0 -483
package/dist/app/deps.d.ts
CHANGED
|
@@ -42,6 +42,12 @@ executionConfig?: ResolvedExecutionConfig): Promise<{
|
|
|
42
42
|
defaultsStore: import("@itphx/synth-core").DefaultsRepository;
|
|
43
43
|
defaultWorkingDir: string;
|
|
44
44
|
getDefaultAgentId: () => Promise<string>;
|
|
45
|
+
/**
|
|
46
|
+
* ADR-046/ADR-069: эффективный project-trust гейт скиллов/команд/инструкций
|
|
47
|
+
* (runtime > config), снятый на старте; нужен резолверу инструкций в
|
|
48
|
+
* `mount-routes`.
|
|
49
|
+
*/
|
|
50
|
+
skillsTrustedProjectDirs: string[];
|
|
45
51
|
egressResolver: import("@itphx/synth-core").EgressPolicyResolver;
|
|
46
52
|
egressLogConfig: {
|
|
47
53
|
enabled: boolean;
|
|
@@ -78,8 +84,10 @@ executionConfig?: ResolvedExecutionConfig): Promise<{
|
|
|
78
84
|
attachmentsSettings: import("@itphx/synth-core").LiveAttachmentsSettings;
|
|
79
85
|
contextWindowSettings: import("@itphx/synth-core").LiveContextWindowPolicy;
|
|
80
86
|
subagentMaxInputTokensSettings: import("@itphx/synth-core").LiveSubagentMaxInputTokens;
|
|
87
|
+
sessionOpsPerMinuteSettings: import("@itphx/synth-core").LiveSessionOpsPerMinute;
|
|
81
88
|
contextDefaultsSettings: import("@itphx/synth-core").LiveContextDefaults;
|
|
82
89
|
stickyNotesLimitsSettings: import("@itphx/synth-core").LiveStickyNotesLimits;
|
|
90
|
+
sshModeSettings: import("@itphx/synth-core").LiveSshMode;
|
|
83
91
|
worktreeService: WorktreeService | undefined;
|
|
84
92
|
webhookStore: import("@itphx/synth-core").WebhookRepository;
|
|
85
93
|
webhookDeliveryStore: import("@itphx/synth-core").WebhookDeliveryRepository;
|
package/dist/app/deps.js
CHANGED
|
@@ -3,6 +3,7 @@
|
|
|
3
3
|
// (ADR-046), runtime-настройки (ADR-005/023).
|
|
4
4
|
// Вынесено из `app.ts` (ADR-095, шаг 4b) — «вынос по швам», без изменения поведения.
|
|
5
5
|
import { mkdir } from 'node:fs/promises';
|
|
6
|
+
import { existsSync } from 'node:fs';
|
|
6
7
|
import { join } from 'node:path';
|
|
7
8
|
import { ensureDataDir, mergeModelCompatibility, parsePrincipalId, resolveDefaultWorkspace, resolveSecretKey, resolveStorageBackend, resolvePostgresConfig, resolvePostgresPassword, resolveDegradedMode, resolveStorageFallbackDir, resolveExecutionConfig, readTlsRuntimeSettings, SYNTH_VERSION, generateId, makeTextPart, nowISO, MessageRole, } from '@itphx/synth-shared';
|
|
8
9
|
import { DEFAULT_TOOL_OUTPUT_MAX_BYTES, DEFAULT_TOOL_OUTPUT_MAX_LINES } from '@itphx/synth-shared/config';
|
|
@@ -13,10 +14,14 @@ createLiveAttachmentsSettings,
|
|
|
13
14
|
createLiveContextWindowPolicy,
|
|
14
15
|
// Бюджет промпта саб-агента (`/settings/agents-limits`).
|
|
15
16
|
createLiveSubagentMaxInputTokens,
|
|
17
|
+
// Лимит тяжёлых операций с сессиями (`/settings/limits`).
|
|
18
|
+
createLiveSessionOpsPerMinute,
|
|
16
19
|
// Дефолты оптимизации контекста новых сессий (`/settings/context-defaults`).
|
|
17
20
|
createLiveContextDefaults,
|
|
18
21
|
// Instance-wide лимиты заметок сессии (`/settings/sticky-notes`).
|
|
19
|
-
createLiveStickyNotesLimits,
|
|
22
|
+
createLiveStickyNotesLimits,
|
|
23
|
+
// PROP-124: режим инстанса для SSH-ключей (`/settings/ssh`).
|
|
24
|
+
createLiveSshMode, createEgressPolicyResolver, createEgressLogSink, configureEgressRuntime, startEgressLogPruner,
|
|
20
25
|
// ADR-105 (Ф3): источник access-токена для MCP-коннекторов + OAuth-сервис.
|
|
21
26
|
OAuthCredentialService, OAuthProviderRegistry, registerOAuthProvidersFromConfig, createRepositoryCredentialSource, SkillService, resolveProjectSkillSeed, CommandService, detectRuntimeDeps, syncProvidersFromEnv,
|
|
22
27
|
// ADR-115 × ADR-101: доступность `ffmpeg` — обработчик вложения aux-моделью шага.
|
|
@@ -34,7 +39,7 @@ createMediaRunner, ThumbnailService,
|
|
|
34
39
|
// ADR-115 × ADR-077: уборка временных каталогов медиа-раннера
|
|
35
40
|
// (`{workspacesRoot}/.synth-media/*`) — после жёсткого kill они остаются.
|
|
36
41
|
startMediaTempPruner,
|
|
37
|
-
// ADR-114: сервис worktree
|
|
42
|
+
// ADR-114: сервис worktree (per-session рабочий каталог) + публикация
|
|
38
43
|
// `worktree.updated` в каналы сессий проекта.
|
|
39
44
|
WorktreeService, publishWorktreeUpdated, startWorktreeSweeper, WebhookService, startWebhookDeliveryPruner, AnalyticsRecorder, attachAnalyticsActivityHooks, startAnalyticsRollupPruner, sessionAxes, createStorageContextAsync, initTlsTrust, applyStartupProxyConfig, attachBusMetrics, startSessionMetrics, startStorageMetrics,
|
|
40
45
|
// ADR-094/PROP-047: метрики памяти (`synth_memory_*`).
|
|
@@ -179,6 +184,12 @@ executionConfig) {
|
|
|
179
184
|
config: config.synth.context?.stickyNotes,
|
|
180
185
|
runtime: await settingsStore.getStickyNotesLimits(),
|
|
181
186
|
});
|
|
187
|
+
// PROP-124: режим инстанса для SSH-ключей (`ssh.mode`): приоритет
|
|
188
|
+
// env > runtime > config.yaml > `tools`; применяется без рестарта.
|
|
189
|
+
const sshModeSettings = createLiveSshMode({
|
|
190
|
+
config: config.synth.ssh?.mode,
|
|
191
|
+
runtime: await settingsStore.getSshMode(),
|
|
192
|
+
});
|
|
182
193
|
// ADR-102: сборщик роллапов аналитики (write-path) — только через порт слоя
|
|
183
194
|
// хранения; в деградации выключен (не пишем домен в файловый фоллбек).
|
|
184
195
|
const analytics = storageDegraded ? undefined : new AnalyticsRecorder({ repo: analyticsRollups });
|
|
@@ -265,6 +276,13 @@ executionConfig) {
|
|
|
265
276
|
config: config.synth.agents.subagentMaxInputTokens,
|
|
266
277
|
runtime: await settingsStore.getSubagentMaxInputTokens(),
|
|
267
278
|
});
|
|
279
|
+
// Лимит тяжёлых операций ресурса сессий (`limits.sessionOpsPerMinute`):
|
|
280
|
+
// приоритет env > runtime > config.yaml > 10; `0` — без лимита. Лимитеры
|
|
281
|
+
// читают значение на каждый запрос — runtime-настройка применяется без рестарта.
|
|
282
|
+
const sessionOpsPerMinuteSettings = createLiveSessionOpsPerMinute({
|
|
283
|
+
config: config.synth.limits.sessionOpsPerMinute,
|
|
284
|
+
runtime: await settingsStore.getSessionOpsPerMinute(),
|
|
285
|
+
});
|
|
268
286
|
const stopEgressLogPruner = storageDegraded || !egressLogConfig.enabled
|
|
269
287
|
? () => { }
|
|
270
288
|
: startEgressLogPruner(egressRequests, { getRetentionDays: () => egressLogConfig.retentionDays });
|
|
@@ -777,6 +795,12 @@ executionConfig) {
|
|
|
777
795
|
// ADR-046 §4.5: runtime-отключение скиллов (админка) — hard-gate системного уровня.
|
|
778
796
|
const skillsDisabled = (await settingsStore.getSkillsDisabled())
|
|
779
797
|
?? { categories: [], groups: [], skills: [] };
|
|
798
|
+
// ADR-046/ADR-069: project-trust гейт скиллов/команд/инструкций. Runtime
|
|
799
|
+
// (`settings.json`/PG) приоритетнее `config.yaml`; применяется при старте —
|
|
800
|
+
// `restartRequired` в API, инвариант 24.
|
|
801
|
+
const effectiveSkillsTrustedProjectDirs = (await settingsStore.getSkillsTrustedProjectDirs())
|
|
802
|
+
?? config.synth.skills.trustedProjectDirs
|
|
803
|
+
?? [];
|
|
780
804
|
// ADR-084: runtime/эффективный конфиг decision-слоя (админка) приоритетнее
|
|
781
805
|
// config.yaml `decision`. Live-применяется ко всем трём потребителям
|
|
782
806
|
// (микро-каскад, роутер, события ADR-089) через `live.setDecision`.
|
|
@@ -825,7 +849,7 @@ executionConfig) {
|
|
|
825
849
|
store: storageContext.skills,
|
|
826
850
|
configPaths: config.synth.skills.paths,
|
|
827
851
|
urls: config.synth.skills.urls,
|
|
828
|
-
trustedProjectDirs:
|
|
852
|
+
trustedProjectDirs: effectiveSkillsTrustedProjectDirs,
|
|
829
853
|
toolsets: config.synth.skills.toolsets,
|
|
830
854
|
});
|
|
831
855
|
// ADR-046 §7: slash-команды и bundles (mirror core).
|
|
@@ -838,7 +862,7 @@ executionConfig) {
|
|
|
838
862
|
maxArgumentsLength: config.synth.commands.maxArgumentsLength,
|
|
839
863
|
maxRenderedBytes: config.synth.commands.maxRenderedBytes,
|
|
840
864
|
toolsets: config.synth.skills.toolsets,
|
|
841
|
-
trustedProjectDirs:
|
|
865
|
+
trustedProjectDirs: effectiveSkillsTrustedProjectDirs,
|
|
842
866
|
inlineShell: config.synth.skills.inlineShell ?? false,
|
|
843
867
|
},
|
|
844
868
|
skillRuntime: skillService,
|
|
@@ -869,7 +893,7 @@ executionConfig) {
|
|
|
869
893
|
limits: { maxLogBytes: config.synth.background.logMaxBytes },
|
|
870
894
|
})
|
|
871
895
|
: undefined;
|
|
872
|
-
// ADR-114: сервис worktree
|
|
896
|
+
// ADR-114: сервис worktree (per-session рабочий каталог).
|
|
873
897
|
//
|
|
874
898
|
// Один инстанс на процесс: его получают HTTP-роуты проектов
|
|
875
899
|
// (`/projects/:id/worktrees*`), тулы `git_worktree_*` и привязка сессии
|
|
@@ -898,7 +922,7 @@ executionConfig) {
|
|
|
898
922
|
});
|
|
899
923
|
},
|
|
900
924
|
});
|
|
901
|
-
// ADR-114 §7.4: sweep осиротевших записей worktree
|
|
925
|
+
// ADR-114 §7.4: sweep осиротевших записей worktree при старте процесса
|
|
902
926
|
// (записи без каталога — их чистит и prune проекта, §7.3). Фоново: старт
|
|
903
927
|
// **не блокируется**, ошибка — в лог, процесс продолжает жить. В деградированном
|
|
904
928
|
// режиме хранилища сервиса нет — вычищать нечего.
|
|
@@ -1044,6 +1068,32 @@ executionConfig) {
|
|
|
1044
1068
|
}
|
|
1045
1069
|
return model ? model.enabled !== false : undefined;
|
|
1046
1070
|
};
|
|
1071
|
+
// Workstream A1: снимок метаданных инстанса для read-only тула `synth_info`
|
|
1072
|
+
// (managed). Секретов нет: только флаги наличия ключей/настроек.
|
|
1073
|
+
const authDebug = config.auth.debugMode === true;
|
|
1074
|
+
const oidcEnabled = config.auth.oidc?.enabled === true;
|
|
1075
|
+
const apiKeyConfigured = Boolean(config.auth.apiKey || process.env.SYNTH_API_KEY);
|
|
1076
|
+
const instanceMeta = {
|
|
1077
|
+
mode: 'managed',
|
|
1078
|
+
server: { port: config.port },
|
|
1079
|
+
auth: {
|
|
1080
|
+
mode: authDebug ? 'debug' : oidcEnabled ? 'oidc' : apiKeyConfigured ? 'api-key' : 'unknown',
|
|
1081
|
+
localKeyPresent: existsSync(join(dataDir, 'secrets/api-key')),
|
|
1082
|
+
apiKeyConfigured,
|
|
1083
|
+
oidcEnabled,
|
|
1084
|
+
debug: authDebug,
|
|
1085
|
+
},
|
|
1086
|
+
storage: {
|
|
1087
|
+
backend: resolveStorageBackend(config.synth, process.env),
|
|
1088
|
+
degraded: storageDegraded,
|
|
1089
|
+
},
|
|
1090
|
+
features: {
|
|
1091
|
+
mcp: true,
|
|
1092
|
+
metrics: config.synth.metrics.enabled === true,
|
|
1093
|
+
memory: true,
|
|
1094
|
+
restartMode: process.env.SYNTH_RESTART_MODE ?? 'disabled',
|
|
1095
|
+
},
|
|
1096
|
+
};
|
|
1047
1097
|
const orchestrator = new ChatOrchestrator({
|
|
1048
1098
|
sessionManager,
|
|
1049
1099
|
eventBus,
|
|
@@ -1053,10 +1103,39 @@ executionConfig) {
|
|
|
1053
1103
|
authorityGate: authorityGuard?.gate,
|
|
1054
1104
|
// ADR-106 Ф3: реестр подтверждений (привязка к ходу + носитель гранта).
|
|
1055
1105
|
...(approvalRegistry ? { approvalRegistry } : {}),
|
|
1106
|
+
// ADR-029: отдельное хранилище ожиданий подтверждения (ADR-096) —
|
|
1107
|
+
// персистентная копия ожидания, переживающая рестарт инстанса. Документ
|
|
1108
|
+
// сессии не трогаем: запись в него — полная замена истории, а результаты
|
|
1109
|
+
// параллельных тулов пишутся точечно (`appendMessage`, ADR-118 §4).
|
|
1110
|
+
...(storageDegraded ? {} : { pendingApprovalRepository: storageContext.pendingApprovals }),
|
|
1056
1111
|
// ADR-077: порт исполнения команд (inline — исполнение в процессе).
|
|
1057
1112
|
executionPort,
|
|
1058
1113
|
// ADR-102: сборщик `usage`/`decision` роллапов (write-path).
|
|
1059
1114
|
analytics,
|
|
1115
|
+
// Аудит выдачи сессионных shell-грантов (паттерны команд и каталоги
|
|
1116
|
+
// правила `external_directory`).
|
|
1117
|
+
onPermissionGrant: (entry) => {
|
|
1118
|
+
if (!securityAudit)
|
|
1119
|
+
return;
|
|
1120
|
+
void securityAudit.append({
|
|
1121
|
+
id: `sa_${generateId()}`,
|
|
1122
|
+
ts: nowISO(),
|
|
1123
|
+
actor: entry.actor,
|
|
1124
|
+
scope: 'permission',
|
|
1125
|
+
action: 'grant',
|
|
1126
|
+
source: 'runtime',
|
|
1127
|
+
before: null,
|
|
1128
|
+
after: {
|
|
1129
|
+
sessionId: entry.sessionId,
|
|
1130
|
+
patterns: entry.patterns,
|
|
1131
|
+
directories: entry.directories,
|
|
1132
|
+
command: entry.command,
|
|
1133
|
+
},
|
|
1134
|
+
version: 1,
|
|
1135
|
+
}).catch((err) => {
|
|
1136
|
+
console.warn(`[permission] аудит гранта не записан: ${err instanceof Error ? err.message : String(err)}`);
|
|
1137
|
+
});
|
|
1138
|
+
},
|
|
1060
1139
|
contextBuilder,
|
|
1061
1140
|
contextConfig,
|
|
1062
1141
|
providerLoader,
|
|
@@ -1069,6 +1148,11 @@ executionConfig) {
|
|
|
1069
1148
|
// (ниже, `PluginRuntime`) — блоки плагинов попадают в промпт сессии.
|
|
1070
1149
|
promptBlocks,
|
|
1071
1150
|
mcpManager,
|
|
1151
|
+
// Workstream A1: реестр MCP и снимок инстанса — read-only тулы
|
|
1152
|
+
// `synth_info`/`synth_mcp_list`/`synth_mcp_test`. Политика читается live.
|
|
1153
|
+
mcpRegistry: mcpRegistryStore,
|
|
1154
|
+
getMcpNetworkPolicy: () => egressResolver.resolveMcp(),
|
|
1155
|
+
instanceMeta,
|
|
1072
1156
|
projectStore,
|
|
1073
1157
|
// Онбординг: тул `profile_update` сохраняет ответы интервью в профиль.
|
|
1074
1158
|
profilesStore,
|
|
@@ -1165,7 +1249,7 @@ executionConfig) {
|
|
|
1165
1249
|
// ADR-069 Фаза 1: проектные инструкции (merged chain AGENTS.md).
|
|
1166
1250
|
instructionsConfig: config.synth.instructions,
|
|
1167
1251
|
// ADR-069 Фаза 2a: project-trust гейт инструкций (config.skills.trustedProjectDirs).
|
|
1168
|
-
instructionsTrustedProjectDirs:
|
|
1252
|
+
instructionsTrustedProjectDirs: effectiveSkillsTrustedProjectDirs,
|
|
1169
1253
|
// ADR-089: late-bound funnel создания сессий для тула `task` (саб-агент).
|
|
1170
1254
|
// Сервис создаётся ниже (после оркестратора) — геттер читает его в рантайме.
|
|
1171
1255
|
getRequestSessionService: () => requestSessionService,
|
|
@@ -1191,7 +1275,12 @@ executionConfig) {
|
|
|
1191
1275
|
// PROP-097: сервис фоновых шелл-процессов — тот же экземпляр, что у
|
|
1192
1276
|
// реестра и тула `execute_shell` (через `ctx.extra.processService`).
|
|
1193
1277
|
...(processService ? { processService } : {}),
|
|
1194
|
-
//
|
|
1278
|
+
// PROP-124 §0: режим инстанса для SSH-ключей (`ssh.mode`) — live-геттер:
|
|
1279
|
+
// runtime-настройка (`/api/v2/settings/ssh`) применяется без рестарта.
|
|
1280
|
+
// `tools` (дефолт) — ключ в окружение команд не попадает; `agent` — ключи
|
|
1281
|
+
// роли агента выдаются вызову `execute_shell` (эфемерный `ssh-agent`).
|
|
1282
|
+
getSshMode: () => sshModeSettings.getMode(),
|
|
1283
|
+
// ADR-114: сервис worktree — тулы `git_worktree_*` (инвентарь
|
|
1195
1284
|
// per-session рабочих каталогов проекта).
|
|
1196
1285
|
...(worktreeService ? { worktreeService } : {}),
|
|
1197
1286
|
backgroundEnabled: config.synth.background.enabled,
|
|
@@ -1207,6 +1296,24 @@ executionConfig) {
|
|
|
1207
1296
|
maxBytes: config.synth.tools.outputMaxBytes ?? DEFAULT_TOOL_OUTPUT_MAX_BYTES,
|
|
1208
1297
|
},
|
|
1209
1298
|
});
|
|
1299
|
+
// ADR-029: восстановление ожиданий подтверждения после рестарта инстанса.
|
|
1300
|
+
//
|
|
1301
|
+
// Живой реестр ожиданий живёт в памяти процесса и после рестарта пуст, а
|
|
1302
|
+
// вопрос пользователю — ещё актуально. Персистентная копия лежит в
|
|
1303
|
+
// **отдельном хранилище ожиданий** (`storage.pendingApprovals`, ADR-096) —
|
|
1304
|
+
// в документе сессии её быть не может (гонка lost update с точечной
|
|
1305
|
+
// записью истории, ADR-118 §4).
|
|
1306
|
+
//
|
|
1307
|
+
// Паттерн — тот же, что у `questionService.recoverOnStart()`: best-effort,
|
|
1308
|
+
// ошибка не роняет старт.
|
|
1309
|
+
if (!storageDegraded) {
|
|
1310
|
+
try {
|
|
1311
|
+
await orchestrator.restorePendingApprovals();
|
|
1312
|
+
}
|
|
1313
|
+
catch (err) {
|
|
1314
|
+
console.warn(`[permission] восстановление ожиданий подтверждения не удалось: ${err instanceof Error ? err.message : String(err)}`);
|
|
1315
|
+
}
|
|
1316
|
+
}
|
|
1210
1317
|
// ADR-090 (Ф5б-2): эффективный конфиг слоя = config.yaml (+env) поверх
|
|
1211
1318
|
// runtime-настроек (`settings.json`/PG): админка `/api/v2/settings/plugins`
|
|
1212
1319
|
// пишет runtime, рантайм собирается при старте (применение — рестартом,
|
|
@@ -1748,6 +1855,12 @@ executionConfig) {
|
|
|
1748
1855
|
defaultsStore,
|
|
1749
1856
|
defaultWorkingDir,
|
|
1750
1857
|
getDefaultAgentId,
|
|
1858
|
+
/**
|
|
1859
|
+
* ADR-046/ADR-069: эффективный project-trust гейт скиллов/команд/инструкций
|
|
1860
|
+
* (runtime > config), снятый на старте; нужен резолверу инструкций в
|
|
1861
|
+
* `mount-routes`.
|
|
1862
|
+
*/
|
|
1863
|
+
skillsTrustedProjectDirs: effectiveSkillsTrustedProjectDirs,
|
|
1751
1864
|
egressResolver,
|
|
1752
1865
|
egressLogConfig,
|
|
1753
1866
|
securityAudit,
|
|
@@ -1802,11 +1915,15 @@ executionConfig) {
|
|
|
1802
1915
|
// Политика ограничения контекстного окна (live, админ-API).
|
|
1803
1916
|
contextWindowSettings,
|
|
1804
1917
|
subagentMaxInputTokensSettings,
|
|
1918
|
+
// Лимит тяжёлых операций с сессиями (live, админ-API `/settings/limits`).
|
|
1919
|
+
sessionOpsPerMinuteSettings,
|
|
1805
1920
|
// Дефолты оптимизации контекста новых сессий (live, админ-API).
|
|
1806
1921
|
contextDefaultsSettings,
|
|
1807
1922
|
// Instance-wide лимиты заметок сессии (live, админ-API).
|
|
1808
1923
|
stickyNotesLimitsSettings,
|
|
1809
|
-
//
|
|
1924
|
+
// PROP-124: режим инстанса для SSH-ключей (live, админ-API).
|
|
1925
|
+
sshModeSettings,
|
|
1926
|
+
// ADR-114: сервис worktree — HTTP-контур проектов и привязка сессии.
|
|
1810
1927
|
worktreeService,
|
|
1811
1928
|
webhookStore,
|
|
1812
1929
|
webhookDeliveryStore,
|
package/dist/app/mount-routes.js
CHANGED
|
@@ -6,11 +6,18 @@
|
|
|
6
6
|
import { isAbsolute, join, normalize, resolve } from 'node:path';
|
|
7
7
|
import { randomUUID } from 'node:crypto';
|
|
8
8
|
import { DEFAULT_LLM_GATEWAY_RATE_LIMIT, ProjectRole, SYNTH_VERSION, resolveSecretKey, resolveStorageBackend, resolvePostgresConfig, resolvePostgresPassword } from '@itphx/synth-shared';
|
|
9
|
-
import { DEFAULT_AGENT_ID, RateLimiter, getPublicOpenApiDocument, createFsRoutes, createGitRoutes, createSshKeyRoutes, createAgentSshKeyRoutes, createEventRoutes, createSchedulerRoutes, createServiceKeyRoutes, createWebhookRoutes, mergeLlmGatewayConfig, mergeSecurityConfig, mergePluginsConfig, createSkillRoutes, createCommandRoutes, createSkillBundleRoutes, createSessionSkillScopeRoutes, createProjectSkillScopeRoutes, createSkillSettingsRoutes, createIdentityRoutes, createMaintenanceRoutes, createAnalyticsRoutes, AnalyticsService, createProjectPortableRoutes, createStorageContextAsync, ProjectInstructionsResolver, createInstructionsInfoResolver, createSettingsRoutes, createDictionaryRoutes, createAuditRoutes
|
|
9
|
+
import { DEFAULT_AGENT_ID, RateLimiter, resolveAgentRoleAlias, 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, currentEgressLog,
|
|
10
|
+
// ADR-036/ADR-095: логи, аудит LLM Gateway, regex-паттерны, файлы контекста
|
|
11
|
+
// и группы логирования — core-фабрики (backend передаёт RBAC/i18n через opts).
|
|
12
|
+
createLogsRoutes, resolveLogDir, createGatewayPatternsRoutes, createContextFileRoutes, createDebugRoutes, createContextRoutes as createCoreContextRoutes, createMetricsSettingsRoutes,
|
|
13
|
+
// ADR-133: обновления — проверка по каналам, SSE-установка и тумблер автопроверки.
|
|
14
|
+
createUpdateRoutes, createUpdatesSettingsRoutes,
|
|
10
15
|
// ADR-115: админ-раздел «Вложения» — runtime-настройки мультимодального ввода.
|
|
11
|
-
createAttachmentsSettingsRoutes, createModalityModelLookup, createContextWindowSettingsRoutes, createAgentsLimitsSettingsRoutes,
|
|
16
|
+
createAttachmentsSettingsRoutes, createModalityModelLookup, createContextWindowSettingsRoutes, createAgentsLimitsSettingsRoutes,
|
|
17
|
+
// Лимит тяжёлых операций с сессиями (`limits.sessionOpsPerMinute`).
|
|
18
|
+
createRequestLimitsSettingsRoutes, createContextDefaultsSettingsRoutes, createStickyNotesSettingsRoutes, createSshSettingsRoutes, createStagingAttachmentRoutes, AttachmentService, createPacksRoutes, createPipelinesRoutes, createPipelineProjectRoutes, createProcessRoutes, createPluginsRoutes, createPluginSettingsRoutes, createMemoryRoutes, MEMORY_PLUGIN_NAME, MemoryProviderUnavailableError, executeToolDef,
|
|
12
19
|
// ADR-118 §8: возможности инстанса (`GET /api/v2/meta`).
|
|
13
|
-
createMetaRoutes, createOAuthRoutes, bindCredentialToConnector, syncMcpManagerFromRegistry, resolveProjectWorkspace, resolvePluginServerPolicy, } from '@itphx/synth-core';
|
|
20
|
+
createMetaRoutes, createOAuthRoutes, bindCredentialToConnector, syncMcpManagerFromRegistry, createProjectPlanRoutes, createProjectLogRoutes, resolveProjectWorkspace, resolvePluginServerPolicy, } from '@itphx/synth-core';
|
|
14
21
|
import { createProjectRoutes, createProjectAccess } from '../routes/projects.js';
|
|
15
22
|
import { createBackendProcessAccess } from '../routes/processes.js';
|
|
16
23
|
import { createSessionRoutes } from '../routes/sessions.js';
|
|
@@ -20,12 +27,7 @@ import { createProviderRoutes } from '../routes/providers.js';
|
|
|
20
27
|
import { createModelRoutes } from '../routes/models.js';
|
|
21
28
|
import { createAgentRoutes } from '../routes/agents.js';
|
|
22
29
|
import { createMcpRoutes } from '../routes/mcp.js';
|
|
23
|
-
import { createContextRoutes as createContextFileRoutes } from '../routes/context.js';
|
|
24
|
-
import { createDebugRoutes } from '../routes/debug.js';
|
|
25
30
|
import { createUserRoutes } from '../routes/users.js';
|
|
26
|
-
import { createAuditRoutes } from '../routes/audit.js';
|
|
27
|
-
import { createLogsRoutes, resolveLogDir } from '../routes/logs.js';
|
|
28
|
-
import { createGatewayPatternsRoutes } from '../routes/gateway-patterns.js';
|
|
29
31
|
import { createLlmRoutes } from '../routes/llm.js';
|
|
30
32
|
import { createRateLimiter } from '../middleware/rate-limiter.js';
|
|
31
33
|
import { scopeGuard, serviceProjectProjection } from '../auth/service-scope.js';
|
|
@@ -59,8 +61,43 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
59
61
|
// ADR-052 (этап I): публичный OpenAPI-документ (spike) за requireAuth;
|
|
60
62
|
// публичную выдачу без auth согласуем отдельно.
|
|
61
63
|
app.get('/api/v2/openapi.json', auth.requireAuth, (c) => c.json(getPublicOpenApiDocument()));
|
|
64
|
+
// RBAC-хелперы проекта (ADR-089 §5.5/§5.8): владелец/участник/LEAD/ADMIN.
|
|
65
|
+
// Объявлены до монтирования проектов — их используют и контур плана/журнала
|
|
66
|
+
// (PROP-054), и FS/git-роуты.
|
|
67
|
+
const projectAccess = createProjectAccess(auth);
|
|
62
68
|
// Projects routes
|
|
63
69
|
app.route('/api/v2/projects', createProjectRoutes(auth, projectStore, sessionManager, config.workspacesRoot, mcpManager, skillService, settingsStore, mcpRegistryStore, deps.worktreeService, eventBus));
|
|
70
|
+
// PROP-054: точечные операции плана проекта (`/projects/:id/plan*`) —
|
|
71
|
+
// core-фабрика, RBAC — те же правила проекта (чтение — право чтения,
|
|
72
|
+
// мутации — право изменения содержимого; `VIEWER` читает, но не мутирует).
|
|
73
|
+
app.route('/api/v2/projects', createProjectPlanRoutes({ requireAuth: auth.requireAuth }, projectStore, {
|
|
74
|
+
canRead: async (c, project, userId) => projectAccess.canReadProject(c, project, userId),
|
|
75
|
+
canEditContent: async (c, project, userId) => projectAccess.canEditProjectContent(c, project, userId),
|
|
76
|
+
getCurrentUserId: async (c) => (await auth.getCurrentUser(c))?.id ?? '',
|
|
77
|
+
messages: {
|
|
78
|
+
notFound: (c) => t('errors.notFound.project', undefined, c),
|
|
79
|
+
forbidden: (c) => t('auth.forbidden', undefined, c),
|
|
80
|
+
invalidBody: (c) => t('errors.validation.invalidPlanBody', undefined, c),
|
|
81
|
+
remoteUnavailable: (c) => t('errors.unavailable.remoteProject', undefined, c),
|
|
82
|
+
},
|
|
83
|
+
sessionManager,
|
|
84
|
+
eventBus,
|
|
85
|
+
}));
|
|
86
|
+
// PROP-054: журнал проекта и инварианты (`/projects/:id/log*`,
|
|
87
|
+
// `/projects/:id/invariants`). Журнал вынесен из детали проекта.
|
|
88
|
+
app.route('/api/v2/projects', createProjectLogRoutes({ requireAuth: auth.requireAuth }, projectStore, {
|
|
89
|
+
canRead: async (c, project, userId) => projectAccess.canReadProject(c, project, userId),
|
|
90
|
+
canEditContent: async (c, project, userId) => projectAccess.canEditProjectContent(c, project, userId),
|
|
91
|
+
getCurrentUserId: async (c) => (await auth.getCurrentUser(c))?.id ?? '',
|
|
92
|
+
messages: {
|
|
93
|
+
notFound: (c) => t('errors.notFound.project', undefined, c),
|
|
94
|
+
forbidden: (c) => t('auth.forbidden', undefined, c),
|
|
95
|
+
invalidBody: (c) => t('errors.validation.invalidLogBody', undefined, c),
|
|
96
|
+
remoteUnavailable: (c) => t('errors.unavailable.remoteProject', undefined, c),
|
|
97
|
+
},
|
|
98
|
+
sessionManager,
|
|
99
|
+
eventBus,
|
|
100
|
+
}));
|
|
64
101
|
// ADR-091 (этап 2): портативный экспорт/импорт проекта (скачать/загрузить архив).
|
|
65
102
|
// Managed RBAC: скачивание — право чтения проекта (owner/участник/LEAD/ADMIN),
|
|
66
103
|
// импорт в существующий проект (`mergeInto`) — право редактирования; создание
|
|
@@ -124,7 +161,7 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
124
161
|
},
|
|
125
162
|
// Этап 1 roadmap 0.13 (блок 3): сервис «вопрос пользователю» (`ask_user`).
|
|
126
163
|
deps.questionService,
|
|
127
|
-
// ADR-114: сервис worktree
|
|
164
|
+
// ADR-114: сервис worktree — привязка сессии к worktree
|
|
128
165
|
// (`PATCH /api/v2/sessions/:id { worktreeId }`).
|
|
129
166
|
deps.worktreeService,
|
|
130
167
|
// ADR-115: вложения сообщений — blob-порт, учёт ссылок; лимиты читаются
|
|
@@ -166,7 +203,10 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
166
203
|
}
|
|
167
204
|
return model ? model.enabled !== false : undefined;
|
|
168
205
|
},
|
|
169
|
-
}
|
|
206
|
+
},
|
|
207
|
+
// Лимит тяжёлых операций ресурса сессий (`limits.sessionOpsPerMinute`) —
|
|
208
|
+
// live-геттер: резолвится на каждый запрос (0 — без лимита).
|
|
209
|
+
() => deps.sessionOpsPerMinuteSettings.getValue()));
|
|
170
210
|
// Messages routes
|
|
171
211
|
app.route('/api/v2/messages', createMessageRoutes(auth, sessionManager, contextOptimizer, eventBus, projectStore,
|
|
172
212
|
// ADR-115: удаление сообщения снимает ссылки на объекты вложений.
|
|
@@ -178,7 +218,6 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
178
218
|
// FS routes (ADR-075): core-фабрика, managed поверх workspace проекта.
|
|
179
219
|
// ADR-089 (P0): доступ к проекту обязателен — иначе любой USER читал/писал бы
|
|
180
220
|
// файлы чужого проекта по id (IDOR). Чтение — canRead, мутации — canEditContent.
|
|
181
|
-
const projectAccess = createProjectAccess(auth);
|
|
182
221
|
app.route('/api/v2/fs', createFsRoutes(auth, config.workspacesRoot, undefined, {
|
|
183
222
|
requireProjectId: true,
|
|
184
223
|
getOutsideRootPolicy: () => 'deny',
|
|
@@ -237,8 +276,14 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
237
276
|
// ADR-046/ADR-089: ролевой промпт агента (`role_prompt` в теле POST)
|
|
238
277
|
// пишется портом файлов контекста — `{dataDir}/context/roles/<contextFile>`.
|
|
239
278
|
app.route('/api/v2/agents', createAgentRoutes(auth, agentStore, agentRegistry, getDefaultAgentId, contextConfig));
|
|
240
|
-
// Context routes (
|
|
241
|
-
app.route('/api/v2/context', createContextFileRoutes(auth, contextConfig
|
|
279
|
+
// Context routes (файлы контекста/промптов инстанца; админ-мутации) — core-фабрика.
|
|
280
|
+
app.route('/api/v2/context', createContextFileRoutes(auth, contextConfig, {
|
|
281
|
+
adminGuard: auth.requireAdmin,
|
|
282
|
+
messages: {
|
|
283
|
+
fileNotFound: (c) => t('errors.notFound.file', undefined, c),
|
|
284
|
+
expectedFilesArray: (c) => t('errors.validation.expectedFilesArray', undefined, c),
|
|
285
|
+
},
|
|
286
|
+
}));
|
|
242
287
|
// User admin routes
|
|
243
288
|
app.route('/api/v2/users', createUserRoutes(auth, profilesStore));
|
|
244
289
|
// Git routes (ADR-076 §T4): core-фабрика + managed RBAC. Write-эндпоинты
|
|
@@ -546,6 +591,19 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
546
591
|
readGuard: auth.requirePermission('ADMIN'),
|
|
547
592
|
writeGuard: auth.requirePermission('ADMIN'),
|
|
548
593
|
}));
|
|
594
|
+
// Лимит тяжёлых операций с сессиями (`limits.sessionOpsPerMinute`):
|
|
595
|
+
// instance-wide, `0` — без лимита; лимитеры читают резолвер на каждый запрос,
|
|
596
|
+
// поэтому runtime-настройка применяется без рестарта. Managed — ADMIN.
|
|
597
|
+
app.route('/api/v2/settings', createRequestLimitsSettingsRoutes({ requireAuth: auth.requireAuth }, {
|
|
598
|
+
settingsStore,
|
|
599
|
+
config: config.synth.limits.sessionOpsPerMinute,
|
|
600
|
+
live: deps.sessionOpsPerMinuteSettings,
|
|
601
|
+
securityAudit,
|
|
602
|
+
env: process.env,
|
|
603
|
+
}, {
|
|
604
|
+
readGuard: auth.requirePermission('ADMIN'),
|
|
605
|
+
writeGuard: auth.requirePermission('ADMIN'),
|
|
606
|
+
}));
|
|
549
607
|
// Дефолты оптимизации контекста для новых сессий (`context.defaults`):
|
|
550
608
|
// instance-wide, применяются при создании сессии. Managed RBAC — ADMIN
|
|
551
609
|
// (чтение и запись): это настройка инстанса.
|
|
@@ -570,6 +628,19 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
570
628
|
readGuard: auth.requirePermission('ADMIN'),
|
|
571
629
|
writeGuard: auth.requirePermission('ADMIN'),
|
|
572
630
|
}));
|
|
631
|
+
// PROP-124: режим инстанса для SSH-ключей (`ssh.mode`): `tools`|`agent`.
|
|
632
|
+
// Runtime-override, применяется сразу. Managed RBAC — ADMIN (чтение и
|
|
633
|
+
// запись): это настройка инстанса.
|
|
634
|
+
app.route('/api/v2/settings', createSshSettingsRoutes({ requireAuth: auth.requireAuth }, {
|
|
635
|
+
settingsStore,
|
|
636
|
+
config: config.synth.ssh?.mode,
|
|
637
|
+
live: deps.sshModeSettings,
|
|
638
|
+
securityAudit,
|
|
639
|
+
env: process.env,
|
|
640
|
+
}, {
|
|
641
|
+
readGuard: auth.requirePermission('ADMIN'),
|
|
642
|
+
writeGuard: auth.requirePermission('ADMIN'),
|
|
643
|
+
}));
|
|
573
644
|
// ADR-115: staging-загрузка без сессии — `POST /api/v2/attachments`
|
|
574
645
|
// (шлюзы принимают файл из внешнего канала, пайплайны — из шага). Managed:
|
|
575
646
|
// `requireAuth` + scope-гейт service-key `events:ingest` (у шлюзов он уже
|
|
@@ -765,6 +836,9 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
765
836
|
// MCP routes (единый реестр; legacy /servers — адаптеры над ним)
|
|
766
837
|
app.route('/api/v2/mcp', createMcpRoutes(auth, mcpManager, sessionManager, {
|
|
767
838
|
registry: mcpRegistryStore,
|
|
839
|
+
// Переподключение сервера (`POST /servers/:name/reconnect`) — снять и
|
|
840
|
+
// заново зарегистрировать MCP-инструменты в общем реестре.
|
|
841
|
+
toolRegistry,
|
|
768
842
|
// Политика резолвится на каждый запрос (live; исключения/режим — из стора).
|
|
769
843
|
getNetworkPolicy: () => egressResolver.resolveMcp(),
|
|
770
844
|
// ADR-105 (Ф3): порт слоя внешних доступов — право привязать доступ
|
|
@@ -880,6 +954,12 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
880
954
|
sessionManager, skillService, settingsStore, projectStore,
|
|
881
955
|
permissionConfig: config.synth.permission,
|
|
882
956
|
resolveProjectWorkspace: resolveSkillWorkspace,
|
|
957
|
+
// ADR-046 §6.3: capability-гейт сессии — по capabilities её агента
|
|
958
|
+
// (legacy-роль резолвится алиасом, как в рантайме оркестратора).
|
|
959
|
+
resolveAgentCapabilities: (role) => {
|
|
960
|
+
const resolved = role ? (resolveAgentRoleAlias(role) ?? role) : undefined;
|
|
961
|
+
return resolved ? agentRegistry.get(resolved)?.capabilities : undefined;
|
|
962
|
+
},
|
|
883
963
|
}, {
|
|
884
964
|
writeGuard: auth.requireAuth,
|
|
885
965
|
resolveUserId: async (c) => (await auth.getCurrentUser(c))?.id ?? '',
|
|
@@ -918,7 +998,10 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
918
998
|
|| project.ownerId === userId
|
|
919
999
|
|| project.members?.[userId] === ProjectRole.OWNER,
|
|
920
1000
|
}));
|
|
921
|
-
app.route('/api/v2/settings', createSkillSettingsRoutes(auth, {
|
|
1001
|
+
app.route('/api/v2/settings', createSkillSettingsRoutes(auth, {
|
|
1002
|
+
settingsStore,
|
|
1003
|
+
trustedProjectDirsDefaults: config.synth.skills.trustedProjectDirs ?? [],
|
|
1004
|
+
}, {
|
|
922
1005
|
writeGuard: auth.requireAdmin,
|
|
923
1006
|
onSkillsDisabledChange: (disabled) => orchestrator.setSkillsDisabled(disabled),
|
|
924
1007
|
}));
|
|
@@ -949,22 +1032,36 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
949
1032
|
unauthorized: (c) => t('auth.unauthorized', undefined, c),
|
|
950
1033
|
},
|
|
951
1034
|
}));
|
|
952
|
-
// LLM Gateway audit routes (ADR-036) — GET только ADMIN/AUDITOR, POST /revealed — все
|
|
1035
|
+
// LLM Gateway audit routes (ADR-036) — GET только ADMIN/AUDITOR, POST /revealed — все авторизованные.
|
|
1036
|
+
// Одна core-фабрика на весь префикс `/api/v2/audit`: голый аудит Gateway (`/`),
|
|
1037
|
+
// `POST /revealed`, журнал безопасности (`/security`) и журнал egress (`/egress`).
|
|
953
1038
|
app.route('/api/v2/audit', createAuditRoutes(auth, {
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
1039
|
+
securityAudit,
|
|
1040
|
+
egressRequests,
|
|
1041
|
+
gatewayAudit: {
|
|
1042
|
+
auditLogPath: gatewayAuditLogger.logPath,
|
|
1043
|
+
sessionExists: async (sessionId) => {
|
|
1044
|
+
const session = await sessionManager.getSession(sessionId);
|
|
1045
|
+
return session !== null;
|
|
1046
|
+
},
|
|
1047
|
+
logger: gatewayAuditLogger,
|
|
958
1048
|
},
|
|
959
|
-
|
|
1049
|
+
}, {
|
|
1050
|
+
readGuard: auth.requirePermission('ADMIN', 'AUDITOR'),
|
|
1051
|
+
gatewayReadGuard: auth.requirePermission('ADMIN', 'AUDITOR'),
|
|
1052
|
+
revealedGuard: auth.requireAuth,
|
|
960
1053
|
}));
|
|
961
1054
|
// Логи сервисов (core/ui/backend) + полный лог запросов/ответов LLM — чтение, только ADMIN/AUDITOR
|
|
962
1055
|
app.route('/api/v2/logs', createLogsRoutes(auth, {
|
|
963
1056
|
logDir: resolveLogDir(),
|
|
964
1057
|
payloadLogPath: gatewayPayloadLogPath,
|
|
1058
|
+
}, {
|
|
1059
|
+
readGuard: auth.requirePermission('ADMIN', 'AUDITOR'),
|
|
965
1060
|
}));
|
|
966
1061
|
// LLM Gateway patterns routes (ADR-036) — управление regex-паттернами детекции секретов, только ADMIN
|
|
967
|
-
app.route('/api/v2/gateway', createGatewayPatternsRoutes(auth, patternStore
|
|
1062
|
+
app.route('/api/v2/gateway', createGatewayPatternsRoutes(auth, patternStore, {
|
|
1063
|
+
adminGuard: auth.requireAdmin,
|
|
1064
|
+
}));
|
|
968
1065
|
// LLM Proxy (гибридный режим, Часть 5) — OpenAI-совместимый POST /api/v2/llm/chat/completions.
|
|
969
1066
|
// Локальный core гоняет LLM-запросы централизованно через LLM Gateway (ADR-036):
|
|
970
1067
|
// обфускация/блокировка секретов, rate limit, аудит, полный payload-лог.
|
|
@@ -1089,6 +1186,23 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
1089
1186
|
// События/decision наследуют тот же guard (если не заданы отдельно).
|
|
1090
1187
|
settingsWriteGuard: auth.requirePermission('ADMIN'),
|
|
1091
1188
|
}));
|
|
1189
|
+
// ADR-133: обновления (`/api/v2/updates`) — проверка по каналам и SSE-установка.
|
|
1190
|
+
// Managed RBAC: проверка и применение — только ADMIN (как обслуживание инстанса).
|
|
1191
|
+
// Admission-гейт внутри роута: в managed/Docker/K8s self-update → 409
|
|
1192
|
+
// `UPDATE_UNSUPPORTED` (обновление выполняется образом/выпуском).
|
|
1193
|
+
app.route('/api/v2/updates', createUpdateRoutes(auth, dataDir, {
|
|
1194
|
+
updates: config.synth.updates,
|
|
1195
|
+
audit: maintenanceAudit,
|
|
1196
|
+
}, {
|
|
1197
|
+
readGuard: auth.requirePermission('ADMIN'),
|
|
1198
|
+
writeGuard: auth.requirePermission('ADMIN'),
|
|
1199
|
+
}));
|
|
1200
|
+
// ADR-133: админ-раздел «Обновления» — runtime-тумблер автопроверки.
|
|
1201
|
+
// Managed RBAC: чтение и запись — только ADMIN.
|
|
1202
|
+
app.route('/api/v2/settings', createUpdatesSettingsRoutes({ requireAuth: auth.requireAuth }, { settingsStore, config: config.synth.updates, env: process.env }, {
|
|
1203
|
+
readGuard: auth.requirePermission('ADMIN'),
|
|
1204
|
+
writeGuard: auth.requirePermission('ADMIN'),
|
|
1205
|
+
}));
|
|
1092
1206
|
// ADR-094: админ-раздел «Наблюдаемость» — runtime `metrics.enabled` (рестарт),
|
|
1093
1207
|
// live-статус и bearer-токен `/metrics` (write-only, применяется сразу).
|
|
1094
1208
|
// Managed RBAC: чтение и мутации — только ADMIN.
|
|
@@ -1106,14 +1220,8 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
1106
1220
|
readGuard: auth.requirePermission('ADMIN'),
|
|
1107
1221
|
writeGuard: auth.requirePermission('ADMIN'),
|
|
1108
1222
|
}));
|
|
1109
|
-
// Журналы
|
|
1110
|
-
//
|
|
1111
|
-
app.route('/api/v2/audit', createSecurityAuditRoutes(auth, {
|
|
1112
|
-
securityAudit,
|
|
1113
|
-
egressRequests,
|
|
1114
|
-
}, {
|
|
1115
|
-
readGuard: auth.requirePermission('ADMIN', 'AUDITOR'),
|
|
1116
|
-
}));
|
|
1223
|
+
// Журналы безопасности (аудит политик + egress) и голый аудит LLM Gateway
|
|
1224
|
+
// смонтированы **одной** core-фабрикой выше (префикс `/api/v2/audit`).
|
|
1117
1225
|
// ADR-102 (волна 1): отчёты аналитики — только чтение, данных без локализации.
|
|
1118
1226
|
// Managed RBAC (§7): ADMIN/LEAD — сквозной обзор; AUDITOR — чтение всех отчётов;
|
|
1119
1227
|
// обычный USER — принудительный фильтр оси `user` по себе (+ 403 на `decision`/`summary`).
|
|
@@ -1143,7 +1251,7 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
1143
1251
|
config: config.synth.instructions,
|
|
1144
1252
|
dictionaryStore: dictionaries,
|
|
1145
1253
|
dataDir,
|
|
1146
|
-
trustedProjectDirs:
|
|
1254
|
+
trustedProjectDirs: deps.skillsTrustedProjectDirs,
|
|
1147
1255
|
// ADR-069 R3: авто-trust workspace внутри workspacesRoot (managed-каталоги).
|
|
1148
1256
|
workspacesRoot: config.workspacesRoot,
|
|
1149
1257
|
// ADR-077: `git rev-parse` — через порт исполнения (тот же, что у тулов).
|
|
@@ -1169,9 +1277,24 @@ export function mountBackendRoutes(app, auth, ctx) {
|
|
|
1169
1277
|
// ADR-118 §8: возможности инстанса (`GET /api/v2/meta`) — **без
|
|
1170
1278
|
// аутентификации** (как `GET /health`): публичная информация о протоколе,
|
|
1171
1279
|
// по ней клиент сверяет модель сообщений (fail-closed гейт транспорта).
|
|
1172
|
-
app.route('/api/v2', createMetaRoutes({
|
|
1280
|
+
app.route('/api/v2', createMetaRoutes({
|
|
1281
|
+
getAttachments: () => deps.attachmentsSettings.getConfig(),
|
|
1282
|
+
// PROP-125: сервер гибрида умеет удалённый MCP (`/api/v2/mcp/remote/*`
|
|
1283
|
+
// и relay) — клиент читает признак из `/api/v2/meta`.
|
|
1284
|
+
// `users: true` — маршрут `/api/v2/users*` (управление пользователями)
|
|
1285
|
+
// смонтирован в backend (`src/routes/users.ts`), поэтому контур есть
|
|
1286
|
+
// всегда; в core standalone его нет, а в core в гибриде он есть лишь
|
|
1287
|
+
// пока подключён удалённый backend (там — прокси).
|
|
1288
|
+
getFeatures: () => ({ remoteMcp: true, users: true }),
|
|
1289
|
+
}));
|
|
1173
1290
|
// Глобальный SSE-хаб для всех сессий пользователя (ADR-052: `events:watch`).
|
|
1174
1291
|
registerEventsSse(app, { auth, eventHub, scopeGuard });
|
|
1175
1292
|
// Admin routes (кроме graceful shutdown — он живёт в main.ts, т.к. требует server)
|
|
1176
|
-
app.route('/api/v2/admin/debug', createDebugRoutes(auth
|
|
1293
|
+
app.route('/api/v2/admin/debug', createDebugRoutes(auth, {
|
|
1294
|
+
adminGuard: auth.requireAdmin,
|
|
1295
|
+
messages: {
|
|
1296
|
+
groupsRequired: (c) => t('errors.validation.groupsRequired', undefined, c),
|
|
1297
|
+
generic: (c) => t('errors.generic', undefined, c),
|
|
1298
|
+
},
|
|
1299
|
+
}));
|
|
1177
1300
|
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// F6 (аудит §6.1): allowlist публичных эндпоинтов `/api/v2/*`.
|
|
2
|
+
//
|
|
3
|
+
// Реализация перенесена в core (`packages/core/src/server/app/public-routes.ts`):
|
|
4
|
+
// общая логика HTTP живёт в core (ADR-017/ADR-018), а allowlist должен быть
|
|
5
|
+
// **один** для обеих сборок (standalone и managed) — иначе публичность
|
|
6
|
+
// `/api/v2/meta`/`/api/v2/health` разъехалась бы между ними.
|
|
7
|
+
//
|
|
8
|
+
// Здесь оставлен тонкий реэкспорт, чтобы существующие импорты
|
|
9
|
+
// (`./app/public-routes.js` в `src/app.ts` и `src/app/route-access-census.test.ts`)
|
|
10
|
+
// не менялись. См. `@itphx/synth-core`.
|
|
11
|
+
export { PUBLIC_API_V2_PATHS, isPublicApiV2Path } from '@itphx/synth-core';
|