@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,361 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* auth.ts — Control API authentication middleware.
|
|
3
|
+
*
|
|
4
|
+
* When IAM_CORE_URL is configured, access tokens are RS256 JWTs issued by the
|
|
5
|
+
* external Hive IAM service. Magnus verifies those tokens; IAM administration
|
|
6
|
+
* happens in Hive IAM itself.
|
|
7
|
+
*
|
|
8
|
+
* If IAM_CORE_URL is not set, local Magnus HS256/API-secret auth remains active.
|
|
9
|
+
*/
|
|
10
|
+
import { createHash } from 'node:crypto';
|
|
11
|
+
import * as jose from 'jose';
|
|
12
|
+
import { HttpError } from './error-handler.js';
|
|
13
|
+
import { JWT_SECRET as jwtSecretRaw, API_SECRET as configuredApiSecret, IAM_CORE_URL, IAM_TOKEN_AUDIENCE, IAM_TOKEN_ISSUER, MAGNUS_COLLECTOR_TOKEN_SHA256, MAGNUS_PLUGIN_API_ENABLED, MAGNUS_PLUGIN_READ_TOKEN_DIGESTS_JSON, MAGNUS_PLUGIN_OPERATOR_TOKEN_SHA256, MAGNUS_APPROVAL_BRIDGE_CONSUMER, MAGNUS_SHARED_RESOURCE_TOKEN_SHA256, MAGNUS_SHARED_RESOURCE_TOKEN_DIGESTS_JSON, MAGNUS_FLEET_CHECK_TOKEN_SHA256, } from '../utils/env.js';
|
|
14
|
+
import { verifyWithRotation } from '../services/credential-rotation-service.js';
|
|
15
|
+
import { verifyIamAccessToken } from './iam-token.js';
|
|
16
|
+
import { getCurrentUserStatus } from './user-status.js';
|
|
17
|
+
import { safeEqual } from '../utils/safe-equal.js';
|
|
18
|
+
/** Constant-time string comparison (re-exported for existing callers). */
|
|
19
|
+
export { safeEqual };
|
|
20
|
+
let cachedPublicKey = null;
|
|
21
|
+
let publicKeyCachedAt = 0;
|
|
22
|
+
let lastForcedRefreshAt = 0;
|
|
23
|
+
let publicKeyFetch = null;
|
|
24
|
+
const PUBLIC_KEY_TTL_MS = 60 * 60 * 1_000; // 1 hour
|
|
25
|
+
// A forged or expired token must not turn every request into an IAM fetch.
|
|
26
|
+
const FORCED_REFRESH_MIN_INTERVAL_MS = 60 * 1_000;
|
|
27
|
+
async function fetchIamPublicKey() {
|
|
28
|
+
const url = `${IAM_CORE_URL}/api/v1/auth/public-key`;
|
|
29
|
+
const res = await fetch(url);
|
|
30
|
+
if (!res.ok) {
|
|
31
|
+
throw new Error(`Failed to fetch IAM public key: ${res.status}`);
|
|
32
|
+
}
|
|
33
|
+
const { publicKey: pem } = await res.json();
|
|
34
|
+
const key = await jose.importSPKI(pem, 'RS256');
|
|
35
|
+
cachedPublicKey = key;
|
|
36
|
+
publicKeyCachedAt = Date.now();
|
|
37
|
+
return key;
|
|
38
|
+
}
|
|
39
|
+
async function getIamPublicKey(forceRefresh = false) {
|
|
40
|
+
const now = Date.now();
|
|
41
|
+
if (cachedPublicKey) {
|
|
42
|
+
if (!forceRefresh && now - publicKeyCachedAt < PUBLIC_KEY_TTL_MS)
|
|
43
|
+
return cachedPublicKey;
|
|
44
|
+
// Rotation refresh is rate-limited; within the window the cached key stays authoritative.
|
|
45
|
+
if (forceRefresh && now - lastForcedRefreshAt < FORCED_REFRESH_MIN_INTERVAL_MS)
|
|
46
|
+
return cachedPublicKey;
|
|
47
|
+
}
|
|
48
|
+
if (forceRefresh)
|
|
49
|
+
lastForcedRefreshAt = now;
|
|
50
|
+
// Concurrent callers share one in-flight fetch.
|
|
51
|
+
publicKeyFetch ??= fetchIamPublicKey().finally(() => { publicKeyFetch = null; });
|
|
52
|
+
return publicKeyFetch;
|
|
53
|
+
}
|
|
54
|
+
// ──────────────────────────────────────────────────────────
|
|
55
|
+
// Role mapping: Hive IAM roles → Magnus UserRole
|
|
56
|
+
// ──────────────────────────────────────────────────────────
|
|
57
|
+
const IAM_ROLE_MAP = {
|
|
58
|
+
SUPER_ADMIN: 'ADMIN',
|
|
59
|
+
IAM_ADMIN: 'ADMIN',
|
|
60
|
+
OPERATOR: 'OPERATOR',
|
|
61
|
+
VIEWER: 'VIEWER',
|
|
62
|
+
SERVICE: 'OPERATOR',
|
|
63
|
+
DEPLOY_AGENT: 'OPERATOR',
|
|
64
|
+
};
|
|
65
|
+
function mapIamRoles(roles) {
|
|
66
|
+
for (const r of roles) {
|
|
67
|
+
const mapped = IAM_ROLE_MAP[r];
|
|
68
|
+
if (mapped)
|
|
69
|
+
return mapped;
|
|
70
|
+
}
|
|
71
|
+
return 'VIEWER';
|
|
72
|
+
}
|
|
73
|
+
// ──────────────────────────────────────────────────────────
|
|
74
|
+
// HS256 legacy key (non-IAM mode)
|
|
75
|
+
// ──────────────────────────────────────────────────────────
|
|
76
|
+
const JWT_SECRET_KEY = jwtSecretRaw
|
|
77
|
+
? new TextEncoder().encode(jwtSecretRaw)
|
|
78
|
+
: null;
|
|
79
|
+
function matchesBearerDigest(token, expectedDigest) {
|
|
80
|
+
return Boolean(expectedDigest) && safeEqual(createHash('sha256').update(token).digest('hex'), expectedDigest);
|
|
81
|
+
}
|
|
82
|
+
export function isScopedServiceRequestAllowed(service, method, path) {
|
|
83
|
+
const pluginExactReads = new Set([
|
|
84
|
+
'/api/v1/stats/overview', '/api/v1/fleet-checks/latest', '/api/v1/fleet-checks/runs',
|
|
85
|
+
'/api/v1/nodes', '/api/v1/nodes/wazuh/summary', '/api/v1/nodes/system-updates/summary',
|
|
86
|
+
'/api/v1/nodes/tailscale/summary',
|
|
87
|
+
'/api/v1/hermes/installations', '/api/v1/anomalies/summary', '/api/v1/anomalies',
|
|
88
|
+
'/api/v1/anomalies/correlations', '/api/v1/anomalies/timeline', '/api/v1/commands',
|
|
89
|
+
'/api/v1/cron', '/api/v1/dependencies', '/api/v1/ops/readiness', '/api/v1/ops/dependency-health',
|
|
90
|
+
'/api/v1/ops/timeline', '/api/v1/ops/incident-summary', '/api/v1/ops/hermes-effective-state',
|
|
91
|
+
'/api/v1/ops/package-security-posture', '/api/v1/alerts/violations', '/api/v1/audit',
|
|
92
|
+
'/api/v1/ops/codex-fleet-status',
|
|
93
|
+
'/api/v1/predictions', '/api/v1/skills', '/api/v1/security-fusion/overview',
|
|
94
|
+
'/api/v1/security-fusion/cases', '/api/v1/security-fusion/events',
|
|
95
|
+
'/api/v1/security-fusion/evidence',
|
|
96
|
+
]);
|
|
97
|
+
const pluginDynamicRead = [
|
|
98
|
+
/^\/api\/v1\/hermes\/installations\/[^/]+$/,
|
|
99
|
+
/^\/api\/v1\/commands\/[^/]+(?:\/result)?$/,
|
|
100
|
+
/^\/api\/v1\/predictions\/[^/]+$/,
|
|
101
|
+
/^\/api\/v1\/security-fusion\/cases\/[^/]+$/,
|
|
102
|
+
/^\/api\/v1\/security-fusion\/entities\/[^/]+$/,
|
|
103
|
+
/^\/api\/v1\/nodes\/(?!tags$|compare$|scan-users$|register$|wazuh$|system-updates$)[^/]+(?:\/health(?:\/history)?)?$/,
|
|
104
|
+
].some((pattern) => pattern.test(path));
|
|
105
|
+
const pluginWrites = new Set([
|
|
106
|
+
'/api/v1/commands', '/api/v1/logs/query', '/api/v1/ops/remediation-plan/classify',
|
|
107
|
+
'/api/v1/ops/engineering/dependency-impact', '/api/v1/ops/engineering/runbook-assessment',
|
|
108
|
+
'/api/v1/ops/engineering/delivery-assessment', '/api/v1/ops/engineering/forecast-assessment',
|
|
109
|
+
'/api/v1/ops/engineering/restore-assessment',
|
|
110
|
+
]);
|
|
111
|
+
const pluginDynamicWrite = /^\/api\/v1\/security-fusion\/cases\/[^/]+\/investigations$/.test(path);
|
|
112
|
+
if (service === 'plugin-read')
|
|
113
|
+
return method === 'GET' && (pluginExactReads.has(path) || pluginDynamicRead);
|
|
114
|
+
if (service === 'plugin-operator') {
|
|
115
|
+
return (method === 'POST' && (pluginWrites.has(path) || pluginDynamicWrite))
|
|
116
|
+
|| (method === 'GET' && path === '/api/v1/ops/engineering/catalog');
|
|
117
|
+
}
|
|
118
|
+
if (service === 'shared-resource') {
|
|
119
|
+
return (method === 'GET' && (/^\/api\/v1\/shared-resource-leases\/[A-Za-z0-9_-]{16,64}$/.test(path)
|
|
120
|
+
|| /^\/api\/v1\/shared-resource-leases\/operation\/[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(path)))
|
|
121
|
+
|| (method === 'POST' && (path === '/api/v1/shared-resource-leases/reserve'
|
|
122
|
+
|| /^\/api\/v1\/shared-resource-leases\/[A-Za-z0-9_-]{16,64}\/(?:start|unknown|settle)$/.test(path)));
|
|
123
|
+
}
|
|
124
|
+
return method === 'GET' && new Set([
|
|
125
|
+
'/api/v1/stats/overview', '/api/v1/nodes', '/api/v1/anomalies', '/api/v1/anomalies/summary',
|
|
126
|
+
]).has(path);
|
|
127
|
+
}
|
|
128
|
+
function assertScopedServiceRequest(c, service) {
|
|
129
|
+
const allowed = isScopedServiceRequestAllowed(service, c.req.method, c.req.path);
|
|
130
|
+
if (!allowed) {
|
|
131
|
+
throw new HttpError(403, 'FORBIDDEN', `${service} credential is endpoint-scoped`);
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
function matchingPluginReadConsumer(token) {
|
|
135
|
+
let registry;
|
|
136
|
+
try {
|
|
137
|
+
registry = JSON.parse(MAGNUS_PLUGIN_READ_TOKEN_DIGESTS_JSON);
|
|
138
|
+
}
|
|
139
|
+
catch {
|
|
140
|
+
return null;
|
|
141
|
+
}
|
|
142
|
+
const digest = createHash('sha256').update(token).digest('hex');
|
|
143
|
+
for (const [consumer, expected] of Object.entries(registry)) {
|
|
144
|
+
if (typeof expected === 'string' && matchesBearerDigest(token, expected) && safeEqual(digest, expected)) {
|
|
145
|
+
return consumer;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
function matchingSharedResourceConsumer(token) {
|
|
151
|
+
let registry;
|
|
152
|
+
try {
|
|
153
|
+
registry = JSON.parse(MAGNUS_SHARED_RESOURCE_TOKEN_DIGESTS_JSON);
|
|
154
|
+
}
|
|
155
|
+
catch {
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
const digest = createHash('sha256').update(token).digest('hex');
|
|
159
|
+
for (const [consumer, expected] of Object.entries(registry)) {
|
|
160
|
+
if (/^[A-Za-z0-9][A-Za-z0-9._:-]{0,95}$/.test(consumer) && typeof expected === 'string'
|
|
161
|
+
&& matchesBearerDigest(token, expected) && safeEqual(digest, expected))
|
|
162
|
+
return consumer;
|
|
163
|
+
}
|
|
164
|
+
return null;
|
|
165
|
+
}
|
|
166
|
+
// ──────────────────────────────────────────────────────────
|
|
167
|
+
// Core auth middleware
|
|
168
|
+
// ──────────────────────────────────────────────────────────
|
|
169
|
+
/** Verify token and attach AuthTokenPayload to context. */
|
|
170
|
+
export async function authMiddleware(c, next) {
|
|
171
|
+
// API-secret bypass (system calls from the dashboard, etc.)
|
|
172
|
+
// When IAM Core is configured, this is a bootstrap-only fallback.
|
|
173
|
+
const apiSecret = c.req.header('x-api-secret');
|
|
174
|
+
if (apiSecret && configuredApiSecret && verifyWithRotation('API_SECRET', configuredApiSecret, apiSecret)) {
|
|
175
|
+
if (IAM_CORE_URL) {
|
|
176
|
+
console.warn(`[auth] API_SECRET bypass used while IAM is active — path: ${new URL(c.req.url).pathname} (should migrate to IAM tokens)`);
|
|
177
|
+
}
|
|
178
|
+
c.set('user', {
|
|
179
|
+
userId: 'system',
|
|
180
|
+
email: 'system@magnus.local',
|
|
181
|
+
role: 'ADMIN',
|
|
182
|
+
iat: Math.floor(Date.now() / 1000),
|
|
183
|
+
exp: Math.floor(Date.now() / 1000) + 3600,
|
|
184
|
+
});
|
|
185
|
+
await next();
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
const header = c.req.header('Authorization');
|
|
189
|
+
if (!header?.startsWith('Bearer ')) {
|
|
190
|
+
throw new HttpError(401, 'UNAUTHORIZED', 'Missing or malformed Authorization header');
|
|
191
|
+
}
|
|
192
|
+
const token = header.slice(7);
|
|
193
|
+
// Hermes plugin credentials are honoured only when the plugin API is enabled.
|
|
194
|
+
const pluginReadConsumer = MAGNUS_PLUGIN_API_ENABLED ? matchingPluginReadConsumer(token) : null;
|
|
195
|
+
if (pluginReadConsumer) {
|
|
196
|
+
const approvalBridge = Boolean(MAGNUS_APPROVAL_BRIDGE_CONSUMER) && pluginReadConsumer === MAGNUS_APPROVAL_BRIDGE_CONSUMER && ((c.req.method === 'GET' && /^\/api\/v1\/team-approvals\/plans(?:\/[^/]+)?$/.test(c.req.path))
|
|
197
|
+
|| (c.req.method === 'POST' && c.req.path === '/api/v1/team-approvals/decisions'));
|
|
198
|
+
// Decision POST additionally requires a signed approval assertion; this
|
|
199
|
+
// never grants general operator writes to a read-only plugin credential.
|
|
200
|
+
if (!approvalBridge)
|
|
201
|
+
assertScopedServiceRequest(c, 'plugin-read');
|
|
202
|
+
c.set('user', {
|
|
203
|
+
userId: `service:magnus-plugin-read:${pluginReadConsumer}`, email: '', role: 'VIEWER',
|
|
204
|
+
iat: Math.floor(Date.now() / 1000), exp: Math.floor(Date.now() / 1000) + 300,
|
|
205
|
+
});
|
|
206
|
+
await next();
|
|
207
|
+
return;
|
|
208
|
+
}
|
|
209
|
+
if (MAGNUS_PLUGIN_API_ENABLED && matchesBearerDigest(token, MAGNUS_PLUGIN_OPERATOR_TOKEN_SHA256)) {
|
|
210
|
+
assertScopedServiceRequest(c, 'plugin-operator');
|
|
211
|
+
c.set('user', {
|
|
212
|
+
userId: 'service:magnus-plugin-operator', email: '', role: 'OPERATOR',
|
|
213
|
+
iat: Math.floor(Date.now() / 1000), exp: Math.floor(Date.now() / 1000) + 300,
|
|
214
|
+
});
|
|
215
|
+
await next();
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
const sharedResourceConsumer = matchingSharedResourceConsumer(token);
|
|
219
|
+
if (sharedResourceConsumer || matchesBearerDigest(token, MAGNUS_SHARED_RESOURCE_TOKEN_SHA256)) {
|
|
220
|
+
assertScopedServiceRequest(c, 'shared-resource');
|
|
221
|
+
c.set('user', {
|
|
222
|
+
userId: sharedResourceConsumer ? `service:shared-resource:${sharedResourceConsumer}` : 'service:shared-resource-client',
|
|
223
|
+
email: '', role: 'OPERATOR',
|
|
224
|
+
iat: Math.floor(Date.now() / 1000), exp: Math.floor(Date.now() / 1000) + 300,
|
|
225
|
+
});
|
|
226
|
+
await next();
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
if (matchesBearerDigest(token, MAGNUS_FLEET_CHECK_TOKEN_SHA256)) {
|
|
230
|
+
assertScopedServiceRequest(c, 'fleet');
|
|
231
|
+
c.set('user', {
|
|
232
|
+
userId: 'service:magnus-fleet-check', email: '', role: 'VIEWER',
|
|
233
|
+
iat: Math.floor(Date.now() / 1000), exp: Math.floor(Date.now() / 1000) + 300,
|
|
234
|
+
});
|
|
235
|
+
await next();
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
// An optional external observability collector has a dedicated read-only
|
|
239
|
+
// credential. Store only its digest and confine it to the collector endpoints.
|
|
240
|
+
if (MAGNUS_COLLECTOR_TOKEN_SHA256) {
|
|
241
|
+
const tokenDigest = createHash('sha256').update(token).digest('hex');
|
|
242
|
+
if (safeEqual(tokenDigest, MAGNUS_COLLECTOR_TOKEN_SHA256)) {
|
|
243
|
+
const allowed = c.req.method === 'GET' && new Set([
|
|
244
|
+
'/api/v1/nodes',
|
|
245
|
+
'/api/v1/hermes/installations',
|
|
246
|
+
'/api/v1/ops/observations',
|
|
247
|
+
'/api/v1/ops/capacity-advice',
|
|
248
|
+
]).has(c.req.path);
|
|
249
|
+
if (!allowed) {
|
|
250
|
+
throw new HttpError(403, 'FORBIDDEN', 'Collector credential is read-only and endpoint-scoped');
|
|
251
|
+
}
|
|
252
|
+
c.set('user', {
|
|
253
|
+
userId: 'service:observability-collector',
|
|
254
|
+
email: '',
|
|
255
|
+
role: 'VIEWER',
|
|
256
|
+
iat: Math.floor(Date.now() / 1000),
|
|
257
|
+
exp: Math.floor(Date.now() / 1000) + 300,
|
|
258
|
+
});
|
|
259
|
+
await next();
|
|
260
|
+
return;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
// ── External Hive IAM verification mode: RS256 ────────
|
|
264
|
+
if (IAM_CORE_URL) {
|
|
265
|
+
let payload;
|
|
266
|
+
try {
|
|
267
|
+
const key = await getIamPublicKey();
|
|
268
|
+
payload = await verifyIamAccessToken(token, key, IAM_TOKEN_ISSUER, IAM_TOKEN_AUDIENCE);
|
|
269
|
+
}
|
|
270
|
+
catch {
|
|
271
|
+
// Might be a key rotation — refresh once and retry
|
|
272
|
+
try {
|
|
273
|
+
const freshKey = await getIamPublicKey(true);
|
|
274
|
+
payload = await verifyIamAccessToken(token, freshKey, IAM_TOKEN_ISSUER, IAM_TOKEN_AUDIENCE);
|
|
275
|
+
}
|
|
276
|
+
catch {
|
|
277
|
+
throw new HttpError(401, 'UNAUTHORIZED', 'Invalid or expired IAM token');
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
const roles = payload['roles'] ?? [];
|
|
281
|
+
c.set('user', {
|
|
282
|
+
userId: payload.sub,
|
|
283
|
+
email: payload['email'] ?? '',
|
|
284
|
+
role: mapIamRoles(roles),
|
|
285
|
+
iat: payload.iat ?? 0,
|
|
286
|
+
exp: payload.exp ?? 0,
|
|
287
|
+
});
|
|
288
|
+
await next();
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
// ── Legacy HS256 mode ─────────────────────────────────
|
|
292
|
+
if (!JWT_SECRET_KEY) {
|
|
293
|
+
throw new HttpError(500, 'CONFIGURATION_ERROR', 'No JWT_SECRET or IAM_CORE_URL configured');
|
|
294
|
+
}
|
|
295
|
+
let claims;
|
|
296
|
+
try {
|
|
297
|
+
const { payload } = await jose.jwtVerify(token, JWT_SECRET_KEY);
|
|
298
|
+
claims = payload;
|
|
299
|
+
}
|
|
300
|
+
catch {
|
|
301
|
+
throw new HttpError(401, 'UNAUTHORIZED', 'Invalid or expired token');
|
|
302
|
+
}
|
|
303
|
+
// The signed role is only a snapshot: deactivated, deleted, or demoted users
|
|
304
|
+
// must not keep access until the token expires. The database role wins.
|
|
305
|
+
const current = typeof claims.userId === 'string' && claims.userId
|
|
306
|
+
? await getCurrentUserStatus(claims.userId)
|
|
307
|
+
: null;
|
|
308
|
+
if (!current?.active) {
|
|
309
|
+
throw new HttpError(401, 'UNAUTHORIZED', 'Invalid or expired token');
|
|
310
|
+
}
|
|
311
|
+
c.set('user', { ...claims, role: current.role });
|
|
312
|
+
await next();
|
|
313
|
+
}
|
|
314
|
+
/** Create a signed HS256 JWT (local Magnus mode only). */
|
|
315
|
+
export async function signUserToken(payload) {
|
|
316
|
+
if (!JWT_SECRET_KEY) {
|
|
317
|
+
throw new Error('signUserToken is not available in IAM Core mode');
|
|
318
|
+
}
|
|
319
|
+
const expiry = process.env['JWT_EXPIRY'] ?? '24h';
|
|
320
|
+
return new jose.SignJWT(payload)
|
|
321
|
+
.setProtectedHeader({ alg: 'HS256' })
|
|
322
|
+
.setIssuedAt()
|
|
323
|
+
.setExpirationTime(expiry)
|
|
324
|
+
.sign(JWT_SECRET_KEY);
|
|
325
|
+
}
|
|
326
|
+
/** Extract user from context (set by authMiddleware). */
|
|
327
|
+
export function getUser(c) {
|
|
328
|
+
const user = c.var.user;
|
|
329
|
+
// Runtime guard — user is always set by authMiddleware before this is called
|
|
330
|
+
if (!user)
|
|
331
|
+
throw new HttpError(401, 'UNAUTHORIZED', 'Not authenticated');
|
|
332
|
+
return user;
|
|
333
|
+
}
|
|
334
|
+
/** Check that the authenticated user has one of the required roles. */
|
|
335
|
+
export function requireRole(...roles) {
|
|
336
|
+
return async (c, next) => {
|
|
337
|
+
const user = getUser(c);
|
|
338
|
+
if (!roles.includes(user.role)) {
|
|
339
|
+
throw new HttpError(403, 'FORBIDDEN', `Requires one of: ${roles.join(', ')}`);
|
|
340
|
+
}
|
|
341
|
+
await next();
|
|
342
|
+
};
|
|
343
|
+
}
|
|
344
|
+
const ROLE_PERMISSIONS = {
|
|
345
|
+
ADMIN: new Set(['security-fusion:read', 'security-fusion:evidence:read']),
|
|
346
|
+
OPERATOR: new Set(['security-fusion:read']),
|
|
347
|
+
VIEWER: new Set(['security-fusion:read']),
|
|
348
|
+
};
|
|
349
|
+
export function hasPermission(user, permission) {
|
|
350
|
+
return ROLE_PERMISSIONS[user.role]?.has(permission) ?? false;
|
|
351
|
+
}
|
|
352
|
+
/** Require an explicit permission rather than treating any dashboard session as access. */
|
|
353
|
+
export function requirePermission(permission) {
|
|
354
|
+
return async (c, next) => {
|
|
355
|
+
if (!hasPermission(getUser(c), permission)) {
|
|
356
|
+
throw new HttpError(403, 'FORBIDDEN', `Requires permission: ${permission}`);
|
|
357
|
+
}
|
|
358
|
+
await next();
|
|
359
|
+
};
|
|
360
|
+
}
|
|
361
|
+
//# sourceMappingURL=auth.js.map
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import { bodyLimit } from 'hono/body-limit';
|
|
2
|
+
export function bodyLimitMiddleware(limitBytes) {
|
|
3
|
+
return bodyLimit({
|
|
4
|
+
maxSize: limitBytes,
|
|
5
|
+
onError: (c) => c.json({
|
|
6
|
+
success: false,
|
|
7
|
+
error: {
|
|
8
|
+
code: 'PAYLOAD_TOO_LARGE',
|
|
9
|
+
message: `Request body exceeds ${limitBytes} bytes`,
|
|
10
|
+
},
|
|
11
|
+
}, 413),
|
|
12
|
+
});
|
|
13
|
+
}
|
|
14
|
+
//# sourceMappingURL=body-limit.js.map
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import { nanoid } from 'nanoid';
|
|
2
|
+
/**
|
|
3
|
+
* Correlation ID middleware — adds `x-request-id` header to every request/response.
|
|
4
|
+
* If the client sends `x-request-id`, it is reused; otherwise a new one is generated.
|
|
5
|
+
* The ID is stored in `c.var.requestId` for downstream use.
|
|
6
|
+
*/
|
|
7
|
+
export const correlationId = async (c, next) => {
|
|
8
|
+
const id = c.req.header('x-request-id') ?? nanoid();
|
|
9
|
+
c.set('requestId', id);
|
|
10
|
+
c.header('x-request-id', id);
|
|
11
|
+
await next();
|
|
12
|
+
};
|
|
13
|
+
//# sourceMappingURL=correlation-id.js.map
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { redactSecretText } from '../utils/redact.js';
|
|
2
|
+
/** Global error handler for Hono — returns structured ApiError JSON. */
|
|
3
|
+
export function errorHandler(err, c) {
|
|
4
|
+
const status = 'status' in err ? err.status : 500;
|
|
5
|
+
const code = 'code' in err ? err.code : 'INTERNAL_ERROR';
|
|
6
|
+
// Log only the error message and code — never the full error object,
|
|
7
|
+
// which may contain request bodies, tokens, or other secrets.
|
|
8
|
+
console.error(`[ERROR] ${c.req.method} ${c.req.url} [${code}] ${redactSecretText(err.message)}`);
|
|
9
|
+
const body = {
|
|
10
|
+
success: false,
|
|
11
|
+
error: {
|
|
12
|
+
code: String(code),
|
|
13
|
+
message: redactSecretText(err.message || 'An unexpected error occurred'),
|
|
14
|
+
},
|
|
15
|
+
};
|
|
16
|
+
return c.json(body, status);
|
|
17
|
+
}
|
|
18
|
+
/** Throw an HTTP error with a code. */
|
|
19
|
+
export class HttpError extends Error {
|
|
20
|
+
status;
|
|
21
|
+
code;
|
|
22
|
+
constructor(status, code, message) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.status = status;
|
|
25
|
+
this.code = code;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
//# sourceMappingURL=error-handler.js.map
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import * as jose from 'jose';
|
|
2
|
+
/**
|
|
3
|
+
* Verify the complete Hive IAM access-token contract. Signature-only checks
|
|
4
|
+
* are insufficient because a valid token minted for another service must not
|
|
5
|
+
* be replayable against Magnus.
|
|
6
|
+
*/
|
|
7
|
+
export async function verifyIamAccessToken(token, key, issuer, audience) {
|
|
8
|
+
if (!issuer || !audience) {
|
|
9
|
+
throw new Error('IAM token issuer and audience must be configured');
|
|
10
|
+
}
|
|
11
|
+
const { payload } = await jose.jwtVerify(token, key, {
|
|
12
|
+
algorithms: ['RS256'],
|
|
13
|
+
issuer,
|
|
14
|
+
audience,
|
|
15
|
+
});
|
|
16
|
+
if (typeof payload.sub !== 'string' || payload.sub.length === 0) {
|
|
17
|
+
throw new Error('IAM access token is missing subject');
|
|
18
|
+
}
|
|
19
|
+
return payload;
|
|
20
|
+
}
|
|
21
|
+
//# sourceMappingURL=iam-token.js.map
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { Redis } from 'ioredis';
|
|
2
|
+
import { incMetric } from '../routes/metrics.js';
|
|
3
|
+
import { heartbeatPeerAddress } from '../utils/heartbeat-peer.js';
|
|
4
|
+
const REDIS_URL = process.env['REDIS_URL'] ?? 'redis://127.0.0.1:6379';
|
|
5
|
+
const REDIS_PREFIX = process.env['REDIS_PREFIX'] ?? 'magnus-';
|
|
6
|
+
let _redis = null;
|
|
7
|
+
let lastRateLimitError = null;
|
|
8
|
+
let lastRateLimitErrorAt = null;
|
|
9
|
+
function getRedis() {
|
|
10
|
+
if (!_redis) {
|
|
11
|
+
_redis = new Redis(REDIS_URL, { maxRetriesPerRequest: 3, lazyConnect: true });
|
|
12
|
+
_redis.connect().catch(() => {
|
|
13
|
+
// silently fail — rate limiter becomes permissive when Redis is unavailable
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
return _redis;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Sliding-window rate limiter backed by Redis.
|
|
20
|
+
* Keyed by client IP address. Falls through (allows) if Redis is unavailable.
|
|
21
|
+
*
|
|
22
|
+
* @param opts.windowMs Time window in milliseconds (default: 60_000 = 1 minute)
|
|
23
|
+
* @param opts.max Maximum requests per window (default: 100)
|
|
24
|
+
* @param opts.keyPrefix Redis key prefix segment (default: 'rl')
|
|
25
|
+
*/
|
|
26
|
+
export function rateLimitMiddleware(opts = {}) {
|
|
27
|
+
const windowMs = opts.windowMs ?? 60_000;
|
|
28
|
+
const max = opts.max ?? 100;
|
|
29
|
+
const prefix = opts.keyPrefix ?? 'rl';
|
|
30
|
+
return async (c, next) => {
|
|
31
|
+
// Port 4000 is directly reachable by fleet peers. A caller-controlled
|
|
32
|
+
// forwarding header must not let login or mutation clients rotate their
|
|
33
|
+
// rate-limit identity. The helper prefers the Node socket peer and only
|
|
34
|
+
// falls back to forwarded metadata in adapter-free/test contexts.
|
|
35
|
+
const ip = heartbeatPeerAddress(c) || 'unknown-peer';
|
|
36
|
+
const key = `${REDIS_PREFIX}${prefix}:${ip}`;
|
|
37
|
+
const now = Date.now();
|
|
38
|
+
const windowStart = now - windowMs;
|
|
39
|
+
try {
|
|
40
|
+
const redis = getRedis();
|
|
41
|
+
const pipe = redis.pipeline();
|
|
42
|
+
pipe.zremrangebyscore(key, '-inf', windowStart);
|
|
43
|
+
pipe.zadd(key, now, `${now}-${Math.random()}`);
|
|
44
|
+
pipe.zcard(key);
|
|
45
|
+
pipe.pexpire(key, windowMs);
|
|
46
|
+
const results = await pipe.exec();
|
|
47
|
+
// Recovery clears the health warning; lastErrorAt keeps the history.
|
|
48
|
+
lastRateLimitError = null;
|
|
49
|
+
const count = results?.[2]?.[1] ?? 0;
|
|
50
|
+
if (count > max) {
|
|
51
|
+
const retryAfter = Math.ceil(windowMs / 1000);
|
|
52
|
+
c.header('Retry-After', String(retryAfter));
|
|
53
|
+
return c.json({ error: 'RATE_LIMITED', message: 'Too many requests. Please try again later.' }, 429);
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
lastRateLimitError = 'Redis unavailable for rate limiting';
|
|
58
|
+
lastRateLimitErrorAt = new Date().toISOString();
|
|
59
|
+
incMetric('rateLimiterFailures');
|
|
60
|
+
if (opts.failClosed && process.env['NODE_ENV'] !== 'test') {
|
|
61
|
+
return c.json({
|
|
62
|
+
error: 'RATE_LIMIT_UNAVAILABLE',
|
|
63
|
+
message: 'Rate limiter is unavailable for this sensitive endpoint.',
|
|
64
|
+
}, 503);
|
|
65
|
+
}
|
|
66
|
+
// Redis unavailable — fail open only for non-critical routes and tests.
|
|
67
|
+
}
|
|
68
|
+
return next();
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
export function getRateLimitHealth() {
|
|
72
|
+
return {
|
|
73
|
+
status: lastRateLimitError ? 'warn' : 'pass',
|
|
74
|
+
message: lastRateLimitError ?? 'rate limiter available or not yet exercised',
|
|
75
|
+
lastErrorAt: lastRateLimitErrorAt,
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
//# sourceMappingURL=rate-limit.js.map
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
import { routePath } from 'hono/route';
|
|
2
|
+
import { getDb } from '../db/index.js';
|
|
3
|
+
import { emitLog } from '../services/log-emitter.js';
|
|
4
|
+
import { incMetric, observeLatency } from '../routes/metrics.js';
|
|
5
|
+
import { redactUnknown } from '../utils/redact.js';
|
|
6
|
+
// ─── Request Logger — logs Control API HTTP requests to logEntry table ───
|
|
7
|
+
import { CONTROL_API_NODE_ID } from '../utils/sentinel-nodes.js';
|
|
8
|
+
export { CONTROL_API_NODE_ID };
|
|
9
|
+
/** Paths to skip logging (noisy or recursive endpoints). */
|
|
10
|
+
const SKIP_PATHS = new Set([
|
|
11
|
+
'/api/v1/health',
|
|
12
|
+
'/api/v1/heartbeat',
|
|
13
|
+
'/api/v1/logs/stream',
|
|
14
|
+
]);
|
|
15
|
+
/** Map HTTP status code ranges to log levels. */
|
|
16
|
+
function statusToLevel(status) {
|
|
17
|
+
if (status >= 500)
|
|
18
|
+
return 'error';
|
|
19
|
+
if (status >= 400)
|
|
20
|
+
return 'warn';
|
|
21
|
+
return 'info';
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Hono middleware that logs each HTTP request to the logEntry table
|
|
25
|
+
* after the response is sent. Also emits to the SSE log bus.
|
|
26
|
+
*
|
|
27
|
+
* Security: Only logs method, path, status, duration, and user email.
|
|
28
|
+
* Never logs request or response bodies.
|
|
29
|
+
*/
|
|
30
|
+
export async function requestLogger(c, next) {
|
|
31
|
+
const path = new URL(c.req.url).pathname;
|
|
32
|
+
// Skip noisy endpoints
|
|
33
|
+
if (SKIP_PATHS.has(path)) {
|
|
34
|
+
await next();
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
const start = Date.now();
|
|
38
|
+
await next();
|
|
39
|
+
const durationMs = Date.now() - start;
|
|
40
|
+
const method = c.req.method;
|
|
41
|
+
const status = c.res.status;
|
|
42
|
+
const level = statusToLevel(status);
|
|
43
|
+
// ── Prometheus counters ──
|
|
44
|
+
incMetric('httpRequestsTotal');
|
|
45
|
+
if (status >= 400)
|
|
46
|
+
incMetric('httpErrorsTotal');
|
|
47
|
+
// Key latency by the matched route pattern, never the raw path, so random
|
|
48
|
+
// (including unauthenticated 404) paths cannot grow the metric cardinality.
|
|
49
|
+
observeLatency(durationMs, routePath(c) || 'unmatched', status);
|
|
50
|
+
// Extract user email from auth context (set by authMiddleware)
|
|
51
|
+
let userEmail = 'anonymous';
|
|
52
|
+
const user = c.var.user;
|
|
53
|
+
if (user?.email)
|
|
54
|
+
userEmail = user.email;
|
|
55
|
+
const message = `${method} ${path} ${status} ${durationMs}ms`;
|
|
56
|
+
const traceId = c.get('traceId');
|
|
57
|
+
const metadata = redactUnknown({ method, path, status, durationMs, userEmail, traceId });
|
|
58
|
+
const now = new Date();
|
|
59
|
+
// Write to DB (fire-and-forget — don't block the response)
|
|
60
|
+
const db = getDb();
|
|
61
|
+
void db.logEntry.create({
|
|
62
|
+
data: {
|
|
63
|
+
nodeId: CONTROL_API_NODE_ID,
|
|
64
|
+
source: 'control-api',
|
|
65
|
+
level,
|
|
66
|
+
message,
|
|
67
|
+
metadata: JSON.stringify(metadata),
|
|
68
|
+
timestamp: now,
|
|
69
|
+
},
|
|
70
|
+
}).catch((err) => {
|
|
71
|
+
const msg = err instanceof Error ? err.message : 'Unknown error';
|
|
72
|
+
console.error(`Request logger write error: ${msg}`);
|
|
73
|
+
});
|
|
74
|
+
// Emit to SSE subscribers
|
|
75
|
+
emitLog({
|
|
76
|
+
id: '',
|
|
77
|
+
nodeId: CONTROL_API_NODE_ID,
|
|
78
|
+
source: 'control-api',
|
|
79
|
+
level,
|
|
80
|
+
message,
|
|
81
|
+
metadata,
|
|
82
|
+
timestamp: now,
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
//# sourceMappingURL=request-logger.js.map
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Security headers middleware.
|
|
3
|
+
* Applies OWASP-recommended HTTP response headers to all responses.
|
|
4
|
+
*/
|
|
5
|
+
export const securityHeaders = async (c, next) => {
|
|
6
|
+
await next();
|
|
7
|
+
// Prevent MIME type sniffing
|
|
8
|
+
c.header('X-Content-Type-Options', 'nosniff');
|
|
9
|
+
// Prevent click-jacking
|
|
10
|
+
c.header('X-Frame-Options', 'DENY');
|
|
11
|
+
// XSS protection (legacy browsers)
|
|
12
|
+
c.header('X-XSS-Protection', '1; mode=block');
|
|
13
|
+
// Strict transport security (1 year, include subdomains)
|
|
14
|
+
c.header('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
|
|
15
|
+
// No referrer leakage
|
|
16
|
+
c.header('Referrer-Policy', 'strict-origin-when-cross-origin');
|
|
17
|
+
// Restrict permissions
|
|
18
|
+
c.header('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
|
|
19
|
+
// Prevent caching of API responses with sensitive data
|
|
20
|
+
c.header('Cache-Control', 'no-store');
|
|
21
|
+
c.header('Pragma', 'no-cache');
|
|
22
|
+
};
|
|
23
|
+
//# sourceMappingURL=security-headers.js.map
|