@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,388 @@
|
|
|
1
|
+
import { getDb } from '../db/index.js';
|
|
2
|
+
import { NodeApiClient } from '../sdk/index.js';
|
|
3
|
+
import { enqueueCommand } from '../queue/workers.js';
|
|
4
|
+
import { getNodeBaseUrl } from '../utils/node-url.js';
|
|
5
|
+
import { randomBytes } from 'node:crypto';
|
|
6
|
+
import { nanoid } from 'nanoid';
|
|
7
|
+
// ─── Role Application Service ───
|
|
8
|
+
// Orchestrates multi-step apply/remove of roles on nodes.
|
|
9
|
+
const CONTROL_API_URL = process.env['CONTROL_API_URL'] ?? 'https://localhost:4000';
|
|
10
|
+
import { getNodeManagerSecret } from '../utils/env.js';
|
|
11
|
+
/** Ensure the 'system' user exists — required as FK target for RemoteCommand.createdBy. */
|
|
12
|
+
let systemUserEnsured = false;
|
|
13
|
+
async function ensureSystemUser() {
|
|
14
|
+
if (systemUserEnsured)
|
|
15
|
+
return;
|
|
16
|
+
const db = getDb();
|
|
17
|
+
const existing = await db.user.findUnique({ where: { id: 'system' } });
|
|
18
|
+
if (!existing) {
|
|
19
|
+
await db.user.create({
|
|
20
|
+
data: {
|
|
21
|
+
id: 'system',
|
|
22
|
+
email: 'system@magnus.local',
|
|
23
|
+
name: 'System',
|
|
24
|
+
password: randomBytes(32).toString('hex'),
|
|
25
|
+
role: 'ADMIN',
|
|
26
|
+
active: true,
|
|
27
|
+
},
|
|
28
|
+
}).catch(() => {
|
|
29
|
+
// Another concurrent call may have created it — ignore unique constraint errors
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
systemUserEnsured = true;
|
|
33
|
+
}
|
|
34
|
+
/** Update a single step's status in the RoleApplication record. */
|
|
35
|
+
async function updateStep(applicationId, stepName, update) {
|
|
36
|
+
const db = getDb();
|
|
37
|
+
const app = await db.roleApplication.findUnique({ where: { id: applicationId } });
|
|
38
|
+
if (!app)
|
|
39
|
+
return;
|
|
40
|
+
const steps = JSON.parse(app.steps);
|
|
41
|
+
const step = steps.find((s) => s.name === stepName);
|
|
42
|
+
if (step) {
|
|
43
|
+
Object.assign(step, update);
|
|
44
|
+
}
|
|
45
|
+
await db.roleApplication.update({
|
|
46
|
+
where: { id: applicationId },
|
|
47
|
+
data: { steps: JSON.stringify(steps) },
|
|
48
|
+
});
|
|
49
|
+
}
|
|
50
|
+
/** Dispatch a command to a node and wait for the result. */
|
|
51
|
+
async function dispatchAndWait(ctx, command, args = [], timeoutSeconds = 300) {
|
|
52
|
+
const db = getDb();
|
|
53
|
+
// Ensure the 'system' user exists (FK target for createdBy)
|
|
54
|
+
await ensureSystemUser();
|
|
55
|
+
// Create a RemoteCommand record
|
|
56
|
+
const idempotencyKey = `role-${ctx.applicationId}-${nanoid()}`;
|
|
57
|
+
const cmd = await db.remoteCommand.create({
|
|
58
|
+
data: {
|
|
59
|
+
nodeId: ctx.nodeId,
|
|
60
|
+
command,
|
|
61
|
+
args: JSON.stringify(args),
|
|
62
|
+
timeoutSeconds,
|
|
63
|
+
status: 'QUEUED',
|
|
64
|
+
riskLevel: 'medium',
|
|
65
|
+
idempotencyKey,
|
|
66
|
+
createdBy: 'system',
|
|
67
|
+
},
|
|
68
|
+
});
|
|
69
|
+
// Dispatch to queue
|
|
70
|
+
const node = await db.node.findUnique({ where: { id: ctx.nodeId } });
|
|
71
|
+
if (!node)
|
|
72
|
+
throw new Error(`Node ${ctx.nodeId} not found`);
|
|
73
|
+
await enqueueCommand(cmd.id);
|
|
74
|
+
// Poll for completion (max wait = timeoutSeconds + 30s buffer)
|
|
75
|
+
const deadline = Date.now() + (timeoutSeconds + 30) * 1000;
|
|
76
|
+
while (Date.now() < deadline) {
|
|
77
|
+
await new Promise((r) => setTimeout(r, 2000));
|
|
78
|
+
const updated = await db.remoteCommand.findUnique({
|
|
79
|
+
where: { id: cmd.id },
|
|
80
|
+
include: { result: true },
|
|
81
|
+
});
|
|
82
|
+
if (updated && ['COMPLETED', 'FAILED', 'TIMEOUT', 'CANCELLED'].includes(updated.status)) {
|
|
83
|
+
return {
|
|
84
|
+
exitCode: updated.result?.exitCode ?? 1,
|
|
85
|
+
stdout: updated.result?.stdout ?? '',
|
|
86
|
+
stderr: updated.result?.stderr ?? '',
|
|
87
|
+
};
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return { exitCode: 124, stdout: '', stderr: 'Timed out waiting for command result' };
|
|
91
|
+
}
|
|
92
|
+
/** Write a file to the node via the node-manager API.
|
|
93
|
+
* Falls back to base64+command when the agent lacks /files/write (404). */
|
|
94
|
+
async function writeFileToNode(ctx, filePath, content) {
|
|
95
|
+
const client = new NodeApiClient({ baseUrl: ctx.nodeBaseUrl, nodeToken: ctx.nodeToken, resourceNodeId: ctx.nodeId });
|
|
96
|
+
try {
|
|
97
|
+
await client.writeFile({ filePath, content, createIfMissing: true });
|
|
98
|
+
}
|
|
99
|
+
catch (err) {
|
|
100
|
+
// If the agent is old and doesn't have /files/write (404),
|
|
101
|
+
// write via the command executor using base64 decode.
|
|
102
|
+
const is404 = err && typeof err === 'object' && 'response' in err
|
|
103
|
+
? err.response.status === 404
|
|
104
|
+
: false;
|
|
105
|
+
if (!is404)
|
|
106
|
+
throw err;
|
|
107
|
+
const b64 = Buffer.from(content, 'utf-8').toString('base64');
|
|
108
|
+
const parentDir = filePath.replace(/\/[^/]+$/, '');
|
|
109
|
+
const sq = (s) => "'" + s.replace(/'/g, "'\\''") + "'";
|
|
110
|
+
const cmd = `mkdir -p ${sq(parentDir)} && printf '%s' ${sq(b64)} | base64 -d > ${sq(filePath)}`;
|
|
111
|
+
const result = await dispatchAndWait(ctx, 'bash', ['-c', cmd], 30);
|
|
112
|
+
if (result.exitCode !== 0) {
|
|
113
|
+
throw new Error(result.stderr || 'Failed to write file via command fallback');
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
// ─── Apply Role ───
|
|
118
|
+
export async function applyRole(applicationId) {
|
|
119
|
+
const db = getDb();
|
|
120
|
+
const application = await db.roleApplication.findUnique({
|
|
121
|
+
where: { id: applicationId },
|
|
122
|
+
include: { role: true, node: true },
|
|
123
|
+
});
|
|
124
|
+
if (!application)
|
|
125
|
+
throw new Error('RoleApplication not found');
|
|
126
|
+
const { role, node } = application;
|
|
127
|
+
const ctx = {
|
|
128
|
+
applicationId,
|
|
129
|
+
nodeId: node.id,
|
|
130
|
+
roleId: role.id,
|
|
131
|
+
nodeBaseUrl: getNodeBaseUrl(node.ipAddress, node.port),
|
|
132
|
+
nodeToken: getNodeManagerSecret(),
|
|
133
|
+
};
|
|
134
|
+
// Build step list based on what the role configures
|
|
135
|
+
const stepDefs = [
|
|
136
|
+
{ name: 'apt-packages', condition: JSON.parse(role.aptPackages).length > 0 },
|
|
137
|
+
{ name: 'npm-packages', condition: JSON.parse(role.npmPackages).length > 0 },
|
|
138
|
+
{ name: 'deploy-files', condition: JSON.parse(role.libraryFileIds).length > 0 },
|
|
139
|
+
{ name: 'deploy-skills', condition: JSON.parse(role.skillNames).length > 0 },
|
|
140
|
+
{ name: 'write-env', condition: Object.keys(JSON.parse(role.envConfig)).length > 0 },
|
|
141
|
+
{ name: 'docker-setup', condition: role.dockerEnabled },
|
|
142
|
+
{ name: 'firewall-setup', condition: role.firewallEnabled },
|
|
143
|
+
];
|
|
144
|
+
const steps = stepDefs.map((s) => ({
|
|
145
|
+
name: s.name,
|
|
146
|
+
status: s.condition ? 'pending' : 'skipped',
|
|
147
|
+
}));
|
|
148
|
+
await db.roleApplication.update({
|
|
149
|
+
where: { id: applicationId },
|
|
150
|
+
data: {
|
|
151
|
+
status: 'running',
|
|
152
|
+
startedAt: new Date(),
|
|
153
|
+
steps: JSON.stringify(steps),
|
|
154
|
+
},
|
|
155
|
+
});
|
|
156
|
+
try {
|
|
157
|
+
// 1. Apt packages
|
|
158
|
+
const aptPkgs = JSON.parse(role.aptPackages);
|
|
159
|
+
if (aptPkgs.length > 0) {
|
|
160
|
+
await updateStep(applicationId, 'apt-packages', { status: 'running', startedAt: new Date().toISOString() });
|
|
161
|
+
const result = await dispatchAndWait(ctx, 'bash', ['-c', `DEBIAN_FRONTEND=noninteractive apt-get update -qq && apt-get install -y -qq ${aptPkgs.join(' ')}`], 600);
|
|
162
|
+
if (result.exitCode !== 0) {
|
|
163
|
+
await updateStep(applicationId, 'apt-packages', { status: 'failed', error: result.stderr.slice(0, 500), completedAt: new Date().toISOString() });
|
|
164
|
+
throw new Error(`apt install failed: ${result.stderr.slice(0, 200)}`);
|
|
165
|
+
}
|
|
166
|
+
await updateStep(applicationId, 'apt-packages', { status: 'completed', completedAt: new Date().toISOString() });
|
|
167
|
+
}
|
|
168
|
+
// 2. npm packages
|
|
169
|
+
const npmPkgs = JSON.parse(role.npmPackages);
|
|
170
|
+
if (npmPkgs.length > 0) {
|
|
171
|
+
await updateStep(applicationId, 'npm-packages', { status: 'running', startedAt: new Date().toISOString() });
|
|
172
|
+
const result = await dispatchAndWait(ctx, 'bash', ['-c', `npm install -g ${npmPkgs.join(' ')}`], 300);
|
|
173
|
+
if (result.exitCode !== 0) {
|
|
174
|
+
await updateStep(applicationId, 'npm-packages', { status: 'failed', error: result.stderr.slice(0, 500), completedAt: new Date().toISOString() });
|
|
175
|
+
throw new Error(`npm install failed: ${result.stderr.slice(0, 200)}`);
|
|
176
|
+
}
|
|
177
|
+
await updateStep(applicationId, 'npm-packages', { status: 'completed', completedAt: new Date().toISOString() });
|
|
178
|
+
}
|
|
179
|
+
// 3. Deploy Library files
|
|
180
|
+
const fileIds = JSON.parse(role.libraryFileIds);
|
|
181
|
+
if (fileIds.length > 0) {
|
|
182
|
+
await updateStep(applicationId, 'deploy-files', { status: 'running', startedAt: new Date().toISOString() });
|
|
183
|
+
for (const fileId of fileIds) {
|
|
184
|
+
const libFile = await db.libraryFile.findUnique({ where: { id: fileId } });
|
|
185
|
+
if (libFile) {
|
|
186
|
+
const targetPath = `/opt/magnus/roles/${role.name}/${libFile.fileName}`;
|
|
187
|
+
await writeFileToNode(ctx, targetPath, libFile.content);
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
await updateStep(applicationId, 'deploy-files', { status: 'completed', completedAt: new Date().toISOString() });
|
|
191
|
+
}
|
|
192
|
+
// 4. Deploy skills
|
|
193
|
+
const skillNames = JSON.parse(role.skillNames);
|
|
194
|
+
if (skillNames.length > 0) {
|
|
195
|
+
await updateStep(applicationId, 'deploy-skills', { status: 'running', startedAt: new Date().toISOString() });
|
|
196
|
+
for (const skillName of skillNames) {
|
|
197
|
+
// Create or update skill installation record
|
|
198
|
+
await db.skillInstallation.upsert({
|
|
199
|
+
where: { skillName_nodeId: { skillName, nodeId: ctx.nodeId } },
|
|
200
|
+
create: {
|
|
201
|
+
skillName,
|
|
202
|
+
nodeId: ctx.nodeId,
|
|
203
|
+
version: '1.0.0',
|
|
204
|
+
status: 'installed',
|
|
205
|
+
installedAt: new Date(),
|
|
206
|
+
},
|
|
207
|
+
update: {
|
|
208
|
+
status: 'installed',
|
|
209
|
+
installedAt: new Date(),
|
|
210
|
+
},
|
|
211
|
+
});
|
|
212
|
+
}
|
|
213
|
+
await updateStep(applicationId, 'deploy-skills', { status: 'completed', completedAt: new Date().toISOString() });
|
|
214
|
+
}
|
|
215
|
+
// 5. Write .env config
|
|
216
|
+
const envConfig = JSON.parse(role.envConfig);
|
|
217
|
+
if (Object.keys(envConfig).length > 0) {
|
|
218
|
+
await updateStep(applicationId, 'write-env', { status: 'running', startedAt: new Date().toISOString() });
|
|
219
|
+
const envContent = Object.entries(envConfig)
|
|
220
|
+
.map(([k, v]) => `${k}=${v}`)
|
|
221
|
+
.join('\n') + '\n';
|
|
222
|
+
await writeFileToNode(ctx, `/opt/magnus/roles/${role.name}/.env`, envContent);
|
|
223
|
+
await updateStep(applicationId, 'write-env', { status: 'completed', completedAt: new Date().toISOString() });
|
|
224
|
+
}
|
|
225
|
+
// 6. Docker setup
|
|
226
|
+
if (role.dockerEnabled) {
|
|
227
|
+
await updateStep(applicationId, 'docker-setup', { status: 'running', startedAt: new Date().toISOString() });
|
|
228
|
+
// Ensure Docker is installed
|
|
229
|
+
await dispatchAndWait(ctx, 'bash', ['-c', 'command -v docker || (apt-get update -qq && apt-get install -y -qq docker.io)'], 300);
|
|
230
|
+
// Write Dockerfile
|
|
231
|
+
const dockerUser = role.dockerNonRoot ? '\nRUN useradd -m magnus\nUSER magnus' : '';
|
|
232
|
+
const baseImage = role.dockerImage ?? 'node:22-slim';
|
|
233
|
+
const dockerfile = `FROM ${baseImage}
|
|
234
|
+
WORKDIR /app
|
|
235
|
+
COPY . /app${dockerUser}
|
|
236
|
+
ENTRYPOINT ["bash", "-c", "source .env 2>/dev/null; exec \\"$@\\"", "--"]
|
|
237
|
+
CMD ["node", "."]
|
|
238
|
+
`;
|
|
239
|
+
await writeFileToNode(ctx, `/opt/magnus/roles/${role.name}/Dockerfile`, dockerfile);
|
|
240
|
+
// Build and run container
|
|
241
|
+
const containerName = `magnus-role-${role.name}`;
|
|
242
|
+
const dockerVolumes = JSON.parse(role.dockerVolumes);
|
|
243
|
+
const volumeFlags = dockerVolumes.map((v) => `-v ${v}`).join(' ');
|
|
244
|
+
const volumeStr = volumeFlags ? ` ${volumeFlags}` : '';
|
|
245
|
+
await dispatchAndWait(ctx, 'bash', ['-c', `cd /opt/magnus/roles/${role.name} && docker build -t ${containerName} . && docker rm -f ${containerName} 2>/dev/null; docker run -d --name ${containerName} --restart unless-stopped --network host${volumeStr} ${containerName}`], 300);
|
|
246
|
+
await updateStep(applicationId, 'docker-setup', { status: 'completed', completedAt: new Date().toISOString() });
|
|
247
|
+
}
|
|
248
|
+
// 7. Firewall setup
|
|
249
|
+
if (role.firewallEnabled) {
|
|
250
|
+
await updateStep(applicationId, 'firewall-setup', { status: 'running', startedAt: new Date().toISOString() });
|
|
251
|
+
const agentPort = node.port || 4100;
|
|
252
|
+
const controlApiHost = new URL(CONTROL_API_URL).hostname;
|
|
253
|
+
// Build UFW script
|
|
254
|
+
const lines = [
|
|
255
|
+
'ufw --force reset',
|
|
256
|
+
'ufw default deny incoming',
|
|
257
|
+
'ufw default allow outgoing',
|
|
258
|
+
`ufw allow ${agentPort}/tcp comment "Magnus agent"`,
|
|
259
|
+
'ufw allow 22/tcp comment "SSH"',
|
|
260
|
+
`ufw allow from ${controlApiHost} comment "Magnus control-api"`,
|
|
261
|
+
];
|
|
262
|
+
if (role.firewallMode === 'restrictive') {
|
|
263
|
+
// Block RFC-1918 private ranges (after allow rules take precedence)
|
|
264
|
+
lines.push('ufw deny from 10.0.0.0/8', 'ufw deny from 172.16.0.0/12', 'ufw deny from 192.168.0.0/16');
|
|
265
|
+
}
|
|
266
|
+
else if (role.firewallMode === 'custom') {
|
|
267
|
+
const customRules = JSON.parse(role.firewallAllowRules);
|
|
268
|
+
for (const rule of customRules) {
|
|
269
|
+
// Rules can be "80/tcp", "443/tcp", "10.0.0.0/8", etc.
|
|
270
|
+
if (rule.includes('/') && !rule.includes('.')) {
|
|
271
|
+
lines.push(`ufw allow ${rule}`);
|
|
272
|
+
}
|
|
273
|
+
else {
|
|
274
|
+
lines.push(`ufw allow from ${rule}`);
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
// 'permissive' mode = no extra deny/allow rules
|
|
279
|
+
lines.push('ufw --force enable');
|
|
280
|
+
const result = await dispatchAndWait(ctx, 'bash', ['-c', lines.join(' && ')], 120);
|
|
281
|
+
if (result.exitCode !== 0) {
|
|
282
|
+
await updateStep(applicationId, 'firewall-setup', { status: 'failed', error: result.stderr.slice(0, 500), completedAt: new Date().toISOString() });
|
|
283
|
+
throw new Error(`UFW setup failed: ${result.stderr.slice(0, 200)}`);
|
|
284
|
+
}
|
|
285
|
+
await updateStep(applicationId, 'firewall-setup', { status: 'completed', completedAt: new Date().toISOString() });
|
|
286
|
+
}
|
|
287
|
+
// All done
|
|
288
|
+
await db.roleApplication.update({
|
|
289
|
+
where: { id: applicationId },
|
|
290
|
+
data: { status: 'completed', completedAt: new Date() },
|
|
291
|
+
});
|
|
292
|
+
}
|
|
293
|
+
catch (err) {
|
|
294
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
295
|
+
await db.roleApplication.update({
|
|
296
|
+
where: { id: applicationId },
|
|
297
|
+
data: { status: 'failed', error: message, completedAt: new Date() },
|
|
298
|
+
});
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
// ─── Remove Role ───
|
|
302
|
+
export async function removeRole(applicationId) {
|
|
303
|
+
const db = getDb();
|
|
304
|
+
const application = await db.roleApplication.findUnique({
|
|
305
|
+
where: { id: applicationId },
|
|
306
|
+
include: { role: true, node: true },
|
|
307
|
+
});
|
|
308
|
+
if (!application)
|
|
309
|
+
throw new Error('RoleApplication not found');
|
|
310
|
+
const { role, node } = application;
|
|
311
|
+
const ctx = {
|
|
312
|
+
applicationId,
|
|
313
|
+
nodeId: node.id,
|
|
314
|
+
roleId: role.id,
|
|
315
|
+
nodeBaseUrl: getNodeBaseUrl(node.ipAddress, node.port),
|
|
316
|
+
nodeToken: getNodeManagerSecret(),
|
|
317
|
+
};
|
|
318
|
+
const steps = [
|
|
319
|
+
{ name: 'stop-services', status: 'pending' },
|
|
320
|
+
{ name: 'remove-docker', status: role.dockerEnabled ? 'pending' : 'skipped' },
|
|
321
|
+
{ name: 'remove-files', status: 'pending' },
|
|
322
|
+
{ name: 'remove-skills', status: JSON.parse(role.skillNames).length > 0 ? 'pending' : 'skipped' },
|
|
323
|
+
{ name: 'reset-firewall', status: role.firewallEnabled ? 'pending' : 'skipped' },
|
|
324
|
+
{ name: 'cleanup', status: 'pending' },
|
|
325
|
+
];
|
|
326
|
+
await db.roleApplication.update({
|
|
327
|
+
where: { id: applicationId },
|
|
328
|
+
data: { status: 'running', startedAt: new Date(), steps: JSON.stringify(steps) },
|
|
329
|
+
});
|
|
330
|
+
try {
|
|
331
|
+
// 1. Stop Orchestra / services
|
|
332
|
+
await updateStep(applicationId, 'stop-services', { status: 'running', startedAt: new Date().toISOString() });
|
|
333
|
+
if (role.dockerEnabled) {
|
|
334
|
+
const containerName = `magnus-role-${role.name}`;
|
|
335
|
+
await dispatchAndWait(ctx, 'bash', ['-c', `docker stop ${containerName} 2>/dev/null; docker rm ${containerName} 2>/dev/null; true`], 60);
|
|
336
|
+
}
|
|
337
|
+
// Try to stop Orchestra process if running outside Docker
|
|
338
|
+
await dispatchAndWait(ctx, 'bash', ['-c', 'pkill -f magnus-agent 2>/dev/null; true'], 30);
|
|
339
|
+
await updateStep(applicationId, 'stop-services', { status: 'completed', completedAt: new Date().toISOString() });
|
|
340
|
+
// 2. Remove Docker artifacts
|
|
341
|
+
if (role.dockerEnabled) {
|
|
342
|
+
await updateStep(applicationId, 'remove-docker', { status: 'running', startedAt: new Date().toISOString() });
|
|
343
|
+
const containerName = `magnus-role-${role.name}`;
|
|
344
|
+
await dispatchAndWait(ctx, 'bash', ['-c', `docker rmi ${containerName} 2>/dev/null; true`], 60);
|
|
345
|
+
await updateStep(applicationId, 'remove-docker', { status: 'completed', completedAt: new Date().toISOString() });
|
|
346
|
+
}
|
|
347
|
+
// 3. Remove deployed files
|
|
348
|
+
await updateStep(applicationId, 'remove-files', { status: 'running', startedAt: new Date().toISOString() });
|
|
349
|
+
await dispatchAndWait(ctx, 'rm', ['-rf', `/opt/magnus/roles/${role.name}`], 30);
|
|
350
|
+
await updateStep(applicationId, 'remove-files', { status: 'completed', completedAt: new Date().toISOString() });
|
|
351
|
+
// 4. Remove skills
|
|
352
|
+
const skillNames = JSON.parse(role.skillNames);
|
|
353
|
+
if (skillNames.length > 0) {
|
|
354
|
+
await updateStep(applicationId, 'remove-skills', { status: 'running', startedAt: new Date().toISOString() });
|
|
355
|
+
for (const skillName of skillNames) {
|
|
356
|
+
await db.skillInstallation.deleteMany({
|
|
357
|
+
where: { skillName, nodeId: ctx.nodeId },
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
await updateStep(applicationId, 'remove-skills', { status: 'completed', completedAt: new Date().toISOString() });
|
|
361
|
+
}
|
|
362
|
+
// 5. Reset firewall
|
|
363
|
+
if (role.firewallEnabled) {
|
|
364
|
+
await updateStep(applicationId, 'reset-firewall', { status: 'running', startedAt: new Date().toISOString() });
|
|
365
|
+
await dispatchAndWait(ctx, 'bash', ['-c', 'ufw --force reset && ufw --force disable'], 60);
|
|
366
|
+
await updateStep(applicationId, 'reset-firewall', { status: 'completed', completedAt: new Date().toISOString() });
|
|
367
|
+
}
|
|
368
|
+
// 6. Cleanup — clear roleId from node
|
|
369
|
+
await updateStep(applicationId, 'cleanup', { status: 'running', startedAt: new Date().toISOString() });
|
|
370
|
+
await db.node.update({
|
|
371
|
+
where: { id: ctx.nodeId },
|
|
372
|
+
data: { roleId: null },
|
|
373
|
+
});
|
|
374
|
+
await updateStep(applicationId, 'cleanup', { status: 'completed', completedAt: new Date().toISOString() });
|
|
375
|
+
await db.roleApplication.update({
|
|
376
|
+
where: { id: applicationId },
|
|
377
|
+
data: { status: 'completed', completedAt: new Date() },
|
|
378
|
+
});
|
|
379
|
+
}
|
|
380
|
+
catch (err) {
|
|
381
|
+
const message = err instanceof Error ? err.message : String(err);
|
|
382
|
+
await db.roleApplication.update({
|
|
383
|
+
where: { id: applicationId },
|
|
384
|
+
data: { status: 'failed', error: message, completedAt: new Date() },
|
|
385
|
+
});
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
//# sourceMappingURL=role-service.js.map
|