Altcha.Net est une librairie .NET open-source communautaire et non officielle pour utiliser ALTCHA en mode proof-of-work auto-heberge.
Elle ne depend pas d'ALTCHA Sentinel, n'appelle aucune API ALTCHA externe et vise les applications modernes comme les sites legacy ASP.NET Framework 4.8.
Altcha.Net fournit un captcha proof-of-work simple. Ce n'est pas une solution anti-spam ou anti-bot complete.
dotnet add package Altcha.NetPackage ASP.NET Core optionnel:
dotnet add package Altcha.Net.AspNetCoreLa cible .NET Framework 4.8 n'ajoute pas System.Text.Json ni Microsoft.Bcl.AsyncInterfaces. La cible .NET Standard 2.0 reference System.Text.Json sur la ligne 8.0.x (8.0.6); .NET 10 utilise le framework partage.
using Altcha.Net;
using Altcha.Net.AspNetCore;
builder.Services.AddAltcha(options =>
{
options.SecretKey = builder.Configuration["Altcha:SecretKey"]!;
options.ChallengeExpiry = TimeSpan.FromMinutes(2);
options.AllowedClockSkew = TimeSpan.FromSeconds(10);
options.Complexity = new AltchaComplexity(50000, 100000);
});
app.MapAltchaChallenge("/altcha/challenge");Pour utiliser un cache partage:
builder.Services.AddDistributedMemoryCache();
builder.Services.AddAltcha(builder.Configuration.GetSection("Altcha"));
builder.Services.AddDistributedAltchaReplayStore();Mode atomique strict (recommande en multi-instance) avec un backend qui supporte une operation de type SET key value NX EX:
builder.Services.AddStackExchangeRedisCache(options =>
{
options.Configuration = builder.Configuration.GetConnectionString("Redis");
});
builder.Services.AddSingleton<IAtomicAltchaReplayStore, RedisAtomicAltchaReplayStore>();
builder.Services.AddAltcha(builder.Configuration.GetSection("Altcha"));
builder.Services.AddDistributedAltchaReplayStore(DistributedAltchaReplayStoreMode.StrictAtomic);DistributedCacheAltchaReplayStore utilise IDistributedCache. Cette abstraction ne garantit pas une insertion atomique pour tous les providers.
L'endpoint challenge peut etre durci avec des conventions optionnelles:
using Altcha.Net;
using Altcha.Net.AspNetCore;
using Microsoft.AspNetCore.RateLimiting;
using System.Threading.RateLimiting;
builder.Services.AddAltcha(builder.Configuration.GetSection("Altcha"));
builder.Services.AddRateLimiter(options =>
{
options.AddFixedWindowLimiter("altcha-challenge", limiter =>
{
limiter.PermitLimit = 30;
limiter.Window = TimeSpan.FromMinutes(1);
limiter.QueueLimit = 0;
});
});
var app = builder.Build();
app.UseRateLimiter();
app.MapAltchaChallenge("/altcha/challenge", security =>
{
security.RateLimitingPolicyName = "altcha-challenge";
security.AllowedHosts = ["example.com", "www.example.com"];
// Cache-Control: no-store est active par defaut.
});Exemple Minimal API pour valider un formulaire:
app.MapPost("/contact", async (HttpRequest request, AltchaService altchaService, CancellationToken ct) =>
{
var form = await request.ReadFormAsync(ct);
var result = altchaService.ValidateResponse(form["altcha"]);
if (!result.IsValid)
{
return Results.BadRequest(new { error = result.Error.ToString() });
}
return Results.Ok();
});Exemple minimal sans rate limiter (seulement Cache-Control: no-store):
app.MapAltchaChallenge("/altcha/challenge");using Altcha.Net;
var service = new AltchaService(new AltchaOptions
{
SecretKey = Environment.GetEnvironmentVariable("ALTCHA_SECRET")!,
ChallengeExpiry = TimeSpan.FromMinutes(2),
AllowedClockSkew = TimeSpan.FromSeconds(10),
Complexity = new AltchaComplexity(50000, 100000)
}, new MemoryAltchaReplayStore());Endpoint challenge MVC:
public ActionResult Challenge()
{
return Content(AltchaProvider.Service.GenerateChallenge().ToJson(), "application/json");
}Validation POST:
var result = AltchaProvider.Service.ValidateResponse(Request.Form["altcha"]);
if (!result.IsValid)
{
ModelState.AddModelError("", "Validation ALTCHA invalide.");
return View(model);
}Des exemples sont disponibles dans:
examples/Altcha.Net.Examples.AspNetMvc.CSharpexamples/Altcha.Net.Examples.AspNetWebForms.VbNetexamples/Altcha.Net.Examples.AspNetCore.MinimalApi
Hebergez le script du widget ALTCHA dans votre application, puis pointez challenge vers votre endpoint local.
<script async defer src="/scripts/altcha.min.js" type="module"></script>
<form method="post" action="/Contact/Submit">
<input name="email" type="email" required>
<textarea name="message" required></textarea>
<altcha-widget challenge="/altcha/challenge"></altcha-widget>
<button type="submit">Envoyer</button>
</form>Le widget poste un champ de formulaire altcha contenant un JSON encode en Base64.
SecretKey: cle HMAC serveur. Ne jamais l'exposer au navigateur.ChallengeExpiry: duree de validite courte, par defaut 2 minutes.Complexity: plage du nombre proof-of-work, par defaut50000..100000.AllowedClockSkew: marge de tolerance inter-noeuds pour l'expiration, par defaut 10 secondes (recommande entre 5 et 30 secondes avec NTP actif).IAltchaReplayStore: store anti-replay.Algorithm: seulSHA-256est supporte actuellement.
- Stocker
SecretKeydans un secret manager ou une variable d'environnement. - Servir le site en HTTPS.
- Garder une expiration courte.
- Synchroniser les horloges serveurs via NTP (chrony/systemd-timesyncd/Windows Time) pour limiter le skew.
- Ne pas logger les payloads ALTCHA complets ni la cle secrete.
- Utiliser un store partage en multi-instance.
- Eviter
MemoryAltchaReplayStoreen production multi-serveur. AddDistributedAltchaReplayStore(DistributedAltchaReplayStoreMode.BestEffort)utiliseIDistributedCacheen fallback best effort: anti-replay non strictement atomique.AddDistributedAltchaReplayStore(DistributedAltchaReplayStoreMode.StrictAtomic)exigeIAtomicAltchaReplayStoreet garantit un "insert-if-absent" atomique entre workers (ex: RedisSET ... NX EX).
- Pas d'integration ALTCHA Sentinel.
- Pas de spam filter API ALTCHA.
- Proof-of-work uniquement.
- SHA-256 uniquement.
- Pas de Redis integre.
IDistributedCachene fournit pas toujours une atomicite stricte.
Altcha.Net est une implementation communautaire non officielle. Ce projet n'est pas affilie, approuve ou sponsorise par ALTCHA.
dotnet restore Altcha.Net.sln
dotnet build Altcha.Net.sln --configuration Release
dotnet test Altcha.Net.sln --configuration Release
dotnet pack src/Altcha.Net/Altcha.Net.csproj --configuration Release --output artifacts
dotnet pack src/Altcha.Net.AspNetCore/Altcha.Net.AspNetCore.csproj --configuration Release --output artifacts