using System.Collections.Concurrent;
using System.Net.Http.Headers;
using System.Text.Json;
using ShieldLabs;
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
var domain = Guid.Parse(builder.Configuration["SHIELDLABS_DOMAIN_ID"]!).ToString();
var apiKey = builder.Configuration["SHIELDLABS_API_KEY"] ?? throw new InvalidOperationException("Missing API key");
var secret = builder.Configuration["SHIELDLABS_WEBHOOK_SECRET"] ?? throw new InvalidOperationException("Missing webhook secret");
using var http = new HttpClient(new HttpClientHandler { AllowAutoRedirect = false }) { Timeout = TimeSpan.FromSeconds(5) };
var used = new ConcurrentDictionary<string, byte>(); // demonstration only; use shared durable storage
app.MapPost("/signup", async (SignupForm form, CancellationToken cancellationToken) =>
{
if (!Guid.TryParse(form.IdentificationId, out var parsedId)) return Results.BadRequest();
var id = parsedId.ToString();
try
{
using var request = new HttpRequestMessage(HttpMethod.Get,
"https://account.shieldlabs.ai/api/v1/domains/" + domain + "/history/identifications/" + id);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
using var response = await http.SendAsync(request, cancellationToken);
if (!response.IsSuccessStatusCode) return Results.Json(new { error = "unverified" }, statusCode: 503);
using var body = JsonDocument.Parse(await response.Content.ReadAsStringAsync(cancellationToken));
var card = body.RootElement.GetProperty("data");
if (card.GetProperty("id").GetString() != id || card.GetProperty("domain_id").GetString() != domain
|| card.GetProperty("type").GetString() != "identification") return Results.StatusCode(403);
var risk = card.GetProperty("risk");
var signals = card.GetProperty("signals");
if (risk.GetProperty("state").GetString() != "ok" || signals.GetProperty("state").GetString() != "ok"
|| !risk.GetProperty("score").TryGetDouble(out var score) || !double.IsFinite(score)
|| score < 0 || score > 100 || signals.GetProperty("items").ValueKind != JsonValueKind.Array) return Results.StatusCode(403);
var band = score < 30 ? "trusted" : score < 60 ? "suspicious" : "dangerous";
if (risk.GetProperty("band").GetString() != band || score >= 60) return Results.StatusCode(403);
foreach (var signal in signals.GetProperty("items").EnumerateArray())
if (signal.ValueKind != JsonValueKind.String || signal.GetString() is "banned_ip" or "browser_automation") return Results.StatusCode(403);
if (!card.GetProperty("created_at").TryGetDateTimeOffset(out var created)) return Results.StatusCode(403);
var age = DateTimeOffset.UtcNow - created;
if (age < TimeSpan.Zero || age > TimeSpan.FromMinutes(5)) return Results.StatusCode(403);
// For signed-in actions, compare card.user_hid to the server-generated HID of the authenticated account here.
if (!used.TryAdd(domain + ":" + id, 0)) return Results.StatusCode(403);
return Results.Ok(new { ok = true, band }); // perform the signup after your other validation
}
catch (Exception error) when (error is HttpRequestException or TaskCanceledException or JsonException or InvalidOperationException or KeyNotFoundException)
{
return Results.Json(new { error = "unverified" }, statusCode: 503);
}
});
app.Run();
// Call this from your webhook route, then durably enqueue the returned envelope before 2xx.
public static class ShieldLabsWebhookVerifier
{
public static JsonElement VerifyWebhook(byte[] bytes, string? signature, string secret)
{
if (secret.Length == 0) throw new InvalidOperationException("Missing webhook secret");
if (!WebhookSignature.Verify(bytes, signature, secret)) throw new InvalidOperationException("Invalid signature");
using var envelope = JsonDocument.Parse(bytes);
var eventId = envelope.RootElement.GetProperty("event_id").GetString();
if (string.IsNullOrEmpty(eventId)) throw new JsonException("Missing event_id");
return envelope.RootElement.Clone();
}
}
record SignupForm(string? IdentificationId);