diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
new file mode 100644
index 0000000..7ff45e1
--- /dev/null
+++ b/.github/workflows/ci.yml
@@ -0,0 +1,72 @@
+name: CI
+
+on:
+ push:
+ branches: [main, develop]
+ pull_request:
+ branches: [main]
+
+jobs:
+ build-and-test:
+ runs-on: ubuntu-latest
+
+ services:
+ postgres:
+ image: postgres:17-alpine
+ env:
+ POSTGRES_DB: heimdall_test
+ POSTGRES_USER: heimdall
+ POSTGRES_PASSWORD: heimdall
+ ports:
+ - 5432:5432
+ options: >-
+ --health-cmd pg_isready
+ --health-interval 10s
+ --health-timeout 5s
+ --health-retries 5
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Setup .NET
+ uses: actions/setup-dotnet@v4
+ with:
+ dotnet-version: "10.0.x"
+
+ - name: Restore
+ run: dotnet restore
+
+ - name: Build
+ run: dotnet build --no-restore -c Release
+
+ - name: Test
+ run: dotnet test --no-build -c Release
+ env:
+ DATABASE_URL: "Host=localhost;Port=5432;Database=heimdall_test;Username=heimdall;Password=heimdall"
+
+ docker-build:
+ needs: build-and-test
+ runs-on: ubuntu-latest
+ if: github.ref == 'refs/heads/main'
+
+ steps:
+ - uses: actions/checkout@v4
+
+ - name: Set up Docker Buildx
+ uses: docker/setup-buildx-action@v3
+
+ - name: Build Central image
+ uses: docker/build-push-action@v6
+ with:
+ context: .
+ file: docker/Dockerfile.central
+ push: false
+ tags: heimdall/central:latest
+
+ - name: Build Agent image
+ uses: docker/build-push-action@v6
+ with:
+ context: .
+ file: docker/Dockerfile.agent
+ push: false
+ tags: heimdall/agent:latest
diff --git a/Directory.Build.props b/Directory.Build.props
index b5c3a31..d1a9016 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -6,7 +6,7 @@
true
latest-Recommended
true
- $(NoWarn);NU1903;CA1848;CA1727
+ $(NoWarn);NU1903;CA1848;CA1727;CA1861;CA1825;CA1873
false
@@ -20,5 +20,6 @@
true
false
+ $(NoWarn);CA1707
diff --git a/docker/Dockerfile.agent b/docker/Dockerfile.agent
new file mode 100644
index 0000000..37509ab
--- /dev/null
+++ b/docker/Dockerfile.agent
@@ -0,0 +1,28 @@
+FROM mcr.microsoft.com/dotnet/sdk:10.0-alpine AS build
+WORKDIR /src
+
+COPY *.slnx .
+COPY Directory.Build.props .
+COPY src/Heimdall.Domain.Primitives/*.csproj src/Heimdall.Domain.Primitives/
+COPY src/Heimdall.Domain/*.csproj src/Heimdall.Domain/
+COPY src/Heimdall.Contracts/*.csproj src/Heimdall.Contracts/
+COPY src/Heimdall.Application/*.csproj src/Heimdall.Application/
+COPY src/Heimdall.Infrastructure/*.csproj src/Heimdall.Infrastructure/
+COPY src/Heimdall.Agent/*.csproj src/Heimdall.Agent/
+
+RUN dotnet restore src/Heimdall.Agent/Heimdall.Agent.csproj
+
+COPY src/ src/
+
+RUN dotnet publish src/Heimdall.Agent/Heimdall.Agent.csproj -c Release -o /app
+
+FROM mcr.microsoft.com/dotnet/aspnet:10.0-alpine AS runtime
+WORKDIR /app
+
+RUN apk add --no-cache icu-libs libstdc++ ffmpeg
+
+ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false
+
+COPY --from=build /app .
+
+ENTRYPOINT ["dotnet", "Heimdall.Agent.dll"]
diff --git a/docker/Dockerfile.central b/docker/Dockerfile.central
new file mode 100644
index 0000000..d946db2
--- /dev/null
+++ b/docker/Dockerfile.central
@@ -0,0 +1,42 @@
+FROM mcr.microsoft.com/dotnet/sdk:10.0-alpine AS build
+WORKDIR /src
+
+# Copy solution and project files
+COPY *.slnx .
+COPY Directory.Build.props .
+COPY src/Heimdall.Domain.Primitives/*.csproj src/Heimdall.Domain.Primitives/
+COPY src/Heimdall.Domain/*.csproj src/Heimdall.Domain/
+COPY src/Heimdall.Contracts/*.csproj src/Heimdall.Contracts/
+COPY src/Heimdall.Application/*.csproj src/Heimdall.Application/
+COPY src/Heimdall.Infrastructure/*.csproj src/Heimdall.Infrastructure/
+COPY src/Heimdall.Api/*.csproj src/Heimdall.Api/
+COPY src/Heimdall.Web/*.csproj src/Heimdall.Web/
+COPY src/Heimdall.Workers/*.csproj src/Heimdall.Workers/
+
+RUN dotnet restore src/Heimdall.Api/Heimdall.Api.csproj
+RUN dotnet restore src/Heimdall.Workers/Heimdall.Workers.csproj
+
+# Copy all source
+COPY src/ src/
+
+# Build and publish API+Web combined container
+RUN dotnet publish src/Heimdall.Api/Heimdall.Api.csproj -c Release -o /app/api
+RUN dotnet publish src/Heimdall.Web/Heimdall.Web.csproj -c Release -o /app/web
+RUN dotnet publish src/Heimdall.Workers/Heimdall.Workers.csproj -c Release -o /app/workers
+
+FROM mcr.microsoft.com/dotnet/aspnet:10.0-alpine AS runtime
+WORKDIR /app
+
+RUN apk add --no-cache icu-libs libstdc++
+
+ENV DOTNET_SYSTEM_GLOBALIZATION_INVARIANT=false \
+ ASPNETCORE_URLS=http://+:8080
+
+COPY --from=build /app/api ./api
+COPY --from=build /app/web ./web
+COPY --from=build /app/workers ./workers
+
+# Expose both API and Web ports
+EXPOSE 8080
+
+ENTRYPOINT ["dotnet", "api/Heimdall.Api.dll"]
diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml
new file mode 100644
index 0000000..c8c6888
--- /dev/null
+++ b/docker/docker-compose.yml
@@ -0,0 +1,62 @@
+services:
+ postgresql:
+ image: postgres:17-alpine
+ environment:
+ POSTGRES_DB: heimdall
+ POSTGRES_USER: heimdall
+ POSTGRES_PASSWORD: heimdall
+ ports:
+ - "5432:5432"
+ volumes:
+ - pgdata:/var/lib/postgresql/data
+ healthcheck:
+ test: ["CMD-SHELL", "pg_isready -U heimdall"]
+ interval: 10s
+ timeout: 5s
+ retries: 5
+
+ minio:
+ image: minio/minio:latest
+ command: server /data --console-address ":9001"
+ environment:
+ MINIO_ROOT_USER: heimdall
+ MINIO_ROOT_PASSWORD: heimdall123
+ ports:
+ - "9000:9000"
+ - "9001:9001"
+ volumes:
+ - minio_data:/data
+
+ heimdall-central:
+ build:
+ context: ..
+ dockerfile: docker/Dockerfile.central
+ environment:
+ DATABASE_URL: "Host=postgresql;Port=5432;Database=heimdall;Username=heimdall;Password=heimdall"
+ JWT__Key: "ThisIsADevelopmentKeyThatIsAtLeast32Bytes!"
+ JWT__Issuer: "heimdall"
+ JWT__Audience: "heimdall-api"
+ ASPNETCORE_ENVIRONMENT: Development
+ Cors__AllowedOrigins: "https://localhost:5001,http://localhost:5000"
+ ports:
+ - "5000:8080"
+ depends_on:
+ postgresql:
+ condition: service_healthy
+ restart: unless-stopped
+
+ heimdall-agent:
+ build:
+ context: ..
+ dockerfile: docker/Dockerfile.agent
+ environment:
+ HEIMDALL_CENTRAL_URL: "http://heimdall-central:8080"
+ HEIMDALL_SITE_TOKEN: "replace-with-actual-token"
+ HEIMDALL_AGENT_NAME: "agent-demo"
+ depends_on:
+ - heimdall-central
+ restart: unless-stopped
+
+volumes:
+ pgdata:
+ minio_data:
diff --git a/src/Heimdall.Agent/Program.cs b/src/Heimdall.Agent/Program.cs
index fa2ca3e..04b6bf2 100644
--- a/src/Heimdall.Agent/Program.cs
+++ b/src/Heimdall.Agent/Program.cs
@@ -1,7 +1,14 @@
-using Heimdall.Agent;
+using Heimdall.Agent.Services;
var builder = Host.CreateApplicationBuilder(args);
-builder.Services.AddHostedService();
+
+builder.Services.AddHttpClient("Central", client =>
+{
+ client.Timeout = TimeSpan.FromSeconds(10);
+});
+
+builder.Services.AddSingleton();
+builder.Services.AddHostedService();
var host = builder.Build();
host.Run();
diff --git a/src/Heimdall.Agent/Services/AgentRegistrationService.cs b/src/Heimdall.Agent/Services/AgentRegistrationService.cs
new file mode 100644
index 0000000..d94427c
--- /dev/null
+++ b/src/Heimdall.Agent/Services/AgentRegistrationService.cs
@@ -0,0 +1,111 @@
+using System.Net.Http.Json;
+using System.Text.Json.Serialization;
+using Microsoft.Extensions.Logging;
+
+namespace Heimdall.Agent.Services;
+
+///
+/// Registers this agent with the Heimdall Central server and manages the heartbeat loop.
+///
+public class AgentRegistrationService : BackgroundService
+{
+ private readonly IHttpClientFactory _httpClientFactory;
+ private readonly ILogger _logger;
+ private readonly AgentState _state;
+
+ public AgentRegistrationService(
+ IHttpClientFactory httpClientFactory,
+ AgentState state,
+ ILogger logger)
+ {
+ _httpClientFactory = httpClientFactory;
+ _state = state;
+ _logger = logger;
+ }
+
+ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
+ {
+ var centralUrl = Environment.GetEnvironmentVariable("HEIMDALL_CENTRAL_URL")
+ ?? throw new InvalidOperationException("HEIMDALL_CENTRAL_URL is not set");
+ var siteToken = Environment.GetEnvironmentVariable("HEIMDALL_SITE_TOKEN")
+ ?? throw new InvalidOperationException("HEIMDALL_SITE_TOKEN is not set");
+ var hostname = Environment.GetEnvironmentVariable("HEIMDALL_AGENT_NAME")
+ ?? System.Net.Dns.GetHostName();
+
+ // Step 1: Register
+ _logger.LogInformation("Registering agent with Central at {CentralUrl}", centralUrl);
+
+ var client = _httpClientFactory.CreateClient("Central");
+ client.BaseAddress = new Uri(centralUrl.TrimEnd('/') + "/");
+
+ try
+ {
+ var request = new RegisterRequest(siteToken, hostname, "1.0.0");
+ var response = await client.PostAsJsonAsync("api/agents/register", request, stoppingToken);
+ response.EnsureSuccessStatusCode();
+
+ var result = await response.Content.ReadFromJsonAsync(stoppingToken);
+ if (result is null)
+ throw new InvalidOperationException("Empty registration response");
+
+ _state.AgentId = result.AgentId;
+ _state.ApiKey = result.ApiKey;
+ _state.ApiKeyPrefix = result.ApiKeyPrefix;
+
+ _logger.LogInformation(
+ "Agent registered successfully. ID: {AgentId}, Key prefix: {Prefix}",
+ result.AgentId, result.ApiKeyPrefix);
+ }
+ catch (Exception ex)
+ {
+ _logger.LogError(ex, "Failed to register agent");
+ throw;
+ }
+
+ // Step 2: Heartbeat loop (every 30 seconds)
+ _logger.LogInformation("Starting heartbeat loop (30s interval)");
+
+ while (!stoppingToken.IsCancellationRequested)
+ {
+ try
+ {
+ var heartbeatRequest = new HeartbeatRequest(GetPublicIp());
+ var heartbeatResponse = await client.PostAsJsonAsync(
+ $"api/agents/{_state.AgentId}/heartbeat",
+ heartbeatRequest, stoppingToken);
+
+ if (!heartbeatResponse.IsSuccessStatusCode)
+ {
+ _logger.LogWarning("Heartbeat failed: {StatusCode}", heartbeatResponse.StatusCode);
+ }
+ }
+ catch (Exception ex) when (ex is not OperationCanceledException)
+ {
+ _logger.LogWarning(ex, "Heartbeat error (will retry)");
+ }
+
+ await Task.Delay(TimeSpan.FromSeconds(30), stoppingToken);
+ }
+ }
+
+ private static string? GetPublicIp()
+ {
+ return null;
+ }
+}
+
+public class AgentState
+{
+ public Guid AgentId { get; set; }
+ public string? ApiKey { get; set; }
+ public string? ApiKeyPrefix { get; set; }
+}
+
+internal sealed record RegisterRequest(string Token, string Hostname, string Version);
+
+internal sealed record RegisterResponse(
+ [property: JsonPropertyName("agentId")] Guid AgentId,
+ [property: JsonPropertyName("apiKey")] string ApiKey,
+ [property: JsonPropertyName("apiKeyPrefix")] string ApiKeyPrefix);
+
+internal sealed record HeartbeatRequest(string? PublicIp);
diff --git a/src/Heimdall.Api/Controllers/AgentsController.cs b/src/Heimdall.Api/Controllers/AgentsController.cs
new file mode 100644
index 0000000..4a792e3
--- /dev/null
+++ b/src/Heimdall.Api/Controllers/AgentsController.cs
@@ -0,0 +1,65 @@
+using Heimdall.Application.DTOs;
+using Heimdall.Application.Services;
+using Heimdall.Infrastructure.Security;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Heimdall.Api.Controllers;
+
+[ApiController]
+[Route("api/agents")]
+public class AgentsController : ControllerBase
+{
+ private readonly IAgentService _agentService;
+
+ public AgentsController(IAgentService agentService) => _agentService = agentService;
+
+ /// Register an agent using a site registration token.
+ [AllowAnonymous]
+ [HttpPost("register")]
+ public async Task Register(
+ [FromBody] RegisterAgentRequest request, CancellationToken ct)
+ {
+ // Extract API key from header (may be empty for registration)
+ var apiKey = Request.Headers.Authorization.FirstOrDefault()
+ ?.Replace("Bearer ", "", StringComparison.OrdinalIgnoreCase);
+
+ var result = await _agentService.RegisterAsync(request, apiKey, ct);
+ return result.IsSuccess
+ ? Ok(result.Data)
+ : StatusCode(result.StatusCode ?? 401, new { error = result.Error });
+ }
+
+ /// Send heartbeat from agent (API Key auth).
+ [Authorize(AuthenticationSchemes = "ApiKey")]
+ [HttpPost("{id:guid}/heartbeat")]
+ public async Task Heartbeat(
+ Guid id, [FromBody] AgentHeartbeatRequest request, CancellationToken ct)
+ {
+ var result = await _agentService.HeartbeatAsync(id, request, ct);
+ return result.IsSuccess
+ ? Ok()
+ : StatusCode(result.StatusCode ?? 400, new { error = result.Error });
+ }
+
+ /// Get agent details (JWT auth).
+ [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
+ [HttpGet("{id:guid}")]
+ public async Task GetById(Guid id, CancellationToken ct)
+ {
+ var result = await _agentService.GetByIdAsync(id, ct);
+ return result.IsSuccess
+ ? Ok(result.Data)
+ : NotFound(new { error = result.Error });
+ }
+
+ /// List agents for a site.
+ [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
+ [HttpGet("by-site/{siteId:guid}")]
+ public async Task ListBySite(
+ Guid siteId, [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
+ {
+ var result = await _agentService.ListBySiteAsync(siteId, page, pageSize, ct);
+ return Ok(result.Data);
+ }
+}
diff --git a/src/Heimdall.Api/Controllers/AuthController.cs b/src/Heimdall.Api/Controllers/AuthController.cs
new file mode 100644
index 0000000..ef99f28
--- /dev/null
+++ b/src/Heimdall.Api/Controllers/AuthController.cs
@@ -0,0 +1,64 @@
+using Heimdall.Application.DTOs;
+using Heimdall.Application.Services;
+using Heimdall.Infrastructure.Security;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Heimdall.Api.Controllers;
+
+[ApiController]
+[Route("api/auth")]
+public class AuthController : ControllerBase
+{
+ private readonly IAuthService _authService;
+
+ public AuthController(IAuthService authService) => _authService = authService;
+
+ /// Register a new user account.
+ [AllowAnonymous]
+ [HttpPost("register")]
+ public async Task Register(
+ [FromBody] RegisterRequest request, CancellationToken ct)
+ {
+ var result = await _authService.RegisterAsync(request, ct);
+ return result.IsSuccess
+ ? Ok(result.Data)
+ : StatusCode(result.StatusCode ?? 400, new { error = result.Error });
+ }
+
+ /// Login with email and password.
+ [AllowAnonymous]
+ [HttpPost("login")]
+ public async Task Login(
+ [FromBody] LoginRequest request, CancellationToken ct)
+ {
+ var result = await _authService.LoginAsync(request, ct);
+ return result.IsSuccess
+ ? Ok(result.Data)
+ : StatusCode(result.StatusCode ?? 401, new { error = result.Error });
+ }
+
+ /// Verify 2FA code during login.
+ [AllowAnonymous]
+ [HttpPost("2fa/verify")]
+ public async Task Verify2fa(
+ [FromBody] Verify2faRequest request, CancellationToken ct)
+ {
+ var result = await _authService.Verify2faAsync(request, ct);
+ return result.IsSuccess
+ ? Ok(result.Data)
+ : StatusCode(result.StatusCode ?? 401, new { error = result.Error });
+ }
+
+ /// Refresh an expired access token.
+ [AllowAnonymous]
+ [HttpPost("refresh")]
+ public async Task Refresh(
+ [FromBody] RefreshTokenRequest request, CancellationToken ct)
+ {
+ var result = await _authService.RefreshTokenAsync(request.RefreshToken, ct);
+ return result.IsSuccess
+ ? Ok(result.Data)
+ : StatusCode(result.StatusCode ?? 401, new { error = result.Error });
+ }
+}
diff --git a/src/Heimdall.Api/Controllers/SitesController.cs b/src/Heimdall.Api/Controllers/SitesController.cs
new file mode 100644
index 0000000..42d6a1a
--- /dev/null
+++ b/src/Heimdall.Api/Controllers/SitesController.cs
@@ -0,0 +1,85 @@
+using System.Security.Claims;
+using Heimdall.Application.DTOs;
+using Heimdall.Application.Services;
+using Heimdall.Infrastructure.Security;
+using Microsoft.AspNetCore.Authorization;
+using Microsoft.AspNetCore.Mvc;
+
+namespace Heimdall.Api.Controllers;
+
+[ApiController]
+[Route("api/sites")]
+public class SitesController : ControllerBase
+{
+ private readonly ISiteService _siteService;
+
+ public SitesController(ISiteService siteService) => _siteService = siteService;
+
+ /// Create a new site (Admin only).
+ [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)]
+ [HttpPost]
+ public async Task Create(
+ [FromBody] CreateSiteRequest request, CancellationToken ct)
+ {
+ var userId = Guid.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
+ var result = await _siteService.CreateAsync(request, userId, ct);
+ return result.IsSuccess
+ ? Ok(result.Data)
+ : StatusCode(result.StatusCode ?? 400, new { error = result.Error });
+ }
+
+ /// List all sites.
+ [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
+ [HttpGet]
+ public async Task List(
+ [FromQuery] int page = 1, [FromQuery] int pageSize = 20, CancellationToken ct = default)
+ {
+ var result = await _siteService.ListAsync(page, pageSize, ct);
+ return Ok(result.Data);
+ }
+
+ /// Get a site by ID.
+ [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteRead)]
+ [HttpGet("{id:guid}")]
+ public async Task GetById(Guid id, CancellationToken ct)
+ {
+ var result = await _siteService.GetByIdAsync(id, ct);
+ return result.IsSuccess
+ ? Ok(result.Data)
+ : NotFound(new { error = result.Error });
+ }
+
+ /// Update a site (Admin only).
+ [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)]
+ [HttpPut("{id:guid}")]
+ public async Task Update(
+ Guid id, [FromBody] UpdateSiteRequest request, CancellationToken ct)
+ {
+ var result = await _siteService.UpdateAsync(id, request, ct);
+ return result.IsSuccess
+ ? Ok(result.Data)
+ : StatusCode(result.StatusCode ?? 400, new { error = result.Error });
+ }
+
+ /// Delete a site (Admin only).
+ [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteDelete)]
+ [HttpDelete("{id:guid}")]
+ public async Task Delete(Guid id, CancellationToken ct)
+ {
+ var result = await _siteService.DeleteAsync(id, ct);
+ return result.IsSuccess
+ ? NoContent()
+ : StatusCode(result.StatusCode ?? 400, new { error = result.Error });
+ }
+
+ /// Generate a new agent registration token (Admin only).
+ [Authorize(AuthenticationSchemes = "JwtBearer", Policy = AppPermissions.SiteWrite)]
+ [HttpPost("{id:guid}/tokens")]
+ public async Task GenerateToken(Guid id, CancellationToken ct)
+ {
+ var result = await _siteService.GenerateTokenAsync(id, ct);
+ return result.IsSuccess
+ ? Ok(result.Data)
+ : StatusCode(result.StatusCode ?? 400, new { error = result.Error });
+ }
+}
diff --git a/src/Heimdall.Api/Filters/ExceptionFilter.cs b/src/Heimdall.Api/Filters/ExceptionFilter.cs
new file mode 100644
index 0000000..2bfcd16
--- /dev/null
+++ b/src/Heimdall.Api/Filters/ExceptionFilter.cs
@@ -0,0 +1,34 @@
+using System.Net;
+using Heimdall.Application.Common;
+using Microsoft.AspNetCore.Mvc;
+using Microsoft.AspNetCore.Mvc.Filters;
+
+namespace Heimdall.Api.Filters;
+
+public class ExceptionFilter : IExceptionFilter
+{
+ private readonly ILogger _logger;
+
+ public ExceptionFilter(ILogger logger) => _logger = logger;
+
+ public void OnException(ExceptionContext context)
+ {
+ _logger.LogError(context.Exception, "Unhandled exception: {Message}", context.Exception.Message);
+
+ var response = new
+ {
+ error = new
+ {
+ code = "InternalServerError",
+ message = "An unexpected error occurred"
+ }
+ };
+
+ context.Result = new ObjectResult(response)
+ {
+ StatusCode = (int)HttpStatusCode.InternalServerError
+ };
+
+ context.ExceptionHandled = true;
+ }
+}
diff --git a/src/Heimdall.Api/Heimdall.Api.csproj b/src/Heimdall.Api/Heimdall.Api.csproj
index 3f60095..b56ead6 100644
--- a/src/Heimdall.Api/Heimdall.Api.csproj
+++ b/src/Heimdall.Api/Heimdall.Api.csproj
@@ -7,6 +7,7 @@
+
diff --git a/src/Heimdall.Api/Program.cs b/src/Heimdall.Api/Program.cs
index 666a9c5..8d6436f 100644
--- a/src/Heimdall.Api/Program.cs
+++ b/src/Heimdall.Api/Program.cs
@@ -1,23 +1,121 @@
+using System.Text;
+using Heimdall.Api.Filters;
+using Heimdall.Application;
+using Heimdall.Infrastructure;
+using Heimdall.Infrastructure.Data;
+using Heimdall.Infrastructure.Security;
+using Microsoft.AspNetCore.Authentication.JwtBearer;
+using Microsoft.EntityFrameworkCore;
+using Microsoft.IdentityModel.Tokens;
+
var builder = WebApplication.CreateBuilder(args);
-// Add services to the container.
+// ── Services ──────────────────────────────────────────────────────
+
+builder.Services.AddControllers(options =>
+{
+ options.Filters.Add();
+});
-builder.Services.AddControllers();
-// Learn more about configuring OpenAPI at https://aka.ms/aspnet/openapi
builder.Services.AddOpenApi();
+// ── Application layer ─────────────────────────────────────────────
+builder.Services.AddApplication();
+
+// ── Infrastructure layer ──────────────────────────────────────────
+builder.Services.AddInfrastructure(builder.Configuration);
+
+// ── Authentication ────────────────────────────────────────────────
+var jwtKey = builder.Configuration["Jwt:Key"]
+ ?? throw new InvalidOperationException("JWT:Key is not configured");
+var jwtIssuer = builder.Configuration["Jwt:Issuer"] ?? "heimdall";
+var jwtAudience = builder.Configuration["Jwt:Audience"] ?? "heimdall-api";
+
+builder.Services.AddAuthentication(options =>
+{
+ options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
+ options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
+})
+.AddJwtBearer("JwtBearer", options =>
+{
+ options.TokenValidationParameters = new TokenValidationParameters
+ {
+ ValidateIssuerSigningKey = true,
+ IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtKey)),
+ ValidateIssuer = true,
+ ValidIssuer = jwtIssuer,
+ ValidateAudience = true,
+ ValidAudience = jwtAudience,
+ ValidateLifetime = true,
+ ClockSkew = TimeSpan.Zero
+ };
+})
+.AddScheme("ApiKey", null);
+
+// ── Authorization policies ───────────────────────────────────────
+builder.Services.AddAuthorization(options =>
+{
+ var allPermissions = AppPermissions.RolePermissions.Values
+ .SelectMany(p => p).Distinct();
+
+ foreach (var permission in allPermissions)
+ {
+ options.AddPolicy(permission, policy =>
+ policy.RequireClaim("permission", permission));
+ }
+});
+
+// ── CORS ──────────────────────────────────────────────────────────
+var allowedOrigins = builder.Configuration["Cors:AllowedOrigins"]?.Split(',')
+ ?? ["https://localhost:5001"];
+
+builder.Services.AddCors(options =>
+{
+ options.AddPolicy("ApiPolicy", policy =>
+ policy.WithOrigins(allowedOrigins)
+ .AllowCredentials()
+ .AllowAnyHeader()
+ .WithMethods("GET", "POST", "PUT", "DELETE", "PATCH"));
+});
+
+// ── Pipeline ──────────────────────────────────────────────────────
+
var app = builder.Build();
-// Configure the HTTP request pipeline.
+// Apply migrations on startup
+using (var scope = app.Services.CreateScope())
+{
+ var db = scope.ServiceProvider.GetRequiredService();
+ if (db.Database.GetPendingMigrations().Any())
+ {
+ db.Database.Migrate();
+ }
+}
+
+// Seed roles
+using (var scope = app.Services.CreateScope())
+{
+ var roleManager = scope.ServiceProvider
+ .GetRequiredService>();
+
+ foreach (var roleName in AppRoles.All)
+ {
+ if (!await roleManager.RoleExistsAsync(roleName))
+ {
+ await roleManager.CreateAsync(new Heimdall.Domain.Entities.AppRole(roleName));
+ }
+ }
+}
+
if (app.Environment.IsDevelopment())
{
app.MapOpenApi();
}
+app.UseCors("ApiPolicy");
app.UseHttpsRedirection();
-
+app.UseAuthentication();
app.UseAuthorization();
-
app.MapControllers();
app.Run();
diff --git a/src/Heimdall.Application/Common/ServiceResult.cs b/src/Heimdall.Application/Common/ServiceResult.cs
new file mode 100644
index 0000000..6df7ed2
--- /dev/null
+++ b/src/Heimdall.Application/Common/ServiceResult.cs
@@ -0,0 +1,48 @@
+namespace Heimdall.Application.Common;
+
+public class ServiceResult
+{
+ public bool IsSuccess { get; protected set; }
+ public string? Error { get; protected set; }
+ public int? StatusCode { get; protected set; }
+
+ protected ServiceResult() { }
+
+ public static ServiceResult Success() => new() { IsSuccess = true };
+
+ public static ServiceResult Failure(string error, int statusCode = 400) =>
+ new() { IsSuccess = false, Error = error, StatusCode = statusCode };
+
+ public static ServiceResult NotFound(string error = "Resource not found") =>
+ new() { IsSuccess = false, Error = error, StatusCode = 404 };
+
+ public static ServiceResult Unauthorized(string error = "Unauthorized") =>
+ new() { IsSuccess = false, Error = error, StatusCode = 401 };
+
+ public static ServiceResult Conflict(string error) =>
+ new() { IsSuccess = false, Error = error, StatusCode = 409 };
+}
+
+#pragma warning disable CA1000 // Do not declare static members on generic types
+public class ServiceResult : ServiceResult
+{
+ public T? Data { get; private set; }
+
+ private ServiceResult() { }
+
+ public static ServiceResult Success(T data) =>
+ new() { IsSuccess = true, Data = data };
+
+ public new static ServiceResult Failure(string error, int statusCode = 400) =>
+ new() { IsSuccess = false, Error = error, StatusCode = statusCode };
+
+ public new static ServiceResult NotFound(string error = "Resource not found") =>
+ new() { IsSuccess = false, Error = error, StatusCode = 404 };
+
+ public new static ServiceResult Unauthorized(string error = "Unauthorized") =>
+ new() { IsSuccess = false, Error = error, StatusCode = 401 };
+
+ public new static ServiceResult Conflict(string error) =>
+ new() { IsSuccess = false, Error = error, StatusCode = 409 };
+}
+#pragma warning restore CA1000
diff --git a/src/Heimdall.Application/DTOs/AgentDto.cs b/src/Heimdall.Application/DTOs/AgentDto.cs
new file mode 100644
index 0000000..7acaad0
--- /dev/null
+++ b/src/Heimdall.Application/DTOs/AgentDto.cs
@@ -0,0 +1,36 @@
+using Heimdall.Domain.Enums;
+
+namespace Heimdall.Application.DTOs;
+
+public record RegisterAgentRequest(
+ string Token,
+ string Hostname,
+ string Version,
+ string? PublicIp);
+
+public record AgentHeartbeatRequest(
+ string? PublicIp,
+ bool? HasGpu,
+ int? CpuCores,
+ long? MemoryMb,
+ string? GpuType);
+
+public record AgentResponse(
+ Guid Id,
+ Guid SiteId,
+ string Name,
+ string Hostname,
+ string Version,
+ AgentStatus Status,
+ DateTime? LastHeartbeat,
+ string? PublicIp,
+ bool HasGpu,
+ int CpuCores,
+ long MemoryMb,
+ string GpuType,
+ DateTime CreatedAt);
+
+public record RegisterAgentResponse(
+ Guid AgentId,
+ string ApiKey,
+ string ApiKeyPrefix);
diff --git a/src/Heimdall.Application/DTOs/AuthDto.cs b/src/Heimdall.Application/DTOs/AuthDto.cs
new file mode 100644
index 0000000..6dd40fe
--- /dev/null
+++ b/src/Heimdall.Application/DTOs/AuthDto.cs
@@ -0,0 +1,37 @@
+namespace Heimdall.Application.DTOs;
+
+public record RegisterRequest(string Email, string Password, string DisplayName);
+
+public record LoginRequest(string Email, string Password);
+
+public record Verify2faRequest(string Email, string Code);
+
+public record RefreshTokenRequest(string RefreshToken);
+
+public record AuthResponse(
+ string AccessToken,
+ string RefreshToken,
+ DateTime ExpiresAt,
+ bool Requires2fa,
+ UserInfo User);
+
+public record UserInfo(
+ Guid Id,
+ string Email,
+ string DisplayName,
+ IList Roles);
+
+public record ApiKeyResponse(
+ Guid Id,
+ string KeyPrefix,
+ Guid? SiteId,
+ DateTime CreatedAt,
+ DateTime? ExpiresAt,
+ bool Enabled,
+ DateTime? LastUsedAt);
+
+public record CreateApiKeyResponse(
+ Guid Id,
+ string KeyPrefix,
+ string FullKey,
+ DateTime? ExpiresAt);
diff --git a/src/Heimdall.Application/DTOs/PagedResult.cs b/src/Heimdall.Application/DTOs/PagedResult.cs
new file mode 100644
index 0000000..dca6b2d
--- /dev/null
+++ b/src/Heimdall.Application/DTOs/PagedResult.cs
@@ -0,0 +1,12 @@
+namespace Heimdall.Application.DTOs;
+
+public record PagedResult(
+ IReadOnlyList Items,
+ int TotalCount,
+ int Page,
+ int PageSize)
+{
+ public int TotalPages => (int)Math.Ceiling(TotalCount / (double)PageSize);
+ public bool HasPreviousPage => Page > 1;
+ public bool HasNextPage => Page < TotalPages;
+}
diff --git a/src/Heimdall.Application/DTOs/SiteDto.cs b/src/Heimdall.Application/DTOs/SiteDto.cs
new file mode 100644
index 0000000..a5c4e33
--- /dev/null
+++ b/src/Heimdall.Application/DTOs/SiteDto.cs
@@ -0,0 +1,26 @@
+namespace Heimdall.Application.DTOs;
+
+public record CreateSiteRequest(string Name, string? Address, string? Timezone);
+
+public record UpdateSiteRequest(string Name, string? Address, string? Timezone);
+
+public record SiteResponse(
+ Guid Id,
+ string Name,
+ string? Address,
+ string Timezone,
+ bool Enabled,
+ DateTime CreatedAt);
+
+public record SiteWithTokenResponse(
+ Guid Id,
+ string Name,
+ string? Address,
+ string Timezone,
+ string? RegistrationToken,
+ DateTime? TokenExpiresAt,
+ DateTime CreatedAt);
+
+public record RegistrationTokenResponse(
+ string Token,
+ DateTime ExpiresAt);
diff --git a/src/Heimdall.Application/DependencyInjection.cs b/src/Heimdall.Application/DependencyInjection.cs
new file mode 100644
index 0000000..ed38f62
--- /dev/null
+++ b/src/Heimdall.Application/DependencyInjection.cs
@@ -0,0 +1,14 @@
+using FluentValidation;
+using Microsoft.Extensions.DependencyInjection;
+
+namespace Heimdall.Application;
+
+public static class DependencyInjection
+{
+ public static IServiceCollection AddApplication(this IServiceCollection services)
+ {
+ services.AddValidatorsFromAssembly(typeof(DependencyInjection).Assembly);
+
+ return services;
+ }
+}
diff --git a/src/Heimdall.Application/Heimdall.Application.csproj b/src/Heimdall.Application/Heimdall.Application.csproj
index cd24e0d..d7370c4 100644
--- a/src/Heimdall.Application/Heimdall.Application.csproj
+++ b/src/Heimdall.Application/Heimdall.Application.csproj
@@ -4,6 +4,11 @@
+
+
+
+
+
net10.0
enable
diff --git a/src/Heimdall.Application/Services/IAgentService.cs b/src/Heimdall.Application/Services/IAgentService.cs
new file mode 100644
index 0000000..c964ac1
--- /dev/null
+++ b/src/Heimdall.Application/Services/IAgentService.cs
@@ -0,0 +1,12 @@
+using Heimdall.Application.Common;
+using Heimdall.Application.DTOs;
+
+namespace Heimdall.Application.Services;
+
+public interface IAgentService
+{
+ Task> RegisterAsync(RegisterAgentRequest request, string? apiKey, CancellationToken ct);
+ Task HeartbeatAsync(Guid agentId, AgentHeartbeatRequest request, CancellationToken ct);
+ Task> GetByIdAsync(Guid id, CancellationToken ct);
+ Task>> ListBySiteAsync(Guid siteId, int page, int pageSize, CancellationToken ct);
+}
diff --git a/src/Heimdall.Application/Services/IApiKeyService.cs b/src/Heimdall.Application/Services/IApiKeyService.cs
new file mode 100644
index 0000000..de3d317
--- /dev/null
+++ b/src/Heimdall.Application/Services/IApiKeyService.cs
@@ -0,0 +1,12 @@
+using Heimdall.Application.Common;
+using Heimdall.Application.DTOs;
+
+namespace Heimdall.Application.Services;
+
+public interface IApiKeyService
+{
+ Task> CreateAsync(Guid? siteId, Guid? createdByUserId, DateTime? expiresAt, CancellationToken ct);
+ Task>> ListAsync(Guid? siteId, int page, int pageSize, CancellationToken ct);
+ Task RevokeAsync(Guid id, CancellationToken ct);
+ Task> ValidateKeyAsync(string key, CancellationToken ct);
+}
diff --git a/src/Heimdall.Application/Services/IAuthService.cs b/src/Heimdall.Application/Services/IAuthService.cs
new file mode 100644
index 0000000..f5b0db7
--- /dev/null
+++ b/src/Heimdall.Application/Services/IAuthService.cs
@@ -0,0 +1,14 @@
+using Heimdall.Application.Common;
+using Heimdall.Application.DTOs;
+
+namespace Heimdall.Application.Services;
+
+public interface IAuthService
+{
+ Task> RegisterAsync(RegisterRequest request, CancellationToken ct);
+ Task> LoginAsync(LoginRequest request, CancellationToken ct);
+ Task> Verify2faAsync(Verify2faRequest request, CancellationToken ct);
+ Task> RefreshTokenAsync(string refreshToken, CancellationToken ct);
+ Task Enable2faAsync(Guid userId, CancellationToken ct);
+ Task LogoutAsync(Guid userId, string refreshToken, CancellationToken ct);
+}
diff --git a/src/Heimdall.Application/Services/ISiteService.cs b/src/Heimdall.Application/Services/ISiteService.cs
new file mode 100644
index 0000000..fe45bf6
--- /dev/null
+++ b/src/Heimdall.Application/Services/ISiteService.cs
@@ -0,0 +1,14 @@
+using Heimdall.Application.Common;
+using Heimdall.Application.DTOs;
+
+namespace Heimdall.Application.Services;
+
+public interface ISiteService
+{
+ Task> CreateAsync(CreateSiteRequest request, Guid userId, CancellationToken ct);
+ Task> GetByIdAsync(Guid id, CancellationToken ct);
+ Task>> ListAsync(int page, int pageSize, CancellationToken ct);
+ Task> UpdateAsync(Guid id, UpdateSiteRequest request, CancellationToken ct);
+ Task DeleteAsync(Guid id, CancellationToken ct);
+ Task> GenerateTokenAsync(Guid id, CancellationToken ct);
+}
diff --git a/src/Heimdall.Application/Validators/CreateSiteValidator.cs b/src/Heimdall.Application/Validators/CreateSiteValidator.cs
new file mode 100644
index 0000000..bd93cd6
--- /dev/null
+++ b/src/Heimdall.Application/Validators/CreateSiteValidator.cs
@@ -0,0 +1,87 @@
+using FluentValidation;
+using Heimdall.Application.DTOs;
+
+namespace Heimdall.Application.Validators;
+
+public class CreateSiteValidator : AbstractValidator
+{
+ public CreateSiteValidator()
+ {
+ RuleFor(x => x.Name)
+ .NotEmpty()
+ .MaximumLength(200);
+
+ RuleFor(x => x.Address)
+ .MaximumLength(500)
+ .When(x => x.Address is not null);
+
+ RuleFor(x => x.Timezone)
+ .Must(tz => string.IsNullOrEmpty(tz) || IsValidTimezone(tz))
+ .WithMessage("Invalid timezone. Use IANA timezone format (e.g., 'Europe/Paris').");
+ }
+
+ private static bool IsValidTimezone(string timezone)
+ {
+ try
+ {
+ _ = TimeZoneInfo.FindSystemTimeZoneById(timezone);
+ return true;
+ }
+ catch
+ {
+ return false;
+ }
+ }
+}
+
+public class RegisterAgentValidator : AbstractValidator
+{
+ public RegisterAgentValidator()
+ {
+ RuleFor(x => x.Token)
+ .NotEmpty()
+ .MaximumLength(500);
+
+ RuleFor(x => x.Hostname)
+ .NotEmpty()
+ .MaximumLength(255);
+
+ RuleFor(x => x.Version)
+ .MaximumLength(50);
+ }
+}
+
+public class LoginRequestValidator : AbstractValidator
+{
+ public LoginRequestValidator()
+ {
+ RuleFor(x => x.Email)
+ .NotEmpty()
+ .EmailAddress()
+ .MaximumLength(200);
+
+ RuleFor(x => x.Password)
+ .NotEmpty()
+ .MaximumLength(200);
+ }
+}
+
+public class RegisterRequestValidator : AbstractValidator
+{
+ public RegisterRequestValidator()
+ {
+ RuleFor(x => x.Email)
+ .NotEmpty()
+ .EmailAddress()
+ .MaximumLength(200);
+
+ RuleFor(x => x.Password)
+ .NotEmpty()
+ .MinimumLength(8)
+ .MaximumLength(200);
+
+ RuleFor(x => x.DisplayName)
+ .NotEmpty()
+ .MaximumLength(200);
+ }
+}
diff --git a/src/Heimdall.Domain.Primitives/Entity.cs b/src/Heimdall.Domain.Primitives/Entity.cs
new file mode 100644
index 0000000..0684bbc
--- /dev/null
+++ b/src/Heimdall.Domain.Primitives/Entity.cs
@@ -0,0 +1,28 @@
+namespace Heimdall.Domain.Primitives;
+
+///
+/// Base class for all domain entities with a strongly-typed identifier.
+///
+public abstract class Entity : IEquatable>
+ where TId : notnull
+{
+ public TId Id { get; protected set; } = default!;
+
+ protected Entity(TId id) => Id = id;
+
+ protected Entity() { } // EF Core
+
+ public override bool Equals(object? obj) =>
+ obj is Entity other && Id.Equals(other.Id);
+
+ public bool Equals(Entity? other) =>
+ other is not null && Id.Equals(other.Id);
+
+ public override int GetHashCode() => Id.GetHashCode();
+
+ public static bool operator ==(Entity? left, Entity? right) =>
+ left is null ? right is null : left.Equals(right);
+
+ public static bool operator !=(Entity? left, Entity? right) =>
+ !(left == right);
+}
diff --git a/src/Heimdall.Domain.Primitives/IAuditableEntity.cs b/src/Heimdall.Domain.Primitives/IAuditableEntity.cs
new file mode 100644
index 0000000..9f57fbc
--- /dev/null
+++ b/src/Heimdall.Domain.Primitives/IAuditableEntity.cs
@@ -0,0 +1,10 @@
+namespace Heimdall.Domain.Primitives;
+
+///
+/// Interface for entities with automatic audit timestamp tracking.
+///
+public interface IAuditableEntity
+{
+ DateTime CreatedAt { get; set; }
+ DateTime UpdatedAt { get; set; }
+}
diff --git a/src/Heimdall.Domain.Primitives/ISoftDeletable.cs b/src/Heimdall.Domain.Primitives/ISoftDeletable.cs
new file mode 100644
index 0000000..76c6496
--- /dev/null
+++ b/src/Heimdall.Domain.Primitives/ISoftDeletable.cs
@@ -0,0 +1,11 @@
+namespace Heimdall.Domain.Primitives;
+
+///
+/// Interface for entities that support soft deletion.
+///
+public interface ISoftDeletable
+{
+ bool IsDeleted { get; }
+ DateTime? DeletedAt { get; }
+ void SoftDelete();
+}
diff --git a/src/Heimdall.Domain.Primitives/ValueObject.cs b/src/Heimdall.Domain.Primitives/ValueObject.cs
new file mode 100644
index 0000000..7cda4fb
--- /dev/null
+++ b/src/Heimdall.Domain.Primitives/ValueObject.cs
@@ -0,0 +1,35 @@
+namespace Heimdall.Domain.Primitives;
+
+///
+/// Base class for value objects. Equality is based on all constituent properties.
+///
+public abstract class ValueObject : IEquatable
+{
+ protected abstract IEnumerable