|
| 1 | +using System.Security.Cryptography; |
| 2 | +using System.Text; |
| 3 | + |
| 4 | +var builder = WebApplication.CreateBuilder(args); |
| 5 | + |
| 6 | +var app = builder.Build(); |
| 7 | + |
| 8 | +const string HOOKDECK_SIGNATURE_HEADER = "X-Hookdeck-Signature"; |
| 9 | +const string HOOKDECK_WEBHOOK_SECRET_CONFIG_KEY = "inbound:HookdeckWebhookSecret"; |
| 10 | + |
| 11 | +string WEBHOOK_SECRET = builder.Configuration[HOOKDECK_WEBHOOK_SECRET_CONFIG_KEY] ?? string.Empty; |
| 12 | + |
| 13 | +static bool VerifyHmacWebhookSignature(HttpContext context, string webhookSecret, string rawBody) |
| 14 | +{ |
| 15 | + if(string.IsNullOrEmpty(webhookSecret)) |
| 16 | + { |
| 17 | + Console.WriteLine("WARNING: Missing webhook secret. Skipping verification."); |
| 18 | + return true; |
| 19 | + } |
| 20 | + |
| 21 | + string? hmacHeader = context.Request.Headers[HOOKDECK_SIGNATURE_HEADER].FirstOrDefault(); |
| 22 | + |
| 23 | + if (string.IsNullOrEmpty(hmacHeader)) |
| 24 | + { |
| 25 | + Console.WriteLine("Missing HMAC headers"); |
| 26 | + return false; |
| 27 | + } |
| 28 | + HMACSHA256 hmac = new(Encoding.UTF8.GetBytes(webhookSecret)); |
| 29 | + string hash = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(rawBody))); |
| 30 | + |
| 31 | + return hash.Equals(hmacHeader); |
| 32 | +} |
| 33 | + |
| 34 | +app.MapPost("/{**path}", async (string? path, HttpContext context) => |
| 35 | +{ |
| 36 | + using StreamReader reader = new StreamReader(context.Request.Body); |
| 37 | + string rawBody = await reader.ReadToEndAsync(); |
| 38 | + |
| 39 | + bool verified = VerifyHmacWebhookSignature(context, WEBHOOK_SECRET, rawBody); |
| 40 | + if(!verified) |
| 41 | + { |
| 42 | + return Results.Unauthorized(); |
| 43 | + } |
| 44 | + |
| 45 | + Console.WriteLine(new |
| 46 | + { |
| 47 | + webhook_received = DateTime.UtcNow.ToString("o"), |
| 48 | + body = rawBody |
| 49 | + }); |
| 50 | + |
| 51 | + return Results.Json(new { |
| 52 | + STATUS = "ACCEPTED" |
| 53 | + }); |
| 54 | +}); |
| 55 | + |
| 56 | +app.UseRouting(); |
| 57 | + |
| 58 | +app.Run(); |
0 commit comments