MechaOnion 0.3.0-preview
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
<PackageReference Include="MechaOnion" Version="0.3.0-preview" />
<PackageVersion Include="MechaOnion" Version="0.3.0-preview" />
<PackageReference Include="MechaOnion" />
paket add MechaOnion --version 0.3.0-preview
#r "nuget: MechaOnion, 0.3.0-preview"
#:package MechaOnion@0.3.0-preview
#addin nuget:?package=MechaOnion&version=0.3.0-preview&prerelease
#tool nuget:?package=MechaOnion&version=0.3.0-preview&prerelease
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.Tracingholds theTracingMetadataof 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 withtarget.WithTracingFrom(source). - Messaging: publications (queue, topic, batch and schedule) carry
traceparent/tracestatewith the local provider and RabbitMQ; consumers continue the flow and readcontext.Metadata.Tracing. Retries and dead letters stay in the same flow. - Logs: every event emitted in a step carries
tracing_id,step_idandorigin, plus aStep completedevent withduration_ms. - Responses and external calls never carry tracing metadata. The only exception is the
v1/MessagingAdminAPI, which exposestracingId,originandflowStartedAtper message to operators.
Internal HTTP clients (opt-in)
Outgoing propagation is disabled process-wide. The
Coremodule replaces the runtime propagator with the NoOutput one, so noHttpClientsendstraceparent/tracestate(webhooks, Mautic, third-party SDKs and your own clients included) unless it opts in. Do not pre-build HTTP handlers beforebuilder.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
IEmailDispatcherbefore deploying and check the migration notes inCHANGELOG.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:
ConfigItemrow of the tenant (Key = "TwoFactorSettings",TenantId = <tenant>);- global
ConfigItemrow (TenantId = ""); - the
TwoFactorSettingssection ofIConfiguration; - 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
ConfigItemrow wins overappsettings. If a global row exists, changingTwoFactorSettings:Enabledin the configuration file has no effect until the row is updated or removed. Persist overrides throughIConfigsService(the demo exposesPOST /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 (
Refreshkeeps the authenticated session). - Reverse proxies: the per-IP limit uses
HttpContext.Connection.RemoteIpAddress. Behind nginx/ingress withoutUseForwardedHeaders, every user shares the proxy IP and theMaxSendsPerIpWindowlimit can throttle the whole tenant. Configure forwarded headers in the host. - Logs carry
TwoFactorChallengeCreated,TwoFactorChallengeConsumed,TwoFactorChallengeResent,TwoFactorVerificationFailed,TwoFactorRateLimited(Scope = User|Ip|Resend),TwoFactorEmailDispatchFailed,TwoFactorAccountLocked,TwoFactorIpThrottledandTwoFactorChallengeInvalidated. 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:
X-Tenant-Idheadertenant_idclaimtenantIdroute valueMechaOnion:DefaultTenantId(fixed fallback)- 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
EnableSingleTenantFallbackdisabled. Requests without an explicit tenant keep returning400. - 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 with400. - Fixed tenant: set
DefaultTenantIdwhen 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 UIGET /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 islocalwhenMessagingSettings.Local=trueandrabbitmqwhenfalse; provider=localwithMessagingSettings.Local=falsereturns409 Conflict;provider=rabbitmqforces the external provider regardless ofMessagingSettings.Local;- an unknown
providerreturns400 Bad Request; - Management API errors never fall back silently to the local provider:
401/403unauthorized,404not found,409duplicate,502invalid response and503timeout/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
400citing the missing capability. - Individual message removal: the Management API cannot remove an arbitrary message;
the
rabbitmqprovider refuses with400. - 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 explicittarget, and the origin is removed withack_requeue_false. The operation is at-least-once; duplicates and concurrency are possible. Withoutx-deathand withouttarget, the response is400. - Credentials: they never appear in logs, responses or exceptions;
Authorizationis 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.ymlruns on every pull request, on pushes tomainand 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.ymlruns on every push tomain(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>insrc/MechaOnion/MechaOnion.csproj. To publish a new package, bump that value in the merge tomain; without a bump the push is a no-op (--skip-duplicate). - Requires the repository secret
NUGET_API_KEY(nuget.org API key scoped topushof theMechaOnionpackage). 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 | Versions 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. |
-
net10.0
- AutoMapper (= 14.0.0)
- DynamicLanguageRuntime (>= 1.3.5)
- Jint (>= 4.10.1)
- Microsoft.AspNetCore.Authentication.JwtBearer (>= 10.0.9)
- Microsoft.AspNetCore.OpenApi (>= 10.0.9)
- Microsoft.EntityFrameworkCore (>= 10.0.9)
- Microsoft.EntityFrameworkCore.Relational (>= 10.0.9)
- MoonSharp (>= 2.0.0)
- NCrontab.Signed (>= 3.4.0)
- Npgsql (>= 10.0.3)
- Npgsql.EntityFrameworkCore.PostgreSQL (>= 10.0.2)
- OpenTelemetry.Exporter.OpenTelemetryProtocol (>= 1.21.0)
- OpenTelemetry.Extensions.Hosting (>= 1.21.0)
- OpenTelemetry.Instrumentation.AspNetCore (>= 1.21.0)
- OpenTelemetry.Instrumentation.Http (>= 1.21.0)
- RabbitMQ.Client (>= 6.8.1)
- Scalar.AspNetCore (>= 2.16.7)
- Serilog (>= 4.3.1)
- Serilog.Enrichers.AspNetCore (>= 1.0.0)
- Serilog.Enrichers.Environment (>= 3.0.1)
- Serilog.Enrichers.Process (>= 3.0.0)
- Serilog.Sinks.Console (>= 6.1.1)
- Serilog.Sinks.OpenTelemetry (>= 4.2.0)
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 |