mirror of
https://github.com/Studio-Saelix/sencho.git
synced 2026-08-22 16:16:41 +00:00
f5178889eb
* feat(recovery): capture complete authored Compose project for atomic rollback Replace the root-compose-only backup slot with staged recovery generations that record the managed inventory, exact Compose invocation, and prior image identity, and wire the same engine through deploy, update, manual rollback, and Git apply. * fix(recovery): satisfy CodeQL path barriers and update-guard mock Inline resolve+startsWith checks at generation/inventory fs sinks and stub getCurrentStackUpdateRecovery in UpdateGuardService tests. * fix(recovery): drop unused FileSystemService import in generation store test * fix(recovery): harden authored-project rollback for upgrade and restore safety Preserve legacy UUID backup rows, restore Git deploy state with files, make multi-file restore recoverable, evaluate policy on the restored target, and fail closed when Git capture cannot cover an apply. * fix(recovery): unblock Git apply unit tests and CodeQL pre-restore TOCTOU Mock recovery capture in git-source-service tests after fail-closed apply capture, and re-resolve live paths immediately before pre-restore snapshot reads. * fix(recovery): fall back to authored inventory when Git manifesto is missing First Git apply captures before promote, so a missing managed-project manifesto must not block rollback capture when the live stack already has authored files. * fix(recovery): make authored-project rollback atomic across Git state Restore the managed-project manifesto with files, keep nullable Git identity on first-apply captures, persist Git side-state in restore intents for startup reconcile, compensate legacy materialize failures, and refuse directory collisions before mutation. * fix(recovery): satisfy CodeQL path and TOCTOU barriers on manifesto restore Add inline resolve barriers for manifesto read/clear sinks and remove the access-then-read race when restoring a generation manifesto snapshot. * fix(recovery): close third-audit rollback generation blockers Fail closed on incomplete Git inventory fallbacks, execute captured Compose invocation during recovery, refuse startup and mutations while restore intents remain unresolved, propagate legacy stale-delete failures, and add Docker-level exact prior-image coverage plus regression tests. * fix(recovery): mark acquired before handoff in prior-image Docker test Match the production updateStack CAS sequence so the exact prior-image integration test does not fail handoff from the captured phase. * fix(recovery): close fourth-audit rollback safety blockers Evaluate policy against held images, use index-based pre-restore snapshots, hold the shared stack lock across Git apply, replay Mesh and empty captured invocations exactly, restore POSIX modes with fail-closed sensitive permissions, keep case-sensitive paths, and link Git auto-deploy health gates. Add regression coverage for these cases. * test(recovery): fix mocks for health-gate link and authored compose args Add linkGateOrRetain to the Git apply recovery mock, and mock authoredComposeArgs so the case-collision inventory test is not masked by a missing getComposeDir stub. * fix(recovery): close fifth-audit rollback safety blockers Share git_apply locking for webhook auto-apply, fail closed on malformed recovery service records, refuse mixed-image capture, and require exact probe counts with hold-tag eligibility checks. * fix(recovery): close sixth-audit rollback safety blockers Preserve the legacy backup slot during generation capture, encrypt sensitive pre-restore snapshots, revert files on a failed health probe without committing Git, fail closed when an absent-file revert would delete a directory, skip Compose one-offs, route manual and scheduled backup through the current generation, and persist runtime image platform identity. * fix(recovery): close seventh-audit rollback safety blockers Fleet snapshot restore and restore-all now capture a recovery generation under the stack lock before any authored file write, including on remote nodes. * fix(recovery): keep pre-deploy generations during health-gate observe Link deploy recovery generations to the observing gate so backup cannot replace them mid-observe. Distinguish missing hold tags from probe failures, refuse generation release when services metadata is corrupt, classify mixed-replica and coverage refusals, and toast the backend rollback message. * fix(recovery): wrap webhook deploy case for eslint const bindings in an unbraced switch case trip no-case-declarations. Match the pull case block.
198 lines
8.9 KiB
TypeScript
198 lines
8.9 KiB
TypeScript
import express, { Request, Response } from 'express';
|
|
import './types/express';
|
|
import { authGate, auditLog } from './middleware/authGate';
|
|
import { enforceApiTokenScope } from './middleware/apiTokenScope';
|
|
import { hubOnlyGuard } from './middleware/hubOnlyGuard';
|
|
import { errorHandler } from './middleware/errorHandler';
|
|
import { createApp } from './app';
|
|
import { createRemoteProxyMiddleware } from './proxy/remoteNodeProxy';
|
|
import { createServer } from './server';
|
|
import { attachUpgrade } from './websocket/upgradeHandler';
|
|
import { startServer } from './bootstrap/startup';
|
|
import { installShutdownHandlers } from './bootstrap/shutdown';
|
|
import { metaRouter } from './routes/meta';
|
|
import { blueprintsRouter } from './routes/blueprints';
|
|
import { nodeLabelsRouter } from './routes/nodeLabels';
|
|
import { authRouter } from './routes/auth';
|
|
import { mfaRouter } from './routes/mfa';
|
|
import { ssoRouter } from './routes/sso';
|
|
import { licenseRouter, systemUpdateRouter } from './routes/license';
|
|
import { imageChannelRouter } from './routes/imageChannel';
|
|
import { webhooksRouter } from './routes/webhooks';
|
|
import { usersRouter } from './routes/users';
|
|
import { gitSourcesRouter, stackGitSourceRouter } from './routes/gitSources';
|
|
import { fleetRouter } from './routes/fleet';
|
|
import { fleetActionsRouter } from './routes/fleetActions';
|
|
import { cloudBackupRouter } from './routes/cloudBackup';
|
|
import { permissionsRouter } from './routes/permissions';
|
|
import { convertRouter } from './routes/convert';
|
|
import { alertsRouter } from './routes/alerts';
|
|
import { labelsRouter, stackLabelsRouter } from './routes/labels';
|
|
import { apiTokensRouter } from './routes/apiTokens';
|
|
import { auditLogRouter } from './routes/auditLog';
|
|
import { settingsRouter } from './routes/settings';
|
|
import { scheduledTasksRouter } from './routes/scheduledTasks';
|
|
import { meshRouter } from './routes/mesh';
|
|
import { agentsRouter } from './routes/agents';
|
|
import { metricsRouter } from './routes/metrics';
|
|
import { imageUpdatesRouter, autoUpdateRouter } from './routes/imageUpdates';
|
|
import { autoHealRouter } from './routes/autoHeal';
|
|
import { notificationsRouter, notificationRoutesRouter, notificationSuppressionRouter } from './routes/notifications';
|
|
import { consoleRouter } from './routes/console';
|
|
import { ssoConfigRouter } from './routes/ssoConfig';
|
|
import { authModeRouter } from './routes/authMode';
|
|
import { registriesRouter } from './routes/registries';
|
|
import { systemMaintenanceRouter } from './routes/systemMaintenance';
|
|
import { volumesRouter } from './routes/volumes';
|
|
import { templatesRouter } from './routes/templates';
|
|
import { securityRouter } from './routes/security';
|
|
import { dashboardRouter } from './routes/dashboard';
|
|
import { containersRouter, portsRouter } from './routes/containers';
|
|
import { nodesRouter } from './routes/nodes';
|
|
import { stacksRouter } from './routes/stacks';
|
|
import { stackActivityRouter } from './routes/stackActivity';
|
|
import { stackMetricsRouter } from './routes/stackMetrics';
|
|
import { fileExplorerMetricsRouter } from './routes/fileExplorerMetrics';
|
|
import { stackActivityMetricsRouter } from './routes/stackActivityMetrics';
|
|
import { secretsRouter } from './routes/secrets';
|
|
import { diagnosticsRouter } from './routes/diagnostics';
|
|
import { dependencyMapRouter } from './routes/dependencyMap';
|
|
import { networkingRouter } from './routes/networking';
|
|
|
|
// Suppress [DEP0060] DeprecationWarning emitted by http-proxy@1.18.1 which calls
|
|
// util._extend internally. The warning fires at runtime when createProxyServer() is
|
|
// first invoked (NOT at import time), so intercepting process.emitWarning here -
|
|
// before the proxy instances are created below - fully prevents it.
|
|
// http-proxy has no compatible update; this suppression is intentional and safe.
|
|
const _origEmitWarning = process.emitWarning.bind(process);
|
|
(process as any).emitWarning = (warning: any, ...args: any[]) => {
|
|
const code = typeof args[0] === 'object' ? args[0]?.code : args[1];
|
|
if (code === 'DEP0060') return;
|
|
_origEmitWarning(warning, ...args);
|
|
};
|
|
|
|
const app = createApp();
|
|
|
|
// Public /api/health and /api/meta (no auth). Mounted before authGate.
|
|
app.use('/api', metaRouter);
|
|
|
|
// Auth / MFA / SSO routers. Mounted before authGate because some paths are
|
|
// public (login, setup, SSO callbacks); handlers that need auth use
|
|
// authMiddleware directly.
|
|
app.use('/api/auth', authRouter);
|
|
app.use('/api/auth', mfaRouter);
|
|
app.use('/api/auth/sso', ssoRouter);
|
|
|
|
// Auth gate on all /api/* routes (exempts /auth/* and webhook triggers).
|
|
app.use('/api', authGate);
|
|
|
|
// Audit-log every mutating /api/* action (POST/PUT/DELETE/PATCH).
|
|
app.use('/api', auditLog);
|
|
|
|
app.use('/api', enforceApiTokenScope);
|
|
|
|
// Hub-only guard: reject requests whose nodeId resolves to a remote node
|
|
// when the path is hub-only (e.g. /api/scheduled-tasks, /api/audit-log,
|
|
// /api/notification-routes). Without this, the proxy would forward the
|
|
// request and process it on the remote as a local call, crossing a
|
|
// node-authority boundary that the UI hides. See helpers/proxyExemptPaths.ts
|
|
// for the prefix list and middleware/hubOnlyGuard.ts for the rationale.
|
|
app.use('/api', hubOnlyGuard);
|
|
|
|
// Remote Node HTTP Proxy (see proxy/remoteNodeProxy.ts). Mounted BEFORE the
|
|
// per-group routers so a request targeting a remote node short-circuits into
|
|
// the proxy instead of hitting a local handler that would read local state.
|
|
// Gateway-level paths (auth, nodes, license, fleet, webhooks, meta) are listed
|
|
// in helpers/proxyExemptPaths.ts and bypass the proxy back to the local
|
|
// handlers below.
|
|
app.use('/api/', createRemoteProxyMiddleware());
|
|
|
|
app.use('/api/license', licenseRouter);
|
|
app.use('/api/license/image-channel', imageChannelRouter);
|
|
app.use('/api/system', systemUpdateRouter);
|
|
app.use('/api/permissions', permissionsRouter);
|
|
app.use('/api/convert', convertRouter);
|
|
app.use('/api/alerts', alertsRouter);
|
|
app.use('/api/labels', labelsRouter);
|
|
app.use('/api/stacks', stackLabelsRouter);
|
|
app.use('/api/secrets', secretsRouter);
|
|
app.use('/api/api-tokens', apiTokensRouter);
|
|
app.use('/api/audit-log', auditLogRouter);
|
|
app.use('/api/fleet', fleetRouter);
|
|
app.use('/api/fleet-actions', fleetActionsRouter);
|
|
app.use('/api/cloud-backup', cloudBackupRouter);
|
|
app.use('/api/webhooks', webhooksRouter);
|
|
app.use('/api/users', usersRouter);
|
|
app.use('/api/git-sources', gitSourcesRouter);
|
|
app.use('/api/stacks', stackGitSourceRouter);
|
|
app.use('/api/settings', settingsRouter);
|
|
app.use('/api/scheduled-tasks', scheduledTasksRouter);
|
|
app.use('/api/mesh', meshRouter);
|
|
app.use('/api/blueprints', blueprintsRouter);
|
|
app.use('/api/node-labels', nodeLabelsRouter);
|
|
app.use('/api/agents', agentsRouter);
|
|
app.use('/api', metricsRouter);
|
|
app.use('/api/image-updates', imageUpdatesRouter);
|
|
app.use('/api/auto-update', autoUpdateRouter);
|
|
app.use('/api/auto-heal', autoHealRouter);
|
|
app.use('/api/notifications', notificationsRouter);
|
|
app.use('/api/notification-routes', notificationRoutesRouter);
|
|
app.use('/api/notification-suppression-rules', notificationSuppressionRouter);
|
|
app.use('/api/system', consoleRouter);
|
|
app.use('/api/sso/config', ssoConfigRouter);
|
|
app.use('/api/sso/auth-mode', authModeRouter);
|
|
app.use('/api/registries', registriesRouter);
|
|
app.use('/api/system', systemMaintenanceRouter);
|
|
app.use('/api/volumes', volumesRouter);
|
|
app.use('/api/templates', templatesRouter);
|
|
app.use('/api/security', securityRouter);
|
|
app.use('/api/containers', containersRouter);
|
|
app.use('/api/ports', portsRouter);
|
|
app.use('/api/dashboard', dashboardRouter);
|
|
app.use('/api/diagnostics', diagnosticsRouter);
|
|
app.use('/api/dependency-map', dependencyMapRouter);
|
|
app.use('/api/networking', networkingRouter);
|
|
app.use('/api/nodes', nodesRouter);
|
|
app.use('/api/stacks', stackActivityRouter);
|
|
app.use('/api/stacks', stacksRouter);
|
|
app.use('/api/stack-metrics', stackMetricsRouter);
|
|
app.use('/api/file-explorer-metrics', fileExplorerMetricsRouter);
|
|
app.use('/api/stack-activity-metrics', stackActivityMetricsRouter);
|
|
|
|
const { server, wss, pilotTunnelWss } = createServer(app);
|
|
attachUpgrade(server, { wss, pilotTunnelWss });
|
|
|
|
// Static / SPA fallback. Production serves the built frontend; dev returns a
|
|
// JSON 404 for unmatched /api paths to prevent fetch hangs.
|
|
if (process.env.NODE_ENV === 'production') {
|
|
app.use(express.static('public'));
|
|
app.use((req: Request, res: Response) => {
|
|
if (!req.path.startsWith('/api')) {
|
|
res.sendFile('index.html', { root: 'public' });
|
|
} else {
|
|
res.status(404).json({ error: 'API endpoint not found' });
|
|
}
|
|
});
|
|
} else {
|
|
app.use((req: Request, res: Response) => {
|
|
if (req.path.startsWith('/api')) {
|
|
res.status(404).json({ error: 'API endpoint not found' });
|
|
}
|
|
});
|
|
}
|
|
|
|
// Central error handler: must be registered after all routes and static.
|
|
app.use(errorHandler);
|
|
|
|
installShutdownHandlers(server);
|
|
|
|
if (require.main === module) {
|
|
void startServer(server).catch((err) => {
|
|
console.error('[Startup] Fatal startup failure:', (err as Error).message);
|
|
process.exit(1);
|
|
});
|
|
}
|
|
|
|
// Exports used by tests (supertest requires the http.Server instance).
|
|
export { app, server };
|