@hivemagnus/magnus-server 0.0.0-stage → 1.0.2
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/.env.example +171 -0
- package/LICENSE +202 -0
- package/README.md +169 -2
- package/agent-version.json +1 -0
- package/dist/ai/HEARTBEAT.md +56 -0
- package/dist/ai/IDENTITY.md +54 -0
- package/dist/ai/MEMORY.md +40 -0
- package/dist/ai/TOOLS.md +538 -0
- package/dist/ai/USER.md +32 -0
- package/dist/cli/args.js +62 -0
- package/dist/cli/env-catalog.js +131 -0
- package/dist/cli/preflight.js +89 -0
- package/dist/cli.js +175 -0
- package/dist/config/cors.js +16 -0
- package/dist/config/env.js +392 -0
- package/dist/config/features.js +16 -0
- package/dist/config/index.js +3 -0
- package/dist/config/listener-security.js +38 -0
- package/dist/config/version.js +31 -0
- package/dist/db/client.js +44 -0
- package/dist/db/generated/prisma/browser.js +18 -0
- package/dist/db/generated/prisma/client.js +35 -0
- package/dist/db/generated/prisma/commonInputTypes.js +11 -0
- package/dist/db/generated/prisma/enums.js +42 -0
- package/dist/db/generated/prisma/internal/class.js +50 -0
- package/dist/db/generated/prisma/internal/prismaNamespace.js +1598 -0
- package/dist/db/generated/prisma/internal/prismaNamespaceBrowser.js +1569 -0
- package/dist/db/generated/prisma/models/A2ATask.js +2 -0
- package/dist/db/generated/prisma/models/AdmissionFence.js +2 -0
- package/dist/db/generated/prisma/models/Agent.js +2 -0
- package/dist/db/generated/prisma/models/AiConversation.js +2 -0
- package/dist/db/generated/prisma/models/AiDashboard.js +2 -0
- package/dist/db/generated/prisma/models/AiMemory.js +2 -0
- package/dist/db/generated/prisma/models/AiMessage.js +2 -0
- package/dist/db/generated/prisma/models/AiScheduledOp.js +2 -0
- package/dist/db/generated/prisma/models/AlertConditionState.js +2 -0
- package/dist/db/generated/prisma/models/AlertRule.js +2 -0
- package/dist/db/generated/prisma/models/AlertViolation.js +2 -0
- package/dist/db/generated/prisma/models/AnomalyEvent.js +2 -0
- package/dist/db/generated/prisma/models/ApplicationObservation.js +2 -0
- package/dist/db/generated/prisma/models/ArdentInstallation.js +2 -0
- package/dist/db/generated/prisma/models/ArdentProfile.js +2 -0
- package/dist/db/generated/prisma/models/ArdentScopeEnrollment.js +2 -0
- package/dist/db/generated/prisma/models/CommandResourceFence.js +2 -0
- package/dist/db/generated/prisma/models/CommandResourceLease.js +2 -0
- package/dist/db/generated/prisma/models/CommandResult.js +2 -0
- package/dist/db/generated/prisma/models/CronJob.js +2 -0
- package/dist/db/generated/prisma/models/CronJobExecution.js +2 -0
- package/dist/db/generated/prisma/models/DeployJob.js +2 -0
- package/dist/db/generated/prisma/models/DriftScan.js +2 -0
- package/dist/db/generated/prisma/models/EngineeringMetricSample.js +2 -0
- package/dist/db/generated/prisma/models/EngineeringRecoveryExercise.js +2 -0
- package/dist/db/generated/prisma/models/ExecutionRun.js +2 -0
- package/dist/db/generated/prisma/models/FilePatchTask.js +2 -0
- package/dist/db/generated/prisma/models/GpuSnapshot.js +2 -0
- package/dist/db/generated/prisma/models/HealthSnapshot.js +2 -0
- package/dist/db/generated/prisma/models/HermesCoreRollout.js +2 -0
- package/dist/db/generated/prisma/models/HermesCoreRolloutHost.js +2 -0
- package/dist/db/generated/prisma/models/HermesCredentialPool.js +2 -0
- package/dist/db/generated/prisma/models/HermesCredentialPoolAttachment.js +2 -0
- package/dist/db/generated/prisma/models/HermesCronJob.js +2 -0
- package/dist/db/generated/prisma/models/HermesHook.js +2 -0
- package/dist/db/generated/prisma/models/HermesInstallation.js +2 -0
- package/dist/db/generated/prisma/models/HermesMcpServer.js +2 -0
- package/dist/db/generated/prisma/models/HermesMcpServerAttachment.js +2 -0
- package/dist/db/generated/prisma/models/HermesMessagingBinding.js +2 -0
- package/dist/db/generated/prisma/models/HermesOperationJob.js +2 -0
- package/dist/db/generated/prisma/models/HermesPluginInstall.js +2 -0
- package/dist/db/generated/prisma/models/HermesProfile.js +2 -0
- package/dist/db/generated/prisma/models/HermesProviderConfig.js +2 -0
- package/dist/db/generated/prisma/models/HermesRegistryClient.js +2 -0
- package/dist/db/generated/prisma/models/HermesRegistryInventory.js +2 -0
- package/dist/db/generated/prisma/models/HermesRegistryReceipt.js +2 -0
- package/dist/db/generated/prisma/models/HermesRegistryRevision.js +2 -0
- package/dist/db/generated/prisma/models/HermesRegistryTarget.js +2 -0
- package/dist/db/generated/prisma/models/HermesRole.js +2 -0
- package/dist/db/generated/prisma/models/HermesRoleApplication.js +2 -0
- package/dist/db/generated/prisma/models/HermesSkillAssignment.js +2 -0
- package/dist/db/generated/prisma/models/HermesToolsetPolicy.js +2 -0
- package/dist/db/generated/prisma/models/IncidentLesson.js +2 -0
- package/dist/db/generated/prisma/models/LibraryCategory.js +2 -0
- package/dist/db/generated/prisma/models/LibraryFile.js +2 -0
- package/dist/db/generated/prisma/models/LogEntry.js +2 -0
- package/dist/db/generated/prisma/models/MagnusReleaseCanary.js +2 -0
- package/dist/db/generated/prisma/models/MaintenanceWindow.js +2 -0
- package/dist/db/generated/prisma/models/ManagedCronDefinition.js +2 -0
- package/dist/db/generated/prisma/models/ManagedCronOccurrence.js +2 -0
- package/dist/db/generated/prisma/models/Node.js +2 -0
- package/dist/db/generated/prisma/models/Notification.js +2 -0
- package/dist/db/generated/prisma/models/NotificationPreference.js +2 -0
- package/dist/db/generated/prisma/models/RemediationExecution.js +2 -0
- package/dist/db/generated/prisma/models/RemediationRule.js +2 -0
- package/dist/db/generated/prisma/models/RemoteCommand.js +2 -0
- package/dist/db/generated/prisma/models/ResourceDrainParticipant.js +2 -0
- package/dist/db/generated/prisma/models/ResourceEnrollment.js +2 -0
- package/dist/db/generated/prisma/models/ResourceParticipantWork.js +2 -0
- package/dist/db/generated/prisma/models/Role.js +2 -0
- package/dist/db/generated/prisma/models/RoleApplication.js +2 -0
- package/dist/db/generated/prisma/models/RolloutTarget.js +2 -0
- package/dist/db/generated/prisma/models/SecurityExportOutbox.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionAction.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionActionApproval.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionCase.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionCaseActivity.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionCaseEntity.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionCaseEvent.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionCaseRelationship.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionCollector.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionCommandOutbox.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionDeletionReceipt.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionDelivery.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionEntity.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionEntityAlias.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionEvent.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionEventEntity.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionEvidence.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionInvestigation.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionNonce.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionReceiptChainHead.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionRuleVersion.js +2 -0
- package/dist/db/generated/prisma/models/SecurityFusionSourceState.js +2 -0
- package/dist/db/generated/prisma/models/SecurityServiceState.js +2 -0
- package/dist/db/generated/prisma/models/SharedResourceFence.js +2 -0
- package/dist/db/generated/prisma/models/SharedResourceLease.js +2 -0
- package/dist/db/generated/prisma/models/SharedResourceLeaseResource.js +2 -0
- package/dist/db/generated/prisma/models/SkillInstallation.js +2 -0
- package/dist/db/generated/prisma/models/SkillRegistryEntry.js +2 -0
- package/dist/db/generated/prisma/models/SkillTag.js +2 -0
- package/dist/db/generated/prisma/models/SkillVersion.js +2 -0
- package/dist/db/generated/prisma/models/TeamApprovalDecision.js +2 -0
- package/dist/db/generated/prisma/models/User.js +2 -0
- package/dist/db/generated/prisma/models/WebhookDelivery.js +2 -0
- package/dist/db/generated/prisma/models/WebhookEndpoint.js +2 -0
- package/dist/db/generated/prisma/models.js +2 -0
- package/dist/db/index.js +3 -0
- package/dist/db/read-retry.js +35 -0
- package/dist/db/seed.js +348 -0
- package/dist/index.js +162 -0
- package/dist/middleware/auth.js +361 -0
- package/dist/middleware/body-limit.js +14 -0
- package/dist/middleware/correlation-id.js +13 -0
- package/dist/middleware/error-handler.js +28 -0
- package/dist/middleware/iam-token.js +21 -0
- package/dist/middleware/rate-limit.js +78 -0
- package/dist/middleware/request-logger.js +85 -0
- package/dist/middleware/security-headers.js +23 -0
- package/dist/middleware/tracing.js +120 -0
- package/dist/middleware/user-status.js +33 -0
- package/dist/openapi/spec.js +2656 -0
- package/dist/queue/redis.js +20 -0
- package/dist/queue/requeue.js +27 -0
- package/dist/queue/workers.js +342 -0
- package/dist/routes/ai-schedule.js +73 -0
- package/dist/routes/alerts.js +79 -0
- package/dist/routes/anomalies.js +101 -0
- package/dist/routes/ardent.js +82 -0
- package/dist/routes/assistant.js +417 -0
- package/dist/routes/audit.js +138 -0
- package/dist/routes/codex.js +65 -0
- package/dist/routes/commands.js +226 -0
- package/dist/routes/credentials.js +58 -0
- package/dist/routes/cron.js +292 -0
- package/dist/routes/dependencies.js +49 -0
- package/dist/routes/deploy.js +18 -0
- package/dist/routes/discovery.js +168 -0
- package/dist/routes/docs.js +24 -0
- package/dist/routes/drift.js +126 -0
- package/dist/routes/events-stream.js +87 -0
- package/dist/routes/files.js +214 -0
- package/dist/routes/fleet-checks.js +21 -0
- package/dist/routes/health.js +133 -0
- package/dist/routes/heartbeat.js +545 -0
- package/dist/routes/hermes-registry.js +278 -0
- package/dist/routes/hermes.js +61 -0
- package/dist/routes/library.js +402 -0
- package/dist/routes/logs.js +172 -0
- package/dist/routes/managed-cron.js +23 -0
- package/dist/routes/mcp.js +39 -0
- package/dist/routes/metrics.js +187 -0
- package/dist/routes/nodes.js +951 -0
- package/dist/routes/notifications.js +130 -0
- package/dist/routes/ops.js +258 -0
- package/dist/routes/orchestra.js +430 -0
- package/dist/routes/predictions.js +23 -0
- package/dist/routes/profiling.js +68 -0
- package/dist/routes/quick-command.js +72 -0
- package/dist/routes/remediation.js +111 -0
- package/dist/routes/resource-leases.js +297 -0
- package/dist/routes/roles.js +370 -0
- package/dist/routes/rollout.js +124 -0
- package/dist/routes/scan.js +116 -0
- package/dist/routes/security-backup.js +58 -0
- package/dist/routes/security-fusion.js +605 -0
- package/dist/routes/security-integration.js +71 -0
- package/dist/routes/self-update.js +129 -0
- package/dist/routes/shared-resource-leases.js +78 -0
- package/dist/routes/skills.js +485 -0
- package/dist/routes/stats.js +96 -0
- package/dist/routes/team-approvals.js +23 -0
- package/dist/routes/terminal-ticket.js +15 -0
- package/dist/routes/terminal.js +17 -0
- package/dist/routes/topology.js +37 -0
- package/dist/routes/users.js +219 -0
- package/dist/routes/webhooks.js +137 -0
- package/dist/schemas/command-reconciliation.js +14 -0
- package/dist/schemas/commands.js +51 -0
- package/dist/schemas/cron.js +33 -0
- package/dist/schemas/deploy.js +20 -0
- package/dist/schemas/files.js +14 -0
- package/dist/schemas/hermes.js +69 -0
- package/dist/schemas/index.js +11 -0
- package/dist/schemas/library.js +48 -0
- package/dist/schemas/logs.js +35 -0
- package/dist/schemas/managed-cron.js +127 -0
- package/dist/schemas/node-responses.js +87 -0
- package/dist/schemas/node-session-receipt.js +84 -0
- package/dist/schemas/nodes.js +36 -0
- package/dist/schemas/orchestra.js +118 -0
- package/dist/schemas/resource-participant-reconciliation.js +99 -0
- package/dist/schemas/roles.js +54 -0
- package/dist/schemas/shared-resource-lease.js +132 -0
- package/dist/schemas/skills.js +44 -0
- package/dist/schemas/users.js +28 -0
- package/dist/scripts/run-disposable-recovery-exercise.js +39 -0
- package/dist/sdk/index.js +2 -0
- package/dist/sdk/node-api-client.js +474 -0
- package/dist/security/approval-assertion.js +66 -0
- package/dist/security/command-completion-registry.js +35 -0
- package/dist/security/command-request.js +12 -0
- package/dist/security/command-result-signature.js +34 -0
- package/dist/security/managed-http.js +45 -0
- package/dist/security/native-completion-registry.js +44 -0
- package/dist/server.js +178 -0
- package/dist/services/admission-fence.js +71 -0
- package/dist/services/ai-assistant-service.js +2523 -0
- package/dist/services/ai-correlation-service.js +225 -0
- package/dist/services/ai-export-service.js +141 -0
- package/dist/services/ai-insights-service.js +219 -0
- package/dist/services/ai-schedule-service.js +145 -0
- package/dist/services/ai-scratchpad-service.js +222 -0
- package/dist/services/ai-tools.js +1343 -0
- package/dist/services/alert-service.js +313 -0
- package/dist/services/anomaly-detector.js +419 -0
- package/dist/services/api-local-work.js +79 -0
- package/dist/services/application-probes.js +309 -0
- package/dist/services/ardent-scope-enrollment.js +123 -0
- package/dist/services/ardent-service.js +86 -0
- package/dist/services/audit-service.js +308 -0
- package/dist/services/codex-service.js +209 -0
- package/dist/services/command-lifecycle.js +60 -0
- package/dist/services/command-resource-leases.js +305 -0
- package/dist/services/control-host-node.js +242 -0
- package/dist/services/credential-rotation-service.js +294 -0
- package/dist/services/dependency-service.js +145 -0
- package/dist/services/disposable-recovery-runner.js +595 -0
- package/dist/services/docker-group-health.js +121 -0
- package/dist/services/engineering-assurance.js +492 -0
- package/dist/services/engineering-evidence-ledger.js +94 -0
- package/dist/services/engineering-metric-evidence.js +26 -0
- package/dist/services/event-bus.js +227 -0
- package/dist/services/fleet-check-log.js +102 -0
- package/dist/services/forecast-service.js +154 -0
- package/dist/services/health-retention.js +175 -0
- package/dist/services/heartbeat-stream.js +63 -0
- package/dist/services/hermes-catalog-import.js +62 -0
- package/dist/services/hermes-cli-parser.js +671 -0
- package/dist/services/hermes-core-rollout.js +90 -0
- package/dist/services/hermes-dashboard-endpoint.js +13 -0
- package/dist/services/hermes-plugin-source.js +149 -0
- package/dist/services/hermes-registry-service.js +258 -0
- package/dist/services/hermes-service.js +566 -0
- package/dist/services/hivemem-client.js +85 -0
- package/dist/services/host-local-writer.js +82 -0
- package/dist/services/incident-evidence.js +110 -0
- package/dist/services/incident-lessons.js +186 -0
- package/dist/services/llm-providers/anthropic.js +143 -0
- package/dist/services/llm-providers/index.js +7 -0
- package/dist/services/llm-providers/llama-cpp.js +237 -0
- package/dist/services/llm-providers/ollama.js +292 -0
- package/dist/services/llm-providers/openai-compatible.js +200 -0
- package/dist/services/llm-providers/provider-error.js +36 -0
- package/dist/services/llm-providers/registry.js +45 -0
- package/dist/services/llm-providers/types.js +2 -0
- package/dist/services/log-emitter.js +19 -0
- package/dist/services/log-retention.js +66 -0
- package/dist/services/maintenance-service.js +29 -0
- package/dist/services/managed-cron.js +493 -0
- package/dist/services/managed-ssh-admission.js +68 -0
- package/dist/services/monitor-pulse.js +10 -0
- package/dist/services/node-issue-monitor.js +71 -0
- package/dist/services/node-service.js +35 -0
- package/dist/services/notification-retention.js +51 -0
- package/dist/services/notification-service.js +94 -0
- package/dist/services/operational-observations.js +112 -0
- package/dist/services/operations-config.js +67 -0
- package/dist/services/ops-service.js +491 -0
- package/dist/services/orchestra-extras-service.js +370 -0
- package/dist/services/orchestra-resources-service.js +530 -0
- package/dist/services/os-scheduler-writer.js +73 -0
- package/dist/services/password-service.js +22 -0
- package/dist/services/prediction-service.js +284 -0
- package/dist/services/recovery-exercises.js +682 -0
- package/dist/services/remediation-service.js +325 -0
- package/dist/services/resource-enrollment.js +433 -0
- package/dist/services/resource-node-lock.js +18 -0
- package/dist/services/resource-participant-work.js +302 -0
- package/dist/services/role-service.js +388 -0
- package/dist/services/rollout-service.js +440 -0
- package/dist/services/security-export.js +185 -0
- package/dist/services/security-fusion-actions.js +22 -0
- package/dist/services/security-fusion-approvals.js +83 -0
- package/dist/services/security-fusion-evidence-integrity.js +144 -0
- package/dist/services/security-fusion-ingest.js +101 -0
- package/dist/services/security-fusion-outbox.js +185 -0
- package/dist/services/security-fusion-receipt-chain.js +134 -0
- package/dist/services/security-fusion-service.js +751 -0
- package/dist/services/security-fusion-verification.js +50 -0
- package/dist/services/self-update-service.js +200 -0
- package/dist/services/shared-resource-leases.js +413 -0
- package/dist/services/skill-publication-bundle.js +90 -0
- package/dist/services/skill-publication-settlement.js +36 -0
- package/dist/services/skill-publication-state.js +40 -0
- package/dist/services/skill-registry-service.js +327 -0
- package/dist/services/skill-service.js +148 -0
- package/dist/services/ssh-exec-service.js +139 -0
- package/dist/services/ssh-host-verification.js +27 -0
- package/dist/services/tailscale-node-key-service.js +75 -0
- package/dist/services/team-approvals.js +118 -0
- package/dist/services/topology-service.js +138 -0
- package/dist/services/transfer-authority-snapshot.js +151 -0
- package/dist/services/webhook-credential-migration.js +97 -0
- package/dist/services/webhook-security.js +242 -0
- package/dist/services/webhook-service.js +494 -0
- package/dist/types/auth.js +3 -0
- package/dist/types/index.js +3 -0
- package/dist/types/library.js +3 -0
- package/dist/types/notifications.js +3 -0
- package/dist/types/roles.js +3 -0
- package/dist/types/shared-contracts.js +3 -0
- package/dist/utils/env.js +141 -0
- package/dist/utils/heartbeat-peer.js +19 -0
- package/dist/utils/idempotency.js +45 -0
- package/dist/utils/ip.js +25 -0
- package/dist/utils/json-fields.js +94 -0
- package/dist/utils/local-tls.js +39 -0
- package/dist/utils/magnus-home.js +15 -0
- package/dist/utils/node-url.js +59 -0
- package/dist/utils/redact.js +26 -0
- package/dist/utils/safe-equal.js +13 -0
- package/dist/utils/sentinel-nodes.js +16 -0
- package/dist/utils/validate.js +41 -0
- package/package.json +119 -4
- package/prisma/migrations/20261031000000_baseline/migration.sql +2935 -0
- package/prisma/migrations/migration_lock.toml +3 -0
- package/prisma/schema.prisma +2185 -0
- package/prisma.config.ts +14 -0
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
import { Hono } from 'hono';
|
|
2
|
+
import { getDb } from '../db/index.js';
|
|
3
|
+
import { authMiddleware, getUser, requireRole } from '../middleware/auth.js';
|
|
4
|
+
import { logAuditEvent, sanitizeDetails } from '../services/audit-service.js';
|
|
5
|
+
import { HttpError } from '../middleware/error-handler.js';
|
|
6
|
+
import { getNodeBaseUrl } from '../utils/node-url.js';
|
|
7
|
+
import { getNodeManagerSecret } from '../utils/env.js';
|
|
8
|
+
import { parseBody } from '../utils/validate.js';
|
|
9
|
+
import { NodeApiClient } from '../sdk/node-api-client.js';
|
|
10
|
+
import { createCategorySchema, updateCategorySchema, createLibraryFileSchema, updateLibraryFileSchema, moveFilesSchema, deployLibrarySchema, } from '../schemas/library.js';
|
|
11
|
+
import { enforceIdempotencyFromHeader } from '../utils/idempotency.js';
|
|
12
|
+
import { parseStringArray, serializeStringArray } from '../utils/json-fields.js';
|
|
13
|
+
import { createCronSchema } from '../schemas/cron.js';
|
|
14
|
+
import { cronMutationMode, installManagedCron, upsertAndRegisterManagedCron } from '../services/managed-cron.js';
|
|
15
|
+
export const libraryRouter = new Hono();
|
|
16
|
+
libraryRouter.use('*', authMiddleware);
|
|
17
|
+
// ════════════════════════════════════════════════
|
|
18
|
+
// Categories
|
|
19
|
+
// ════════════════════════════════════════════════
|
|
20
|
+
// ── List all categories ──
|
|
21
|
+
libraryRouter.get('/categories', async (c) => {
|
|
22
|
+
const db = getDb();
|
|
23
|
+
const categories = await db.libraryCategory.findMany({
|
|
24
|
+
orderBy: { sortOrder: 'asc' },
|
|
25
|
+
include: { _count: { select: { files: true } } },
|
|
26
|
+
});
|
|
27
|
+
const data = categories.map((cat) => ({
|
|
28
|
+
...cat,
|
|
29
|
+
fileCount: cat._count.files,
|
|
30
|
+
_count: undefined,
|
|
31
|
+
}));
|
|
32
|
+
return c.json({ success: true, data });
|
|
33
|
+
});
|
|
34
|
+
// ── Create category ──
|
|
35
|
+
libraryRouter.post('/categories', requireRole('ADMIN', 'OPERATOR'), async (c) => {
|
|
36
|
+
const db = getDb();
|
|
37
|
+
const user = getUser(c);
|
|
38
|
+
const body = await parseBody(c, createCategorySchema);
|
|
39
|
+
const existing = await db.libraryCategory.findUnique({ where: { name: body.name.trim() } });
|
|
40
|
+
if (existing) {
|
|
41
|
+
throw new HttpError(409, 'CONFLICT', 'A category with this name already exists');
|
|
42
|
+
}
|
|
43
|
+
const category = await db.libraryCategory.create({
|
|
44
|
+
data: {
|
|
45
|
+
name: body.name.trim(),
|
|
46
|
+
description: body.description ?? '',
|
|
47
|
+
color: body.color ?? '#6366f1',
|
|
48
|
+
sortOrder: body.sortOrder ?? 0,
|
|
49
|
+
},
|
|
50
|
+
});
|
|
51
|
+
await logAuditEvent({
|
|
52
|
+
action: 'library.category.create',
|
|
53
|
+
actorId: user.userId,
|
|
54
|
+
targetType: 'library_category',
|
|
55
|
+
targetId: category.id,
|
|
56
|
+
details: { name: category.name },
|
|
57
|
+
});
|
|
58
|
+
return c.json({ success: true, data: category }, 201);
|
|
59
|
+
});
|
|
60
|
+
// ── Update category ──
|
|
61
|
+
libraryRouter.patch('/categories/:categoryId', requireRole('ADMIN', 'OPERATOR'), async (c) => {
|
|
62
|
+
const db = getDb();
|
|
63
|
+
const user = getUser(c);
|
|
64
|
+
const categoryId = c.req.param('categoryId');
|
|
65
|
+
const body = await parseBody(c, updateCategorySchema);
|
|
66
|
+
const existing = await db.libraryCategory.findUnique({ where: { id: categoryId } });
|
|
67
|
+
if (!existing)
|
|
68
|
+
throw new HttpError(404, 'NOT_FOUND', 'Category not found');
|
|
69
|
+
const category = await db.libraryCategory.update({
|
|
70
|
+
where: { id: categoryId },
|
|
71
|
+
data: {
|
|
72
|
+
...(body.name !== undefined && { name: body.name.trim() }),
|
|
73
|
+
...(body.description !== undefined && { description: body.description }),
|
|
74
|
+
...(body.color !== undefined && { color: body.color }),
|
|
75
|
+
...(body.sortOrder !== undefined && { sortOrder: body.sortOrder }),
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
await logAuditEvent({
|
|
79
|
+
action: 'library.category.update',
|
|
80
|
+
actorId: user.userId,
|
|
81
|
+
targetType: 'library_category',
|
|
82
|
+
targetId: categoryId,
|
|
83
|
+
details: { name: body.name, description: body.description },
|
|
84
|
+
});
|
|
85
|
+
return c.json({ success: true, data: category });
|
|
86
|
+
});
|
|
87
|
+
// ── Delete category ──
|
|
88
|
+
libraryRouter.delete('/categories/:categoryId', requireRole('ADMIN'), async (c) => {
|
|
89
|
+
const db = getDb();
|
|
90
|
+
const user = getUser(c);
|
|
91
|
+
const categoryId = c.req.param('categoryId');
|
|
92
|
+
const existing = await db.libraryCategory.findUnique({ where: { id: categoryId } });
|
|
93
|
+
if (!existing)
|
|
94
|
+
throw new HttpError(404, 'NOT_FOUND', 'Category not found');
|
|
95
|
+
// Unset categoryId on files, then delete the category
|
|
96
|
+
await db.libraryFile.updateMany({
|
|
97
|
+
where: { categoryId },
|
|
98
|
+
data: { categoryId: null },
|
|
99
|
+
});
|
|
100
|
+
await db.libraryCategory.delete({ where: { id: categoryId } });
|
|
101
|
+
await logAuditEvent({
|
|
102
|
+
action: 'library.category.delete',
|
|
103
|
+
actorId: user.userId,
|
|
104
|
+
targetType: 'library_category',
|
|
105
|
+
targetId: categoryId,
|
|
106
|
+
details: { name: existing.name },
|
|
107
|
+
});
|
|
108
|
+
return c.json({ success: true, data: { deleted: true } });
|
|
109
|
+
});
|
|
110
|
+
// ════════════════════════════════════════════════
|
|
111
|
+
// Files
|
|
112
|
+
// ════════════════════════════════════════════════
|
|
113
|
+
// ── List / search files ──
|
|
114
|
+
libraryRouter.get('/files', async (c) => {
|
|
115
|
+
const db = getDb();
|
|
116
|
+
const query = c.req.query('query');
|
|
117
|
+
const categoryId = c.req.query('categoryId');
|
|
118
|
+
const mimeType = c.req.query('mimeType');
|
|
119
|
+
const page = parseInt(c.req.query('page') ?? '1', 10);
|
|
120
|
+
const pageSize = parseInt(c.req.query('pageSize') ?? '50', 10);
|
|
121
|
+
const where = {};
|
|
122
|
+
if (query) {
|
|
123
|
+
where.name = { contains: query };
|
|
124
|
+
}
|
|
125
|
+
if (categoryId) {
|
|
126
|
+
where.categoryId = categoryId === 'uncategorized' ? null : categoryId;
|
|
127
|
+
}
|
|
128
|
+
if (mimeType) {
|
|
129
|
+
where.mimeType = { startsWith: mimeType };
|
|
130
|
+
}
|
|
131
|
+
const [files, total] = await Promise.all([
|
|
132
|
+
db.libraryFile.findMany({
|
|
133
|
+
where,
|
|
134
|
+
include: { category: { select: { id: true, name: true, color: true } } },
|
|
135
|
+
orderBy: { updatedAt: 'desc' },
|
|
136
|
+
skip: (page - 1) * pageSize,
|
|
137
|
+
take: pageSize,
|
|
138
|
+
}),
|
|
139
|
+
db.libraryFile.count({ where }),
|
|
140
|
+
]);
|
|
141
|
+
// Parse tags from JSON string
|
|
142
|
+
const data = files.map((f) => ({
|
|
143
|
+
...f,
|
|
144
|
+
tags: parseStringArray(f.tags),
|
|
145
|
+
// Strip content from list view to save bandwidth
|
|
146
|
+
content: undefined,
|
|
147
|
+
}));
|
|
148
|
+
return c.json({
|
|
149
|
+
success: true,
|
|
150
|
+
data,
|
|
151
|
+
meta: { total, page, pageSize, hasMore: page * pageSize < total },
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
// ── Get single file (with content) ──
|
|
155
|
+
libraryRouter.get('/files/:fileId', async (c) => {
|
|
156
|
+
const db = getDb();
|
|
157
|
+
const fileId = c.req.param('fileId');
|
|
158
|
+
const file = await db.libraryFile.findUnique({
|
|
159
|
+
where: { id: fileId },
|
|
160
|
+
include: { category: { select: { id: true, name: true, color: true } } },
|
|
161
|
+
});
|
|
162
|
+
if (!file)
|
|
163
|
+
throw new HttpError(404, 'NOT_FOUND', 'Library file not found');
|
|
164
|
+
return c.json({
|
|
165
|
+
success: true,
|
|
166
|
+
data: {
|
|
167
|
+
...file,
|
|
168
|
+
tags: parseStringArray(file.tags),
|
|
169
|
+
},
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
// ── Create file (upload) ──
|
|
173
|
+
libraryRouter.post('/files', requireRole('ADMIN', 'OPERATOR'), async (c) => {
|
|
174
|
+
const db = getDb();
|
|
175
|
+
const user = getUser(c);
|
|
176
|
+
const body = await parseBody(c, createLibraryFileSchema);
|
|
177
|
+
const content = body.content ?? '';
|
|
178
|
+
const file = await db.libraryFile.create({
|
|
179
|
+
data: {
|
|
180
|
+
name: body.name.trim(),
|
|
181
|
+
fileName: body.fileName.trim(),
|
|
182
|
+
mimeType: body.mimeType ?? 'text/markdown',
|
|
183
|
+
content,
|
|
184
|
+
sizeBytes: Buffer.byteLength(content, 'utf-8'),
|
|
185
|
+
categoryId: body.categoryId ?? null,
|
|
186
|
+
tags: serializeStringArray(body.tags),
|
|
187
|
+
createdBy: user.userId,
|
|
188
|
+
},
|
|
189
|
+
include: { category: { select: { id: true, name: true, color: true } } },
|
|
190
|
+
});
|
|
191
|
+
await logAuditEvent({
|
|
192
|
+
action: 'library.file.create',
|
|
193
|
+
actorId: user.userId,
|
|
194
|
+
targetType: 'library_file',
|
|
195
|
+
targetId: file.id,
|
|
196
|
+
details: { name: body.name, fileName: body.fileName, mimeType: body.mimeType },
|
|
197
|
+
});
|
|
198
|
+
return c.json({
|
|
199
|
+
success: true,
|
|
200
|
+
data: { ...file, tags: parseStringArray(file.tags) },
|
|
201
|
+
}, 201);
|
|
202
|
+
});
|
|
203
|
+
// ── Update file ──
|
|
204
|
+
libraryRouter.patch('/files/:fileId', requireRole('ADMIN', 'OPERATOR'), async (c) => {
|
|
205
|
+
const db = getDb();
|
|
206
|
+
const user = getUser(c);
|
|
207
|
+
const fileId = c.req.param('fileId');
|
|
208
|
+
const body = await parseBody(c, updateLibraryFileSchema);
|
|
209
|
+
const existing = await db.libraryFile.findUnique({ where: { id: fileId } });
|
|
210
|
+
if (!existing)
|
|
211
|
+
throw new HttpError(404, 'NOT_FOUND', 'Library file not found');
|
|
212
|
+
const updateData = {};
|
|
213
|
+
if (body.name !== undefined)
|
|
214
|
+
updateData.name = body.name.trim();
|
|
215
|
+
if (body.fileName !== undefined)
|
|
216
|
+
updateData.fileName = body.fileName.trim();
|
|
217
|
+
if (body.mimeType !== undefined)
|
|
218
|
+
updateData.mimeType = body.mimeType;
|
|
219
|
+
if (body.content !== undefined) {
|
|
220
|
+
updateData.content = body.content;
|
|
221
|
+
updateData.sizeBytes = Buffer.byteLength(body.content, 'utf-8');
|
|
222
|
+
}
|
|
223
|
+
if (body.categoryId !== undefined)
|
|
224
|
+
updateData.categoryId = body.categoryId;
|
|
225
|
+
if (body.tags !== undefined)
|
|
226
|
+
updateData.tags = serializeStringArray(body.tags);
|
|
227
|
+
const file = await db.libraryFile.update({
|
|
228
|
+
where: { id: fileId },
|
|
229
|
+
data: updateData,
|
|
230
|
+
include: { category: { select: { id: true, name: true, color: true } } },
|
|
231
|
+
});
|
|
232
|
+
await logAuditEvent({
|
|
233
|
+
action: 'library.file.update',
|
|
234
|
+
actorId: user.userId,
|
|
235
|
+
targetType: 'library_file',
|
|
236
|
+
targetId: fileId,
|
|
237
|
+
details: { name: body.name, fileName: body.fileName },
|
|
238
|
+
});
|
|
239
|
+
return c.json({
|
|
240
|
+
success: true,
|
|
241
|
+
data: { ...file, tags: parseStringArray(file.tags) },
|
|
242
|
+
});
|
|
243
|
+
});
|
|
244
|
+
// ── Delete file ──
|
|
245
|
+
libraryRouter.delete('/files/:fileId', requireRole('ADMIN'), async (c) => {
|
|
246
|
+
const db = getDb();
|
|
247
|
+
const user = getUser(c);
|
|
248
|
+
const fileId = c.req.param('fileId');
|
|
249
|
+
const existing = await db.libraryFile.findUnique({ where: { id: fileId } });
|
|
250
|
+
if (!existing)
|
|
251
|
+
throw new HttpError(404, 'NOT_FOUND', 'Library file not found');
|
|
252
|
+
await db.libraryFile.delete({ where: { id: fileId } });
|
|
253
|
+
await logAuditEvent({
|
|
254
|
+
action: 'library.file.delete',
|
|
255
|
+
actorId: user.userId,
|
|
256
|
+
targetType: 'library_file',
|
|
257
|
+
targetId: fileId,
|
|
258
|
+
details: { name: existing.name, fileName: existing.fileName },
|
|
259
|
+
});
|
|
260
|
+
return c.json({ success: true, data: { deleted: true } });
|
|
261
|
+
});
|
|
262
|
+
// ── Move files to a category (drag-and-drop support) ──
|
|
263
|
+
libraryRouter.post('/files/move', requireRole('ADMIN', 'OPERATOR'), async (c) => {
|
|
264
|
+
const db = getDb();
|
|
265
|
+
const user = getUser(c);
|
|
266
|
+
const body = await parseBody(c, moveFilesSchema);
|
|
267
|
+
const fileIds = body.fileIds;
|
|
268
|
+
const categoryId = body.categoryId ?? null;
|
|
269
|
+
if (categoryId) {
|
|
270
|
+
const cat = await db.libraryCategory.findUnique({ where: { id: categoryId } });
|
|
271
|
+
if (!cat)
|
|
272
|
+
throw new HttpError(404, 'NOT_FOUND', 'Target category not found');
|
|
273
|
+
}
|
|
274
|
+
await db.libraryFile.updateMany({
|
|
275
|
+
where: { id: { in: fileIds } },
|
|
276
|
+
data: { categoryId },
|
|
277
|
+
});
|
|
278
|
+
await logAuditEvent({
|
|
279
|
+
action: 'library.file.move',
|
|
280
|
+
actorId: user.userId,
|
|
281
|
+
targetType: 'library_category',
|
|
282
|
+
targetId: categoryId ?? 'uncategorized',
|
|
283
|
+
details: { fileIds, categoryId },
|
|
284
|
+
});
|
|
285
|
+
return c.json({ success: true, data: { moved: fileIds.length } });
|
|
286
|
+
});
|
|
287
|
+
// ════════════════════════════════════════════════
|
|
288
|
+
// Deploy Library Item to Nodes
|
|
289
|
+
// ════════════════════════════════════════════════
|
|
290
|
+
libraryRouter.post('/deploy', requireRole('ADMIN', 'OPERATOR'), async (c) => {
|
|
291
|
+
const db = getDb();
|
|
292
|
+
const user = getUser(c);
|
|
293
|
+
const body = await parseBody(c, deployLibrarySchema);
|
|
294
|
+
// Load library file with content
|
|
295
|
+
const file = await db.libraryFile.findUnique({ where: { id: body.fileId } });
|
|
296
|
+
if (!file)
|
|
297
|
+
throw new HttpError(404, 'NOT_FOUND', 'Library file not found');
|
|
298
|
+
// Parse content based on MIME type
|
|
299
|
+
let parsed;
|
|
300
|
+
try {
|
|
301
|
+
parsed = JSON.parse(file.content);
|
|
302
|
+
}
|
|
303
|
+
catch {
|
|
304
|
+
throw new HttpError(400, 'VALIDATION_ERROR', 'Library file content is not valid JSON');
|
|
305
|
+
}
|
|
306
|
+
// Load target nodes
|
|
307
|
+
const nodes = await db.node.findMany({
|
|
308
|
+
where: { id: { in: body.nodeIds }, status: 'ONLINE' },
|
|
309
|
+
select: { id: true, name: true, ipAddress: true, port: true },
|
|
310
|
+
});
|
|
311
|
+
if (nodes.length === 0) {
|
|
312
|
+
throw new HttpError(400, 'NO_ONLINE_NODES', 'No online nodes found from the provided list');
|
|
313
|
+
}
|
|
314
|
+
// Claim after validation/preview/preflight so a rejected retry is not a duplicate.
|
|
315
|
+
await enforceIdempotencyFromHeader(c);
|
|
316
|
+
const results = await Promise.allSettled(nodes.map(async (node) => {
|
|
317
|
+
const client = new NodeApiClient({
|
|
318
|
+
baseUrl: getNodeBaseUrl(node.ipAddress, node.port),
|
|
319
|
+
resourceNodeId: node.id,
|
|
320
|
+
nodeToken: getNodeManagerSecret(),
|
|
321
|
+
timeout: 30_000,
|
|
322
|
+
});
|
|
323
|
+
try {
|
|
324
|
+
if (file.mimeType === 'application/x-magnus-skill') {
|
|
325
|
+
// Deploy skill: write each file to /opt/magnus/skills/{name}/{version}/
|
|
326
|
+
const manifest = parsed['manifest'];
|
|
327
|
+
const files = parsed['files'];
|
|
328
|
+
const skillName = (manifest?.['name'] ?? file.name);
|
|
329
|
+
const skillVersion = (manifest?.['version'] ?? '1.0.0');
|
|
330
|
+
if (files) {
|
|
331
|
+
for (const [fileName, content] of Object.entries(files)) {
|
|
332
|
+
const filePath = `/opt/magnus/skills/${skillName}/${skillVersion}/${fileName}`;
|
|
333
|
+
await client.writeFile({
|
|
334
|
+
filePath,
|
|
335
|
+
content: content,
|
|
336
|
+
createIfMissing: true,
|
|
337
|
+
});
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
else if (file.mimeType === 'application/x-magnus-cronjob') {
|
|
342
|
+
const cron = createCronSchema.parse({ ...parsed, nodeId: node.id, name: parsed['name'] ?? file.name });
|
|
343
|
+
const mode = await cronMutationMode(node.id);
|
|
344
|
+
if (mode === 'legacy') {
|
|
345
|
+
await client.syncCronJob({ nodeId: node.id, name: cron.name, description: cron.description,
|
|
346
|
+
schedule: cron.schedule, command: cron.command, args: cron.args,
|
|
347
|
+
workingDirectory: cron.workingDirectory ?? undefined,
|
|
348
|
+
environment: sanitizeDetails(cron.environment), timeoutSeconds: cron.timeoutSeconds });
|
|
349
|
+
}
|
|
350
|
+
else {
|
|
351
|
+
if (!cron.managed)
|
|
352
|
+
throw new Error('Activated nodes require an exact finite managed cron revision');
|
|
353
|
+
const { job } = await upsertAndRegisterManagedCron(node.id, cron.name, {
|
|
354
|
+
description: cron.description, schedule: cron.schedule, command: cron.command,
|
|
355
|
+
args: JSON.stringify(cron.args), workingDirectory: cron.workingDirectory ?? null,
|
|
356
|
+
environment: JSON.stringify(sanitizeDetails(cron.environment)), timeoutSeconds: cron.timeoutSeconds,
|
|
357
|
+
status: 'ACTIVE', createdBy: user.userId,
|
|
358
|
+
}, cron.managed);
|
|
359
|
+
await installManagedCron(job.id, user.userId);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
else {
|
|
363
|
+
throw new Error(`Unsupported MIME type for deploy: ${file.mimeType}`);
|
|
364
|
+
}
|
|
365
|
+
return {
|
|
366
|
+
nodeId: node.id,
|
|
367
|
+
nodeName: node.name,
|
|
368
|
+
status: 'success',
|
|
369
|
+
};
|
|
370
|
+
}
|
|
371
|
+
catch (err) {
|
|
372
|
+
return {
|
|
373
|
+
nodeId: node.id,
|
|
374
|
+
nodeName: node.name,
|
|
375
|
+
status: 'failed',
|
|
376
|
+
error: err instanceof Error ? err.message : 'Unknown error',
|
|
377
|
+
};
|
|
378
|
+
}
|
|
379
|
+
}));
|
|
380
|
+
const data = results.map((r) => r.status === 'fulfilled'
|
|
381
|
+
? r.value
|
|
382
|
+
: {
|
|
383
|
+
nodeId: 'unknown',
|
|
384
|
+
nodeName: 'unknown',
|
|
385
|
+
status: 'failed',
|
|
386
|
+
error: r.reason instanceof Error ? r.reason.message : 'Unknown error',
|
|
387
|
+
});
|
|
388
|
+
await logAuditEvent({
|
|
389
|
+
action: 'library.deploy',
|
|
390
|
+
actorId: user.userId,
|
|
391
|
+
targetType: 'library_file',
|
|
392
|
+
targetId: body.fileId,
|
|
393
|
+
details: {
|
|
394
|
+
fileName: file.name,
|
|
395
|
+
mimeType: file.mimeType,
|
|
396
|
+
nodeCount: body.nodeIds.length,
|
|
397
|
+
successCount: data.filter((d) => d.status === 'success').length,
|
|
398
|
+
},
|
|
399
|
+
});
|
|
400
|
+
return c.json({ success: true, data });
|
|
401
|
+
});
|
|
402
|
+
//# sourceMappingURL=library.js.map
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
import { Hono } from 'hono';
|
|
2
|
+
import { createHmac, timingSafeEqual } from 'node:crypto';
|
|
3
|
+
import { streamSSE } from 'hono/streaming';
|
|
4
|
+
import { getDb } from '../db/index.js';
|
|
5
|
+
import { authMiddleware } from '../middleware/auth.js';
|
|
6
|
+
import { sanitizeDetails } from '../services/audit-service.js';
|
|
7
|
+
import { emitLog, onLog } from '../services/log-emitter.js';
|
|
8
|
+
import { parseBody } from '../utils/validate.js';
|
|
9
|
+
import { logQuerySchema, logIngestSchema } from '../schemas/logs.js';
|
|
10
|
+
import { LOG_INGEST_PREVIOUS_SIGNING_SECRET, LOG_INGEST_SIGNING_SECRET, } from '../utils/env.js';
|
|
11
|
+
import { HttpError } from '../middleware/error-handler.js';
|
|
12
|
+
export const logsRouter = new Hono();
|
|
13
|
+
logsRouter.use('/query', authMiddleware);
|
|
14
|
+
logsRouter.use('/stream', authMiddleware);
|
|
15
|
+
function verifyLogToken(nodeIdentity, provided) {
|
|
16
|
+
if (LOG_INGEST_SIGNING_SECRET.length < 32 || !provided)
|
|
17
|
+
return false;
|
|
18
|
+
const actualBuffer = Buffer.from(provided);
|
|
19
|
+
const candidates = [
|
|
20
|
+
LOG_INGEST_SIGNING_SECRET,
|
|
21
|
+
...(LOG_INGEST_PREVIOUS_SIGNING_SECRET.length >= 32
|
|
22
|
+
? [LOG_INGEST_PREVIOUS_SIGNING_SECRET]
|
|
23
|
+
: []),
|
|
24
|
+
];
|
|
25
|
+
let matched = false;
|
|
26
|
+
for (const secret of candidates) {
|
|
27
|
+
const expectedBuffer = Buffer.from(createHmac('sha256', secret)
|
|
28
|
+
.update(`magnus:log-ingest:v1:${nodeIdentity.toLowerCase()}`)
|
|
29
|
+
.digest('base64url'));
|
|
30
|
+
matched = (actualBuffer.length === expectedBuffer.length
|
|
31
|
+
&& timingSafeEqual(actualBuffer, expectedBuffer)) || matched;
|
|
32
|
+
}
|
|
33
|
+
return matched;
|
|
34
|
+
}
|
|
35
|
+
// ── Query logs ──
|
|
36
|
+
logsRouter.post('/query', async (c) => {
|
|
37
|
+
const db = getDb();
|
|
38
|
+
const body = await parseBody(c, logQuerySchema);
|
|
39
|
+
const where = {};
|
|
40
|
+
if (body.nodeId)
|
|
41
|
+
where['nodeId'] = body.nodeId;
|
|
42
|
+
if (body.source)
|
|
43
|
+
where['source'] = body.source;
|
|
44
|
+
if (body.level)
|
|
45
|
+
where['level'] = body.level;
|
|
46
|
+
if (body.search) {
|
|
47
|
+
where['message'] = { contains: body.search };
|
|
48
|
+
}
|
|
49
|
+
if (body.since || body.until) {
|
|
50
|
+
where['timestamp'] = {
|
|
51
|
+
...(body.since ? { gte: new Date(body.since) } : {}),
|
|
52
|
+
...(body.until ? { lte: new Date(body.until) } : {}),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
const limit = Math.min(body.limit ?? 100, 1000);
|
|
56
|
+
const offset = body.offset ?? 0;
|
|
57
|
+
// Cursor-based pagination: if cursor is provided, use it instead of offset
|
|
58
|
+
if (body.cursor) {
|
|
59
|
+
where['id'] = { lt: body.cursor };
|
|
60
|
+
}
|
|
61
|
+
const [logs, total] = await Promise.all([
|
|
62
|
+
db.logEntry.findMany({
|
|
63
|
+
where,
|
|
64
|
+
orderBy: { timestamp: 'desc' },
|
|
65
|
+
take: limit,
|
|
66
|
+
...(body.cursor ? {} : { skip: offset }),
|
|
67
|
+
}),
|
|
68
|
+
db.logEntry.count({ where: { ...where, ...(body.cursor ? {} : {}) } }),
|
|
69
|
+
]);
|
|
70
|
+
const nextCursor = logs.length === limit ? logs[logs.length - 1]?.id : undefined;
|
|
71
|
+
return c.json({
|
|
72
|
+
success: true,
|
|
73
|
+
data: {
|
|
74
|
+
logs,
|
|
75
|
+
total,
|
|
76
|
+
hasMore: body.cursor ? logs.length === limit : offset + limit < total,
|
|
77
|
+
nextCursor,
|
|
78
|
+
},
|
|
79
|
+
});
|
|
80
|
+
});
|
|
81
|
+
// ── Ingest logs from agents (internal) ──
|
|
82
|
+
logsRouter.post('/ingest', async (c) => {
|
|
83
|
+
const db = getDb();
|
|
84
|
+
const body = await parseBody(c, logIngestSchema);
|
|
85
|
+
const entries = Array.isArray(body) ? body : [body];
|
|
86
|
+
const identities = [...new Set(entries.map((entry) => entry.nodeId.trim().toLowerCase()))];
|
|
87
|
+
if (identities.length !== 1) {
|
|
88
|
+
throw new HttpError(400, 'NODE_IDENTITY_MISMATCH', 'A log batch must contain exactly one node identity');
|
|
89
|
+
}
|
|
90
|
+
const nodeIdentity = identities[0];
|
|
91
|
+
if (!verifyLogToken(nodeIdentity, c.req.header('x-log-token') ?? '')) {
|
|
92
|
+
throw new HttpError(401, 'INVALID_CREDENTIALS', 'Invalid node-bound log credential');
|
|
93
|
+
}
|
|
94
|
+
const node = await db.node.findFirst({
|
|
95
|
+
where: {
|
|
96
|
+
status: { not: 'DECOMMISSIONED' },
|
|
97
|
+
OR: [
|
|
98
|
+
{ id: nodeIdentity },
|
|
99
|
+
{ name: { equals: nodeIdentity, mode: 'insensitive' } },
|
|
100
|
+
{ hostname: { equals: nodeIdentity, mode: 'insensitive' } },
|
|
101
|
+
],
|
|
102
|
+
},
|
|
103
|
+
select: { id: true },
|
|
104
|
+
});
|
|
105
|
+
if (!node)
|
|
106
|
+
throw new HttpError(401, 'INVALID_CREDENTIALS', 'Unknown node identity');
|
|
107
|
+
await db.logEntry.createMany({
|
|
108
|
+
data: entries.map((e) => ({
|
|
109
|
+
nodeId: node.id,
|
|
110
|
+
source: e.source ?? 'agent',
|
|
111
|
+
level: e.level ?? 'info',
|
|
112
|
+
message: e.message,
|
|
113
|
+
metadata: e.metadata ? JSON.stringify(sanitizeDetails(e.metadata)) : '{}',
|
|
114
|
+
timestamp: e.timestamp ? new Date(e.timestamp) : new Date(),
|
|
115
|
+
})),
|
|
116
|
+
});
|
|
117
|
+
// Emit to SSE subscribers
|
|
118
|
+
for (const e of entries) {
|
|
119
|
+
emitLog({
|
|
120
|
+
id: '',
|
|
121
|
+
nodeId: node.id,
|
|
122
|
+
source: (e.source ?? 'agent'),
|
|
123
|
+
level: (e.level ?? 'info'),
|
|
124
|
+
message: e.message,
|
|
125
|
+
metadata: e.metadata ? sanitizeDetails(e.metadata) : {},
|
|
126
|
+
timestamp: e.timestamp ? new Date(e.timestamp) : new Date(),
|
|
127
|
+
});
|
|
128
|
+
}
|
|
129
|
+
return c.json({ success: true, data: { ingested: entries.length } }, 201);
|
|
130
|
+
});
|
|
131
|
+
// ── SSE log stream (live tail) ──
|
|
132
|
+
logsRouter.get('/stream', (c) => {
|
|
133
|
+
// Parse optional filters from query params
|
|
134
|
+
const nodeIdsParam = c.req.query('nodeIds');
|
|
135
|
+
const sourcesParam = c.req.query('sources');
|
|
136
|
+
const levelsParam = c.req.query('levels');
|
|
137
|
+
const nodeIds = nodeIdsParam ? nodeIdsParam.split(',').filter(Boolean) : undefined;
|
|
138
|
+
const sources = sourcesParam ? sourcesParam.split(',').filter(Boolean) : undefined;
|
|
139
|
+
const levels = levelsParam ? levelsParam.split(',').filter(Boolean) : undefined;
|
|
140
|
+
return streamSSE(c, async (stream) => {
|
|
141
|
+
let eventId = 0;
|
|
142
|
+
// Keep-alive heartbeat every 30s
|
|
143
|
+
const heartbeatTimer = setInterval(() => {
|
|
144
|
+
void stream.writeSSE({ data: '', event: 'heartbeat', id: String(eventId++) });
|
|
145
|
+
}, 30_000);
|
|
146
|
+
const unsubscribe = onLog((entry) => {
|
|
147
|
+
// Apply filters
|
|
148
|
+
if (nodeIds && !nodeIds.includes(entry.nodeId))
|
|
149
|
+
return;
|
|
150
|
+
if (sources && !sources.includes(entry.source))
|
|
151
|
+
return;
|
|
152
|
+
if (levels && !levels.includes(entry.level))
|
|
153
|
+
return;
|
|
154
|
+
void stream.writeSSE({
|
|
155
|
+
data: JSON.stringify(entry),
|
|
156
|
+
event: 'log',
|
|
157
|
+
id: String(eventId++),
|
|
158
|
+
});
|
|
159
|
+
});
|
|
160
|
+
// Wait until the client disconnects
|
|
161
|
+
stream.onAbort(() => {
|
|
162
|
+
clearInterval(heartbeatTimer);
|
|
163
|
+
unsubscribe();
|
|
164
|
+
});
|
|
165
|
+
// Keep the stream open — the onAbort callback will clean up
|
|
166
|
+
// We need to await something that never resolves to keep the stream alive
|
|
167
|
+
await new Promise(() => {
|
|
168
|
+
// intentionally never resolves — stream closed via onAbort
|
|
169
|
+
});
|
|
170
|
+
});
|
|
171
|
+
});
|
|
172
|
+
//# sourceMappingURL=logs.js.map
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/** Node credentials may consume existing authority, never create a cron definition. */
|
|
2
|
+
import { Hono } from 'hono';
|
|
3
|
+
import { z } from 'zod';
|
|
4
|
+
import { HttpError } from '../middleware/error-handler.js';
|
|
5
|
+
import { NODE_MANAGER_SECRET } from '../utils/env.js';
|
|
6
|
+
import { verifyWithRotation } from '../services/credential-rotation-service.js';
|
|
7
|
+
import { parseBody } from '../utils/validate.js';
|
|
8
|
+
import { admitCronOccurrence, cronOccurrenceStatus, settleCronOccurrence, schedulerTriggerSchema, schedulerSettleSchema } from '../services/managed-cron.js';
|
|
9
|
+
export const managedCronRouter = new Hono();
|
|
10
|
+
managedCronRouter.use('*', async (c, next) => {
|
|
11
|
+
const token = c.req.header('x-node-token') ?? '';
|
|
12
|
+
if (!token || !NODE_MANAGER_SECRET || !verifyWithRotation('NODE_MANAGER_SECRET', NODE_MANAGER_SECRET, token))
|
|
13
|
+
throw new HttpError(401, 'UNAUTHORIZED', 'Node credential required');
|
|
14
|
+
c.header('Cache-Control', 'no-store');
|
|
15
|
+
await next();
|
|
16
|
+
});
|
|
17
|
+
managedCronRouter.post('/admit', async (c) => c.json({ success: true, data: await admitCronOccurrence(await parseBody(c, schedulerTriggerSchema)) }));
|
|
18
|
+
managedCronRouter.post('/settle', async (c) => c.json({ success: true, data: await settleCronOccurrence(await parseBody(c, schedulerSettleSchema)) }));
|
|
19
|
+
managedCronRouter.post('/status', async (c) => {
|
|
20
|
+
const body = await parseBody(c, z.object({ nodeFqdn: z.string().min(1).max(253), occurrenceId: z.string().regex(/^[a-f0-9]{64}$/) }).strict());
|
|
21
|
+
return c.json({ success: true, data: await cronOccurrenceStatus(body.nodeFqdn, body.occurrenceId) });
|
|
22
|
+
});
|
|
23
|
+
//# sourceMappingURL=managed-cron.js.map
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { Hono } from 'hono';
|
|
2
|
+
import { authMiddleware } from '../middleware/auth.js';
|
|
3
|
+
import { getDependencyHealth, getFleetReadiness, getFleetTimeline, getRetentionSummary, } from '../services/ops-service.js';
|
|
4
|
+
import { getCodexFleetPosture } from '../services/codex-service.js';
|
|
5
|
+
export const mcpRouter = new Hono();
|
|
6
|
+
const tools = [
|
|
7
|
+
{ name: 'magnus_dependency_health', description: 'Read Magnus dependency health checks.' },
|
|
8
|
+
{ name: 'magnus_fleet_readiness', description: 'Read per-node fleet readiness and stale-node posture.' },
|
|
9
|
+
{ name: 'magnus_fleet_timeline', description: 'Read recent fleet events from logs, commands, deploys, Hermes jobs, and audit.' },
|
|
10
|
+
{ name: 'magnus_retention_summary', description: 'Read retention counts and oldest known operational records.' },
|
|
11
|
+
{ name: 'magnus_codex_fleet_status', description: 'Read cached Codex CLI version, update, and ChatGPT OAuth posture.' },
|
|
12
|
+
];
|
|
13
|
+
mcpRouter.use('*', authMiddleware);
|
|
14
|
+
mcpRouter.get('/', (c) => c.json({
|
|
15
|
+
name: 'magnus-readonly',
|
|
16
|
+
version: '0.1.0',
|
|
17
|
+
description: 'Read-only MCP-compatible Magnus fleet tools. Mutating tools are intentionally absent.',
|
|
18
|
+
tools,
|
|
19
|
+
}));
|
|
20
|
+
mcpRouter.post('/', async (c) => {
|
|
21
|
+
const body = await c.req.json();
|
|
22
|
+
if (body.method === 'tools/list') {
|
|
23
|
+
return c.json({ tools });
|
|
24
|
+
}
|
|
25
|
+
if (body.method === 'tools/call') {
|
|
26
|
+
const name = body.params?.name;
|
|
27
|
+
const result = name === 'magnus_dependency_health' ? await getDependencyHealth() :
|
|
28
|
+
name === 'magnus_fleet_readiness' ? await getFleetReadiness() :
|
|
29
|
+
name === 'magnus_fleet_timeline' ? await getFleetTimeline(Number(body.params?.arguments?.['limit'] ?? 80)) :
|
|
30
|
+
name === 'magnus_retention_summary' ? await getRetentionSummary() :
|
|
31
|
+
name === 'magnus_codex_fleet_status' ? getCodexFleetPosture() :
|
|
32
|
+
null;
|
|
33
|
+
if (!result)
|
|
34
|
+
return c.json({ error: { code: 'UNKNOWN_TOOL', message: `Unknown tool: ${name}` } }, 404);
|
|
35
|
+
return c.json({ content: [{ type: 'json', json: result }] });
|
|
36
|
+
}
|
|
37
|
+
return c.json({ error: { code: 'UNSUPPORTED_METHOD', message: 'Supported methods: tools/list, tools/call' } }, 400);
|
|
38
|
+
});
|
|
39
|
+
//# sourceMappingURL=mcp.js.map
|