MechaOnion 0.3.0-preview

This is a prerelease version of MechaOnion.
There is a newer prerelease version of this package available.
See the version list below for details.
dotnet add package MechaOnion --version 0.3.0-preview
                    
NuGet\Install-Package MechaOnion -Version 0.3.0-preview
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="MechaOnion" Version="0.3.0-preview" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="MechaOnion" Version="0.3.0-preview" />
                    
Directory.Packages.props
<PackageReference Include="MechaOnion" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add MechaOnion --version 0.3.0-preview
                    
#r "nuget: MechaOnion, 0.3.0-preview"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package MechaOnion@0.3.0-preview
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=MechaOnion&version=0.3.0-preview&prerelease
                    
Install as a Cake Addin
#tool nuget:?package=MechaOnion&version=0.3.0-preview&prerelease
                    
Install as a Cake Tool

MechaOnion

MechaOnion is a single-assembly, modular base library for .NET (net10.0). Each module lives in its own folder and namespace (MechaOnion.<Module>) and can be enabled or disabled by configuration.

Current version: 0.3.0-preview. See the CHANGELOG for breaking changes.

Three-line setup

var builder = WebApplication.CreateBuilder(args);

builder.AddMechaOnion(builder.Configuration); // 1) configuration and options
builder.Services.AddMechaOnion();             // 2) services, repositories and providers

var app = builder.Build();

app.UseMechaOnion();                          // 3) middlewares and endpoints

app.Run();

UseMechaOnion applies a fixed pipeline order regardless of module discovery order: CORS → Routing → Tracing → Tenant → Permissions → Errors → endpoints → health checks. Tracing runs before Tenant and Permissions, so their logs already carry tracing_id, step_id and origin.

Modules

Flag Module Responsibility
Core Core Entities, contracts, exceptions, attributes, helpers and validations
Auth Auth JWT validation, permissions and CORS
Configs Configs Tenant/app key-value configuration
Tenants Tenants Tenants, themes and resolution
Users Users Users, login, profiles, groups, roles and fields
Events Events Event catalog, automations, webhooks and integrations
Configuration Configuration Host sources, environment/project info and OpenAPI helpers
Database Database EF Core base context and repository infrastructure
Messaging Messaging Local and RabbitMQ providers, retry, scheduling and DLQ
MessagingAdmin MessagingAdmin Administration API for the local and RabbitMQ providers
Observability Observability Structured logging, W3C tracing and OpenTelemetry trace export
HealthChecks HealthChecks Readiness and liveness endpoints
Web Web CORS, error handling, ProblemDetails, JSON options and OpenAPI/Scalar docs
Enrich Enrich Data enrichment pipeline and contracts

Flags are combined through MechaOnion:Modules (default All). Dependencies are auto-enabled and registered in topological order.

Configuration

"MechaOnion": {
  "Modules": "All",
  "ServiceName": "MechaOnion",
  "EnableTenantFilter": true,
  "MigrationsAssembly": "",
  "DefaultTenantId": null,
  "EnableSingleTenantFallback": false
}

Extending the library

Default implementations are registered with TryAdd; the last registration wins, so consumers can replace services without editing the library.

// Replace a service through its public contract.
builder.Services.Replace(ServiceDescriptor.Scoped<IEnrichmentRepository, MyEnrichRepository>());

// Replace the database provider through options.
builder.Services.AddSingleton(new MechaOnionDbContextOptions
{
    MigrationsAssembly = "MyHost",
    EnableTenantFilter = true,
    ConfigureProvider = options => options.UseNpgsql(connectionString),
});

// Register a custom tenant resolver after the library (last one wins).
builder.Services.AddScoped<ITenantResolver, MyTenantResolver>();

E-mail delivery is decoupled through IEmailDispatcher (MechaOnion.Communication). The host registers an adapter for its e-mail service:

builder.Services.Replace(
    ServiceDescriptor.Singleton<IEmailDispatcher, MyEmailDispatcher>());

Tracing

Every request, message consumption, internal call and cronjob runs in a W3C Trace Context step (System.Diagnostics.Activity). The flow id (TracingId) is the trace id and the step id is the span id, so logs, traces and DTO metadata use the same values. Origin and flow start travel in the mo entry of the tracestate (mo=o:<MechaOnion:ServiceName>;s:<unix-ms>). See ADR-002.

  • DTOs: DtoBase.Tracing holds the TracingMetadata of the step that created the DTO (TracingId, StepId, ParentStepId, Origin, StartedAt, EndedAt). It is never written to nor read from JSON and has no public setter; copy it with target.WithTracingFrom(source).
  • Messaging: publications (queue, topic, batch and schedule) carry traceparent/tracestate with the local provider and RabbitMQ; consumers continue the flow and read context.Metadata.Tracing. Retries and dead letters stay in the same flow.
  • Logs: every event emitted in a step carries tracing_id, step_id and origin, plus a Step completed event with duration_ms.
  • Responses and external calls never carry tracing metadata. The only exception is the v1/MessagingAdmin API, which exposes tracingId, origin and flowStartedAt per message to operators.

Internal HTTP clients (opt-in)

Outgoing propagation is disabled process-wide. The Core module replaces the runtime propagator with the NoOutput one, so no HttpClient sends traceparent/tracestate (webhooks, Mautic, third-party SDKs and your own clients included) unless it opts in. Do not pre-build HTTP handlers before builder.Services.AddMechaOnion().

Mark only the clients that call your own services:

builder.Services
    .AddHttpClient("orders-api", client => client.BaseAddress = new Uri("http://orders-api"))
    .AddMechaOnionTracing();

The receiving MechaOnion API continues the flow in a new step. Incoming traceparent headers are always accepted; a missing or malformed header starts a new flow with this service as origin.

Settings

Trace export reuses the LoggingSettings section:

"LoggingSettings": {
  "OpenTelemetryUrl": "http://opentelemetry-collector:4317",
  "EnableTracing": true,
  "TracingSampleRatio": 1.0,
  "TracingOpenTelemetryUrl": null
}
Key Default Description
EnableTracing true Exports traces (OTLP gRPC, batch). Off keeps metadata, propagation and logs.
TracingSampleRatio 1.0 Fraction (0–1) of flows started here that are exported; continued flows follow the origin decision.
TracingOpenTelemetryUrl null Trace collector endpoint (http/https); falls back to OpenTelemetryUrl.

An unavailable collector never fails requests or consumers: spans are dropped in the background.

Two-factor authentication (e-mail code)

Password login is protected by a second factor by default. After the credentials are validated, POST /v1/Login creates a TwoFactorChallenge and sends a 6-digit code to the user e-mail; the JWT is only issued by POST /v1/Login/VerifyTwoFactor. The code has a single use, expires in 10 minutes, allows 5 wrong attempts per challenge and 10 per account in 15 minutes, and the resend honours a 60 s cooldown plus 3 sends per 15 minutes.

Route Purpose
POST /v1/Login Validates the password and returns code = TwoFactorRequired (9) with challengeId, codeExpiresAt and maskedEmail; no token.
POST /v1/Login/VerifyTwoFactor Consumes { challengeId, code } and returns the usual token + user payload.
POST /v1/Login/ResendTwoFactorCode Rotates the code of an active challenge respecting the limits.
POST /v1/Login/RequestLoginCode / GET /v1/Login/ByCode Refused with code = Invalid (6) while the tenant requires the second factor.

Breaking change: a host that upgrades without configuring anything starts requiring the code. Register a real IEmailDispatcher before deploying and check the migration notes in CHANGELOG.md.

Settings

"TwoFactorSettings": {
  "Enabled": true,
  "CodeLength": 6,
  "CodeDurationMinutes": 10,
  "MaxAttemptsPerChallenge": 5,
  "MaxAttemptsPerAccountWindow": 10,
  "AttemptWindowMinutes": 15,
  "ResendCooldownSeconds": 60,
  "MaxSendsPerWindow": 3,
  "MaxSendsPerIpWindow": 10,
  "SendWindowMinutes": 15,
  "TemplateCode": "TWO_FACTOR_CODE",
  "ServiceCode": ""
}

The IConfiguration section is only the application default. The HMAC key used to store the code hash is not part of the policy: it is generated (32 random bytes, Base64) on first use and persisted in its own global ConfigItem (Key = "TwoFactorSettings.HashKey").

Global and per-tenant override

The effective policy is resolved on every login in this order:

  1. ConfigItem row of the tenant (Key = "TwoFactorSettings", TenantId = <tenant>);
  2. global ConfigItem row (TenantId = "");
  3. the TwoFactorSettings section of IConfiguration;
  4. the built-in defaults (Enabled = true).

A row with invalid JSON or values outside the documented ranges is logged (TwoFactorSettingsOverrideInvalid) and ignored — the previous source is used, never an error. To disable the second factor for one tenant, persist a row for it:

{ "Enabled": false }

A ConfigItem row wins over appsettings. If a global row exists, changing TwoFactorSettings:Enabled in the configuration file has no effect until the row is updated or removed. Persist overrides through IConfigsService (the demo exposes POST /demo/config) instead of editing the file and assuming it takes precedence.

Schema (consumer-owned)

The library does not ship migrations. Create the table in the host schema (PostgreSQL DDL generated from MechaOnionDbContext; the demo and the integration tests use Database.EnsureCreated()):

CREATE TABLE "TwoFactorChallenge" (
    "Id"              text                     NOT NULL,
    "UserId"          text                     NOT NULL,
    "TenantId"        text                     NOT NULL,
    "CodeHash"        text                     NOT NULL,
    "PasswordFingerprint" text                 NOT NULL,
    "ExpirationDate"  timestamp with time zone NOT NULL,
    "Attempts"        integer                  NOT NULL,
    "LastAttemptAt"   timestamp with time zone NULL,
    "SendCount"       integer                  NOT NULL,
    "SendWindowStart" timestamp with time zone NOT NULL,
    "LastSentAt"      timestamp with time zone NOT NULL,
    "IpAddress"       text                     NULL,
    "Remember"        boolean                  NOT NULL,
    "CreatedAt"       timestamp with time zone NOT NULL,
    "ConsumedAt"      timestamp with time zone NULL,
    CONSTRAINT "PK_TwoFactorChallenge" PRIMARY KEY ("Id")
);

CREATE INDEX "IX_TwoFactorChallenge_UserId" ON "TwoFactorChallenge" ("UserId");
CREATE INDEX "IX_TwoFactorChallenge_IpAddress_CreatedAt"
    ON "TwoFactorChallenge" ("IpAddress", "CreatedAt");

xmin (the PostgreSQL system column) is the optimistic concurrency token used to guarantee single use of a code; no extra column is required. The table contains only the HMAC-SHA256 hash — the clear code exists only in memory and in the e-mail.

Host without an e-mail provider

NullEmailDispatcher is the fallback and never throws. When TwoFactorSettings.Enabled is true and the registered dispatcher is still the null one, the startup emits a TwoFactorEmailDispatcherMissing warning and every login attempt fails with TwoFactorDeliveryException (HTTP 200 + code = Error): the user never receives a "code sent" answer for a code that did not leave. The escapes are registering a real IEmailDispatcher or disabling the flag globally/for the tenant.

Known bypasses and operational notes

  • E-mail validation and webhooks keep issuing tokens without the second factor, as before. Both are documented risks (outside the scope of this change) and should be reviewed before relying on 2FA as the only barrier.
  • Password recovery is unchanged; the next login after it still requires the code.
  • Session renewal does not require a new code (Refresh keeps the authenticated session).
  • Reverse proxies: the per-IP limit uses HttpContext.Connection.RemoteIpAddress. Behind nginx/ingress without UseForwardedHeaders, every user shares the proxy IP and the MaxSendsPerIpWindow limit can throttle the whole tenant. Configure forwarded headers in the host.
  • Logs carry TwoFactorChallengeCreated, TwoFactorChallengeConsumed, TwoFactorChallengeResent, TwoFactorVerificationFailed, TwoFactorRateLimited (Scope = User|Ip|Resend), TwoFactorEmailDispatchFailed, TwoFactorAccountLocked, TwoFactorIpThrottled and TwoFactorChallengeInvalidated. They never contain the code or the hash, and the e-mail/IP are masked (j***@example.com, 203.0.***.***).
  • Rollback: setting Enabled = false (globally or per tenant) restores the password-only login; the table stays unused and can be dropped later.

Persistence and migrations

The library does not apply migrations; the consumer owns the schema. The sample host uses MechaOnionDbContext directly with Database.EnsureCreated():

using var scope = app.Services.CreateScope();
var dbContext = scope.ServiceProvider.GetRequiredService<MechaOnionDbContext>();
dbContext.Database.EnsureCreated();

A production host can inherit from MechaOnionDbContext to add its own mappings and seeds, and keep the migrations in its own assembly:

public sealed class AppDbContext : MechaOnionDbContext
{
    public AppDbContext(
        DatabaseSettings databaseSettings,
        ITenantContext? tenantContext = null,
        MechaOnionDbContextOptions? options = null)
        : base(databaseSettings, tenantContext, options)
    {
    }
}

Set MechaOnion:MigrationsAssembly (or MechaOnionDbContextOptions.MigrationsAssembly) to the assembly that contains the migrations.

Tenant resolution

The tenant is resolved in this order:

  1. X-Tenant-Id header
  2. tenant_id claim
  3. tenantId route value
  4. MechaOnion:DefaultTenantId (fixed fallback)
  5. Single-tenant fallback (MechaOnion:EnableSingleTenantFallback)

The single-tenant fallback queries the Tenant table on demand. It only applies when the endpoint requires a tenant and no other resolver found one:

  • Multi-tenant: leave EnableSingleTenantFallback disabled. Requests without an explicit tenant keep returning 400.
  • Single-tenant: enable EnableSingleTenantFallback. If the database contains exactly one tenant, that tenant is used automatically. If it contains zero or multiple tenants, the request still fails with 400.
  • Fixed tenant: set DefaultTenantId when the fallback must be a specific tenant regardless of the database contents.

API documentation

The Web module registers and maps the OpenAPI document and the Scalar UI:

  • GET /docs — Scalar UI
  • GET /openapi/v1.json — OpenAPI document

Both endpoints are anonymous and explicitly opt out of the tenant requirement, so they can be opened directly in a browser without X-Tenant-Id, a tenant route value or a resolved tenant. Mapping is skipped when EnvironmentSettings:EnvironmentType is production.

Messaging administration (v1/MessagingAdmin)

The MessagingAdmin module (MechaOnionModules.MessagingAdmin) exposes a single v1/MessagingAdmin API over two providers:

  • local — messages persisted in the application database through the local messaging provider (MechaOnionDbContext);
  • rabbitmq — queues and exchanges of a vhost accessed through the RabbitMQ Management HTTP API (the management plugin must be enabled).

Enabling the module is just a flag: MechaOnion:Modules = "All" already includes it. The Messaging, Auth, Database and Configuration dependencies are auto-enabled, and the permissions remain system_admin/admin.

Settings

"MessagingAdminSettings": {
  "ManagementUrl": "http://rabbitmq:15672",
  "Username": "",
  "Password": "",
  "VirtualHost": "/",
  "TimeoutSeconds": 10,
  "MaxPageSize": 200
}

Username and Password are sensitive: provide them through environment variables, user-secrets or the orchestrator's secret manager — never commit real credentials. Without ManagementUrl/credentials the local provider keeps working; rabbitmq responds 503 with an explicit message.

Provider selection

Every route accepts provider=local|rabbitmq as an optional query parameter:

  • without provider, the default is local when MessagingSettings.Local=true and rabbitmq when false;
  • provider=local with MessagingSettings.Local=false returns 409 Conflict;
  • provider=rabbitmq forces the external provider regardless of MessagingSettings.Local;
  • an unknown provider returns 400 Bad Request;
  • Management API errors never fall back silently to the local provider: 401/403 unauthorized, 404 not found, 409 duplicate, 502 invalid response and 503 timeout/unavailable.

Capability matrix

Operation local rabbitmq
List/detail queues and topics/exchanges ✅ ✅
Create/remove queues and exchanges ✅ ✅
List paginated messages ✅ (queues and topics) ✅ (queues only)
Inspect a message without consuming ✅ ✅ (ack_requeue_true, MaxPageSize window)
Individual message removal ✅ ❌ (400, capability not available)
Purge ✅ (pending/scheduled; optional DLQ) ✅ (queues only)
Purge an exchange ✅ (local topics) ❌ (not offered by the Management API)
Requeue/reprocess ✅ (back to Pending) ✅ (publish + best-effort removal)

Limitations

  • Exchange purge: the RabbitMQ Management API does not support purging an exchange; the operation returns 400 citing the missing capability.
  • Individual message removal: the Management API cannot remove an arbitrary message; the rabbitmq provider refuses with 400.
  • Listing messages from an exchange: exchanges do not store messages, so listing and inspection on RabbitMQ exchanges return 400.
  • Best-effort requeue: the external message is republished to its origin (x-death[0].queue) or to the explicit target, and the origin is removed with ack_requeue_false. The operation is at-least-once; duplicates and concurrency are possible. Without x-death and without target, the response is 400.
  • Credentials: they never appear in logs, responses or exceptions; Authorization is not logged.

Running the sample

The MechaOnion.Demo host composes the library with the three lines, creates its own schema with EnsureCreated() and seeds a tenant, an admin role and an admin user. It covers login, tenant, configuration and messaging. The sample keeps the second factor explicitly disabled (TwoFactorSettings.Enabled = false) so the password login stays the shortest path to try the library; remove the override to exercise the two-step flow.

dotnet run --project samples/MechaOnion.Demo/MechaOnion.Demo.csproj

The JWT secret comes from MECHAONION_DEMO_JWT_SECRET; without the variable the demo generates an ephemeral key valid only for the current process.

Build, test and pack

dotnet restore MechaOnion.slnx
dotnet build MechaOnion.slnx
dotnet test tests/MechaOnion.Tests/MechaOnion.Tests.csproj
dotnet pack src/MechaOnion/MechaOnion.csproj -c Release -o artifacts

Integration tests use PostgreSQL and are skipped unless a test connection is configured:

MECHAONION_TEST_DB_CONNECTION="Host=localhost;Database=mechaonion;Username=postgres;Password=postgres" \
  dotnet test tests/MechaOnion.Tests/MechaOnion.Tests.csproj

Continuous integration and NuGet publishing

  • .github/workflows/ci.yml runs on every pull request, on pushes to main and on manual dispatch: builds the solution on Linux, macOS and Windows and runs the suite (without database, so PostgreSQL tests are skipped), plus a Linux job with a PostgreSQL service that runs the full suite.
  • .github/workflows/publish.yml runs on every push to main (and on manual dispatch with an optional version): it restores, builds, runs the full suite against PostgreSQL, packs and pushes the package to nuget.org with --skip-duplicate.
  • The published version comes from <Version> in src/MechaOnion/MechaOnion.csproj. To publish a new package, bump that value in the merge to main; without a bump the push is a no-op (--skip-duplicate).
  • Requires the repository secret NUGET_API_KEY (nuget.org API key scoped to push of the MechaOnion package). A manual run can override the version from the workflow inputs.

The user (or role) in the connection string needs permission to create databases: the demo acceptance test owns <database>_demo, created from the same connection string, so it never shares schema or configuration rows with the other integration tests.

The optional RabbitMQ end-to-end tests are skipped unless the Management API is configured:

MECHAONION_TEST_RABBITMQ_MANAGEMENT_URL="http://localhost:15672" \
MECHAONION_TEST_RABBITMQ_USER="guest" \
MECHAONION_TEST_RABBITMQ_PASSWORD="guest" \
  dotnet test tests/MechaOnion.Tests/MechaOnion.Tests.csproj --filter "FullyQualifiedName~RabbitMq"

Preview limitations

  • The library does not apply migrations, does not include ASP.NET Identity, social login, a database per tenant or automatic data migration.

License

MIT. See LICENSE.

Product Compatible and additional computed target framework versions.
.NET net10.0 is compatible.  net10.0-android was computed.  net10.0-browser was computed.  net10.0-ios was computed.  net10.0-maccatalyst was computed.  net10.0-macos was computed.  net10.0-tvos was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
0.4.0-preview 50 11/20/2026
0.3.0-preview 59 11/18/2026
0.2.0-preview 55 11/17/2026
0.1.0-preview 82 11/8/2026