Repository navigation
Expand file tree
/
Copy pathProgram.cs
More file actions
284 lines (248 loc) · 13 KB
/
Copy pathProgram.cs
File metadata and controls
284 lines (248 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
using System.Text;
using System.Text.Json;
using VerifyBlind.Server;
using VerifyBlind.TestPortal.Services;
DotNetEnv.Env.Load();
var builder = WebApplication.CreateBuilder(args);
// ── Sentry ──────────────────────────────────────────────────────────────────
// 3 example portal (nextjs/dotnet/php) tek "verifyblind-examples" projesine raporlar;
// example_stack tag'i hangisi olduğunu ayırır. DSN yoksa Sentry no-op kalır.
builder.WebHost.UseSentry(o =>
{
o.Dsn = Environment.GetEnvironmentVariable("EXAMPLES_SENTRY_DSN") ?? "";
o.Environment = builder.Environment.EnvironmentName;
o.TracesSampleRate = 0.1;
o.SendDefaultPii = false;
o.SetBeforeSend((Sentry.SentryEvent e) =>
{
e.SetTag("example_stack", "dotnet");
return e;
});
});
// ──────────────────────────────────────────────────────────────────────────
builder.Services.AddRazorPages();
builder.Services.AddHttpClient();
// Demo nonce store for PoP login replay protection (use Redis or a shared DB in
// production). In-memory only works single-instance.
builder.Services.AddSingleton<InMemoryTtlStore>();
// Fixed partner callback keypair (env-held). Lazy: only constructed when a callback
// endpoint is first hit, so the app still boots if CALLBACK_PRIVATE_KEY is unset.
builder.Services.AddSingleton<CallbackKeyProvider>();
// VerifyBlind.Server (NuGet): webhook signature, callback decryption, enclave signature,
// single-use nonce and the asked-condition check. One instance; it caches the public keys.
// This portal is a TEST partner, so the demo card is accepted (a real site leaves it off).
builder.Services.AddVerifyBlind(o =>
{
var apiUrl = Environment.GetEnvironmentVariable("VERIFYBLIND_API_URL");
if (!string.IsNullOrWhiteSpace(apiUrl)) o.ApiBaseUrl = apiUrl;
o.AllowTestCards = true;
});
var app = builder.Build();
// ── Sentry açılış ping'i (sağlık kontrolü) ─────────────────────────────────
// Her açılışta tek Info event'i; example_stack=dotnet tag'i BeforeSend ile eklenir.
Sentry.SentrySdk.CaptureMessage("[startup] example-web-dotnet up", Sentry.SentryLevel.Info);
// /net alt yolu altında sunulduğunda doğru URL üretimi için
app.UsePathBase("/net");
// Statik index.html'i / icin default file olarak serve et (widget)
app.UseDefaultFiles();
app.UseStaticFiles();
app.MapRazorPages();
// ─── POST /api/generate (callback modu) ──────────────────────────────────────
// SDK'dan { validations, additional_data? } alir; VerifyBlind pop/generate'e KENDI
// public key'ini + callback_url'ini ekleyerek gonderir; SDK'ya { nonce, pk_hash } doner.
app.MapPost("/api/generate", async (HttpContext ctx, IHttpClientFactory httpClientFactory,
InMemoryTtlStore store, CallbackKeyProvider keys) =>
{
var apiKey = Environment.GetEnvironmentVariable("TEST_VERIFYBLIND_API_KEY") ?? "";
var apiUrl = Environment.GetEnvironmentVariable("VERIFYBLIND_API_URL") ?? "https://api.verifyblind.com";
var callbackUrl = Environment.GetEnvironmentVariable("CALLBACK_URL") ?? "";
if (string.IsNullOrEmpty(apiKey) || string.IsNullOrEmpty(callbackUrl))
{
ctx.Response.StatusCode = 500;
await ctx.Response.WriteAsJsonAsync(new { error = "TEST_VERIFYBLIND_API_KEY / CALLBACK_URL yapılandırılmamış" });
return;
}
// ── What to ask is decided by the SERVER ─────────────────────────────────────
// The enclave signs `validations.age: true|false`, i.e. the answer to the condition it was
// ASKED. The browser body can be edited in DevTools: if this endpoint forwarded the browser's
// `validations`, a visitor could ask "1+" instead of "18+" and get a genuinely signed `age: true`.
//
// A REAL SITE sets validations from its own server configuration and ignores the browser's, e.g.
// var validations = new Dictionary<string, object> { ["age"] = "18+", ["user_id"] = true };
//
// This demo lets the visitor tick what to verify, so it accepts the browser's choice ONLY from
// the allow-list in PickAsked (bottom of this file). What was asked is stored with the nonce;
// /api/callback reads the signed result against that STORED condition.
var browserBody = await new StreamReader(ctx.Request.Body).ReadToEndAsync();
VerifyBlindAsked? asked = new();
object? additionalData = null;
try
{
using var d = JsonDocument.Parse(string.IsNullOrWhiteSpace(browserBody) ? "{}" : browserBody);
if (d.RootElement.TryGetProperty("validations", out var v))
asked = PickAsked(v);
if (d.RootElement.TryGetProperty("additional_data", out var a))
additionalData = JsonSerializer.Deserialize<object>(a.GetRawText());
}
catch { /* bos/hatali govde → hicbir sey sorulmaz */ }
if (asked is null)
{
ctx.Response.StatusCode = 400;
await ctx.Response.WriteAsJsonAsync(new { error = "Bu demoda yalnız 18+ ve user_id sorulabilir" });
return;
}
var upstream = JsonSerializer.Serialize(new
{
public_key = keys.PublicKeyBase64,
callback_url = callbackUrl,
validations = JsonSerializer.Deserialize<JsonElement>(asked.ToJson()),
additional_data = additionalData
});
var httpClient = httpClientFactory.CreateClient();
var request = new HttpRequestMessage(HttpMethod.Post, $"{apiUrl}/api/pop/generate");
request.Headers.Add("X-API-Key", apiKey);
var acceptLang = ctx.Request.Headers.AcceptLanguage.ToString();
request.Headers.TryAddWithoutValidation("Accept-Language", string.IsNullOrEmpty(acceptLang) ? "tr" : acceptLang);
request.Content = new StringContent(upstream, Encoding.UTF8, "application/json");
var response = await httpClient.SendAsync(request);
var responseBody = await response.Content.ReadAsStringAsync();
if (!response.IsSuccessStatusCode)
{
ctx.Response.StatusCode = (int)response.StatusCode;
ctx.Response.ContentType = "application/json";
await ctx.Response.WriteAsync(responseBody);
return;
}
string? nonce = null;
try
{
using var doc = System.Text.Json.JsonDocument.Parse(responseBody);
if (doc.RootElement.TryGetProperty("nonce", out var nEl)) nonce = nEl.GetString();
}
catch { /* handled below */ }
if (string.IsNullOrEmpty(nonce))
{
ctx.Response.StatusCode = 502;
await ctx.Response.WriteAsJsonAsync(new { error = "VerifyBlind nonce döndürmedi" });
return;
}
// Webhook gelene kadar 'pending'; QR tarama penceresi ~10 dk.
store.Set($"cbresult:{nonce}", "{\"status\":\"pending\"}", 600);
// Sorulan koşulu nonce ile birlikte sakla — callback sonucu buna göre okur (TTL = QR ömrü + pay).
store.Set($"asked:{nonce}", asked.ToJson(), 960);
app.Logger.LogInformation("[Generate-callback] nonce={Nonce} pk_hash={PkHash}", nonce, keys.PkHashHex[..8]);
await ctx.Response.WriteAsJsonAsync(new { nonce, pk_hash = keys.PkHashHex });
});
// ─── POST /api/callback (VerifyBlind webhook alıcısı) ────────────────────────
// VerifyBlind.Server tek çağrıda: timestamp tazeligi (±300 sn) → webhook imzasi (RSA-PSS,
// VerifyBlind webhook public key) → decrypt (kendi private key) → enclave imzasi → imzali
// nonce == webhook nonce'u. Sonra nonce'u bir kez tuketip sonucu SORDUGUMUZ kosula gore okur.
// Sonuc nonce'a gore saklanir; statusUrl bunu poll eder.
app.MapPost("/api/callback", async (HttpRequest request, IVerifyBlindVerifier verifier,
InMemoryTtlStore store, CallbackKeyProvider keys) =>
{
CallbackResult r;
try
{
r = await verifier.VerifyCallbackAsync(request.Body,
request.Headers["X-Webhook-Signature"], request.Headers["X-Webhook-Timestamp"], keys.Key);
}
catch (VerifyBlindException e) when (WebhookRejection(e) is { } rejected)
{
app.Logger.LogWarning("[Callback] Webhook reddedildi ({Code})", e.Code);
return rejected;
}
catch (VerifyBlindException e)
{
// Webhook imzasi gecerli ama icerik cozulemedi / enclave imzasi tutmadi.
app.Logger.LogWarning("[Callback] Sonuç saklanmadı ({Code})", e.Code);
return Results.Ok(); // webhook'u onayla ama sonucu saklama
}
// Iptal callback'i
if (r.Status == CallbackStatus.Cancelled)
{
store.Set($"cbresult:{r.Nonce}",
JsonSerializer.Serialize(new { status = "cancelled", reason = r.Reason }), 600);
return Results.Ok();
}
// Sonucu generate'te SORDUGUMUZ kosula gore oku (nonce ile saklanan), tarayicinin
// soyledigine gore degil. Tek kullanimlik: okununca silinir.
var outcome = await verifier.ConsumeAndCheckAsync(r.Verified!,
nonce => Task.FromResult(store.GetAndRemove($"asked:{nonce}")));
if (!outcome.Ok)
{
app.Logger.LogWarning("[Callback] Sonuç reddedildi ({Code}), nonce={Nonce}", outcome.Error.Code, r.Nonce);
return Results.Ok(); // webhook'u onayla ama sonucu saklama
}
// data = enclave imzali ic yuk: { nonce, validations:{...}, additional_data? }
store.Set($"cbresult:{r.Nonce}",
JsonSerializer.Serialize(new { status = "completed", data = outcome.Result.Payload }), 600);
app.Logger.LogInformation("[Callback] ✅ nonce={Nonce} çözüldü + imza doğrulandı", r.Nonce);
return Results.Ok();
});
// ─── GET /api/status/{nonce} (SDK statusUrl bunu poll eder) ──────────────────
app.MapGet("/api/status/{nonce}", (string nonce, InMemoryTtlStore store) =>
{
var stored = store.Get($"cbresult:{nonce}");
return Results.Content(stored ?? "{\"status\":\"pending\"}", "application/json");
});
// ─── POST /api/revoke (VerifyBlind revoke webhook alıcısı) ───────────────────
// Kullanici mobil app'ten dogrulamayi geri cektiginde VerifyBlind buraya IMZALI bir
// webhook POST eder: { nonce, partner_id } (callback ile AYNI RSA-PSS imzasi).
// Referans deseni: once IMZAYI DOGRULA, sonra bu nonce'a bagli sakladigin veriyi SIL.
app.MapPost("/api/revoke", async (HttpRequest request, IVerifyBlindVerifier verifier) =>
{
WebhookBody body;
try
{
body = await verifier.VerifyRevokeAsync(request.Body,
request.Headers["X-Webhook-Signature"], request.Headers["X-Webhook-Timestamp"]);
}
catch (VerifyBlindException e) when (WebhookRejection(e) is { } rejected)
{
app.Logger.LogWarning("[Revoke] Webhook reddedildi ({Code})", e.Code);
return rejected;
}
catch (VerifyBlindException e)
{
app.Logger.LogWarning("[Revoke] İmzalı gövde okunamadı ({Code})", e.Code);
return Results.Ok();
}
// TODO partner: burada bu nonce'a bagli sakladigin kullanici verisini SIL (KVKK geri cekme).
// Bu ornek dogrulama sonucunu kalici saklamadigindan (cbresult:{nonce} 600s sonra ucar)
// silinecek kalici veri yok — yalniz imzayi dogrulayip 200 ile ack'liyoruz.
app.Logger.LogInformation("[Revoke] ✅ İmza doğrulandı, revoke ack, nonce={Nonce}", body.Nonce);
return Results.Ok();
});
app.Run();
// Webhook'un kendisi reddedildiyse (timestamp, imza, anahtar alinamadi) donulecek yanit;
// imza gecerliyse null. Govdeler eski el yazimi surumle ayni.
static IResult? WebhookRejection(VerifyBlindException e) => e.Code switch
{
VerifyBlindErrorCode.BadWebhookTimestamp => Results.Json(new { error = "stale timestamp" }, statusCode: 401),
VerifyBlindErrorCode.BadWebhookSignature => Results.Json(new { error = "invalid signature" }, statusCode: 401),
VerifyBlindErrorCode.KeyFetchFailed => Results.StatusCode(502),
_ => null,
};
// Demo sayfasi ziyaretcinin neyi dogrulatacagini secmesine izin verir; tarayicinin secimi YALNIZ
// bu listeden kabul edilir: age = "18+", user_id = true. Baska anahtar, baska yas kosulu ("1+"),
// true olmayan user_id ya da nesne olmayan deger → null (400). Gercek site tarayiciyi hic dinlemez.
static VerifyBlindAsked? PickAsked(JsonElement requested)
{
if (requested.ValueKind == JsonValueKind.Null) return new VerifyBlindAsked();
if (requested.ValueKind != JsonValueKind.Object) return null;
string? age = null;
var userId = false;
foreach (var prop in requested.EnumerateObject())
{
if (prop.Name == "age" && prop.Value.ValueKind == JsonValueKind.String && prop.Value.GetString() == "18+")
age = "18+";
else if (prop.Name == "user_id" && prop.Value.ValueKind == JsonValueKind.True)
userId = true;
else
return null;
}
return new VerifyBlindAsked { Age = age, UserId = userId };
}
// WebApplicationFactory<Program> (Tests/) icin.
public partial class Program { }