-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
518 lines (436 loc) · 22.8 KB
/
Copy pathProgram.cs
File metadata and controls
518 lines (436 loc) · 22.8 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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.RateLimiting;
using Blazored.SessionStorage;
using Blazored.LocalStorage;
using NovinCRM.Components; // App lives in NovinCRM.Components (namespace preserved)
using NovinCRM.Infrastructure.Authorization;
using NovinCRM.Infrastructure.Http; // ShecanDnsHttpClientHandler namespace (file moved, namespace preserved)
using NovinCRM.Infrastructure.Logging;
using NovinCRM.Infrastructure.Services;
using NovinCRM.Infrastructure.State;
using NovinCRM.Infrastructure.Sync;
using NovinCRM.Infrastructure.Webhooks;
using NovinCRM.Presentation.Webhooks;
using Microsoft.EntityFrameworkCore;
using NovinCRM.Application.Features.CRM.Commerce;
using NovinCRM.Application.Features.CRM.EventHandlers;
using NovinCRM.Infrastructure.Backup;
using NovinCRM.Infrastructure.HubSpot.CRM.Commerce;
using NovinCRM.Infrastructure.Persistence;
using NovinCRM.Services.Admin;
using NovinCRM.Services.Auth;
using NovinCRM.Services.UserPanel;
using NovinCRM.State.Admin;
using DotNetEnv;
using Microsoft.AspNetCore.Localization;
using System.Globalization;
using NovinCRM.Localization.Extensions;
var builder = WebApplication.CreateBuilder(args);
// Load .env file if it exists (development convenience only — not for production)
var envPath = Path.Combine(Directory.GetCurrentDirectory(), ".env");
if (File.Exists(envPath))
{
Env.Load(envPath);
}
// Configuration — sources ordered by ascending priority:
// appsettings.json (base, no secrets) → appsettings.{env}.json → environment variables → user secrets
builder.Configuration
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.AddUserSecrets<Program>(optional: true);
// ── Sentry — error monitoring, tracing, and structured logs ──────────────────
builder.WebHost.UseSentry(o =>
{
o.Dsn = "https://3c72551a13dba31fa8fea00b077170cc@o4508578883895296.ingest.de.sentry.io/4511738441498704";
// Disable verbose SDK debug output in production
o.Debug = !builder.Environment.IsProduction();
// Capture 100% of transactions for tracing (tune down in production as needed)
o.TracesSampleRate = 1.0;
// Forward ASP.NET Core log entries to Sentry
o.EnableLogs = true;
});
// Configure Kestrel for production (HTTP only) and development (HTTPS)
builder.WebHost.ConfigureKestrel(options =>
{
if (builder.Environment.IsProduction())
{
// Production: HTTP only on port 5000 (Liara/Docker)
options.ListenAnyIP(5000);
}
// Development uses default HTTPS configuration from launchSettings.json
});
// Data Protection — platform-managed key storage and rotation.
// Keys are stored in the default location (user profile / container volume).
// Do NOT configure a persistence path to a path that is excluded from backups
// without understanding the consequences for encrypted data.
builder.Services.AddDataProtection();
// Logging - optimized for production
builder.Logging.ClearProviders();
builder.Logging.AddConsole();
builder.Logging.AddDebug();
if (builder.Environment.IsProduction())
{
builder.Logging.AddFilter("Microsoft", LogLevel.Warning);
builder.Logging.AddFilter("System", LogLevel.Warning);
builder.Logging.SetMinimumLevel(LogLevel.Information);
}
else
{
builder.Logging.SetMinimumLevel(LogLevel.Debug);
}
// ── ASP.NET Core built-in localization (for middleware/cookie culture provider) ────────────────
builder.Services.AddLocalization(options => options.ResourcesPath = "Resources");
var supportedCultures = new[] { new CultureInfo("fa-IR"), new CultureInfo("en-US") };
builder.Services.Configure<RequestLocalizationOptions>(options =>
{
options.DefaultRequestCulture = new RequestCulture("fa-IR");
options.SupportedCultures = supportedCultures;
options.SupportedUICultures = supportedCultures;
});
// ── NovinCRM JSON localization system ────────────────────────────────────────────────────────
builder.Services.AddNovinCRMLocalization();
// Enable hot-reload in Development for instant JSON edits
if (builder.Environment.IsDevelopment())
builder.Services.EnableLocalizationHotReload();
// Response compression for better performance
builder.Services.AddResponseCompression(options =>
{
options.EnableForHttps = true;
});
// ── Correlation ID service ─────────────────────────────────────────────────
// Singleton: the AsyncLocal<> inside CorrelationIdService is per-execution-context,
// so one singleton instance works correctly across all concurrent requests.
builder.Services.AddSingleton<CorrelationIdService>();
// Razor Components
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();
// Storage: Session + Local (for remember-me / persistence)
builder.Services.AddBlazoredSessionStorage();
builder.Services.AddBlazoredLocalStorage();
builder.Services.AddScoped<INavigationService, NavigationService>();
builder.Services.AddSingleton<ToastService>();
builder.Services.AddScoped<NovinCRM.Infrastructure.Services.IDialogService, DialogServiceWrapper>();
builder.Services.AddScoped<NovinCRM.Infrastructure.Services.ISessionStorageService, SessionStorageServiceWrapper>();
builder.Services.AddScoped<NovinCRM.Infrastructure.Services.ILocalStorageService, LocalStorageServiceWrapper>();
// AuthenticationStateService — scoped: each Blazor circuit gets its own instance
// with its own in-memory state, backed by IDistributedCache for cross-restart durability.
builder.Services.AddScoped<AuthenticationStateService>();
// Admin Services
builder.Services.AddScoped<AdminAuthorizationHandler>();
builder.Services.AddScoped<AdminStateService>();
builder.Services.AddScoped<AdminOwnerService>();
builder.Services.AddScoped<DashboardService>();
builder.Services.AddScoped<KanbanService>();
// Authentication Service
builder.Services.AddScoped<AuthService>();
// ── HubSpot token validation — fail-fast on startup ─────────────────────
// Resolved once, before DI container is built, so a missing token causes an
// immediate startup error rather than a confusing 401 at runtime.
var hubSpotToken = Environment.GetEnvironmentVariable("HUBSPOT_TOKEN")
?? builder.Configuration["HubSpot:Token"]
?? throw new InvalidOperationException(
"HubSpot:Token is required. Set the HUBSPOT_TOKEN environment variable or " +
"HubSpot:Token in configuration.");
// HttpClient with Shecan
builder.Services.AddHttpClient("HubSpot", (sp, client) =>
{
client.BaseAddress = new Uri("https://api.hubapi.com");
client.Timeout = TimeSpan.FromSeconds(30);
// Authorization header value is set but never written to logs
// (SanitizingLoggingHandler strips it before any log sink sees it).
client.DefaultRequestHeaders.Add("Authorization", $"Bearer {hubSpotToken}");
client.DefaultRequestHeaders.Add("Accept", "application/json");
})
.ConfigurePrimaryHttpMessageHandler(() => new ShecanDnsHttpClientHandler())
.AddHttpMessageHandler<SanitizingLoggingHandler>();
// Register the sanitizing handler so DI can inject it
builder.Services.AddTransient<SanitizingLoggingHandler>();
// Zohal API
builder.Services.AddHttpClient<NovinCRM.Services.Identity.ZohalService>((sp, client) =>
{
client.BaseAddress = new Uri("https://service.zohal.io");
client.Timeout = TimeSpan.FromSeconds(30);
})
.ConfigurePrimaryHttpMessageHandler(() => new ShecanDnsHttpClientHandler());
// Liara API
builder.Services.AddHttpClient<NovinCRM.Services.Utils.LiaraApiService>((sp, client) =>
{
client.BaseAddress = new Uri("https://api.iran.liara.ir");
client.Timeout = TimeSpan.FromSeconds(15);
});
// User Panel Services
builder.Services.AddScoped<IUserPanelService, UserPanelService>();
builder.Services.AddScoped<DealDetailService>();
// CRM Services
builder.Services.AddScoped<NovinCRM.Services.CRM.Objects.Contact>();
builder.Services.AddScoped<NovinCRM.Services.CRM.Objects.Deal>();
builder.Services.AddScoped<NovinCRM.Services.CRM.Objects.Company>();
builder.Services.AddScoped<NovinCRM.Services.CRM.Objects.Ticket>();
builder.Services.AddScoped<NovinCRM.Services.CRM.Engagements.Notes>();
builder.Services.AddScoped<NovinCRM.Services.CRM.Associate>();
builder.Services.AddScoped<NovinCRM.Services.CRM.ContactUpdateService>();
builder.Services.AddHttpClient<NovinCRM.Services.CRM.Commerce.Product>((sp, client) =>
{
client.BaseAddress = new Uri("https://api.hubapi.com");
client.Timeout = TimeSpan.FromSeconds(30);
})
.ConfigurePrimaryHttpMessageHandler(() => new ShecanDnsHttpClientHandler());
builder.Services.AddHttpClient<NovinCRM.Services.CRM.Commerce.LineItem>((sp, client) =>
{
client.BaseAddress = new Uri("https://api.hubapi.com");
client.Timeout = TimeSpan.FromSeconds(30);
})
.ConfigurePrimaryHttpMessageHandler(() => new ShecanDnsHttpClientHandler());
builder.Services.AddScoped<NovinCRM.Services.CRM.Pipelines>();
builder.Services.AddScoped<NovinCRM.Services.CRM.Associate>();
builder.Services.AddScoped<NovinCRM.Services.CRM.Owners>();
// SMS
builder.Services.AddHttpClient<NovinCRM.Services.SMS.SmsIr>((sp, client) =>
{
client.BaseAddress = new Uri("https://api.sms.ir");
client.Timeout = TimeSpan.FromSeconds(30);
})
.ConfigurePrimaryHttpMessageHandler(() => new ShecanDnsHttpClientHandler());
builder.Services.AddScoped<NovinCRM.Services.SMS.SMS.Send>();
// IPPanel Edge API
builder.Services.AddHttpClient<NovinCRM.Services.SMS.IpPanelClient>((sp, client) =>
{
client.BaseAddress = new Uri(NovinCRM.Services.SMS.IpPanelClient.BaseUrl);
client.Timeout = TimeSpan.FromSeconds(30);
client.DefaultRequestHeaders.Add("User-Agent", "NovinCRM-IPPanel-Client/1.0");
})
.ConfigurePrimaryHttpMessageHandler(() => new ShecanDnsHttpClientHandler());
// Register each provider as both its concrete type (for HttpClient wiring) AND
// as a keyed ISmsService so SmsServiceFactory can resolve by config string key.
builder.Services.AddScoped<NovinCRM.Services.SMS.SmsIrService>();
builder.Services.AddScoped<NovinCRM.Services.SMS.FarazSmsService>();
builder.Services.AddScoped<NovinCRM.Services.SMS.IpPanelSmsService>();
builder.Services.AddKeyedScoped<NovinCRM.Services.SMS.ISmsService,
NovinCRM.Services.SMS.SmsIrService>(NovinCRM.Services.SMS.SmsServiceFactory.KeySmsIr);
builder.Services.AddKeyedScoped<NovinCRM.Services.SMS.ISmsService,
NovinCRM.Services.SMS.FarazSmsService>(NovinCRM.Services.SMS.SmsServiceFactory.KeyFarazSms);
builder.Services.AddKeyedScoped<NovinCRM.Services.SMS.ISmsService,
NovinCRM.Services.SMS.IpPanelSmsService>(NovinCRM.Services.SMS.SmsServiceFactory.KeyIpPanel);
builder.Services.AddScoped<NovinCRM.Services.SMS.SmsServiceFactory>();
builder.Services.AddScoped<NovinCRM.Services.SMS.ISmsService, NovinCRM.Services.SMS.SmsService>();
builder.Services.AddScoped<OtpService>();
// ── Application services (Clean Arch — no MVVM) ──────────────────────────────
builder.Services.AddScoped<NovinCRM.Services.Auth.IRegisterService, NovinCRM.Services.Auth.RegisterService>();
builder.Services.AddScoped<NovinCRM.Services.Deal.IDealCreateService, NovinCRM.Services.Deal.DealCreateService>();
// User Panel
builder.Services.AddSingleton<NovinCRM.Services.UserPanel.IPersianDateService, NovinCRM.Services.UserPanel.PersianDateService>();
builder.Services.AddScoped<NovinCRM.Services.UserPanel.IUserPanelService, NovinCRM.Services.UserPanel.UserPanelService>();
builder.Services.AddMemoryCache();
// ── Distributed cache — Redis in production, in-process fallback in dev ──────
// Set REDIS_CONNECTION_STRING env var (or ConnectionStrings:Redis in config)
// to activate the Redis-backed IDistributedCache. Without it the app falls back
// to an in-process store that is sufficient for single-instance development.
var redisCs =
Environment.GetEnvironmentVariable("REDIS_CONNECTION_STRING")
?? builder.Configuration.GetConnectionString("Redis");
if (!string.IsNullOrWhiteSpace(redisCs))
builder.Services.AddStackExchangeRedisCache(o => o.Configuration = redisCs);
else
builder.Services.AddDistributedMemoryCache();
// ── Rate limiting (ASP.NET Core built-in — no extra package needed) ───────────
// Protects OTP send, OTP verify, and admin login from brute-force / SMS-pumping.
builder.Services.AddRateLimiter(opts =>
{
opts.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
// OTP send: max 3 per phone per 60 s (keyed by remote IP as a safe default)
opts.AddSlidingWindowLimiter("otp-send", o =>
{
o.PermitLimit = 3;
o.Window = TimeSpan.FromMinutes(1);
o.SegmentsPerWindow = 6;
o.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
o.QueueLimit = 0;
});
// OTP verify: max 10 attempts per IP per 10 min
opts.AddSlidingWindowLimiter("otp-verify", o =>
{
o.PermitLimit = 10;
o.Window = TimeSpan.FromMinutes(10);
o.SegmentsPerWindow = 5;
o.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
o.QueueLimit = 0;
});
// Admin login: max 10 per IP per 15 min
opts.AddSlidingWindowLimiter("admin-login", o =>
{
o.PermitLimit = 10;
o.Window = TimeSpan.FromMinutes(15);
o.SegmentsPerWindow = 5;
o.QueueProcessingOrder = QueueProcessingOrder.OldestFirst;
o.QueueLimit = 0;
});
});
// ── Dead-letter store — in-memory singleton (swap for Redis/SQL implementation) ──
builder.Services.AddSingleton<
NovinCRM.Application.Common.Interfaces.IDeadLetterStore,
NovinCRM.Infrastructure.Webhooks.InMemoryDeadLetterStore>();
// ── HubSpot Webhook Infrastructure ───────────────────────────────────────────
// Registers: HubSpotWebhookOptions, HubSpotSignatureVerifier (singleton),
// InMemoryWebhookEventQueue (singleton), WebhookDispatcherService (hosted).
builder.Services.AddHubSpotWebhooks();
// ── Event-Driven Architecture + Bidirectional Sync ────────────────────────────
// Registers: MediatR, IDomainEventDispatcher, IIntegrationEventPublisher,
// ISyncStateRepository (Redis or in-memory), BidirectionalSyncService, HubSpotWebhookSyncHandler.
builder.Services.AddEventDrivenSync(builder.Configuration);
// ── Infrastructure: concrete implementations ──────────────────────────────
builder.Services.AddScoped<NovinCRM.Services.Imaging.ImageProcessingService>();
// ── Application interfaces → Infrastructure adapters ─────────────────────
// These registrations satisfy the dependency-inversion rule:
// Application layer depends on interfaces; Infrastructure provides implementations.
builder.Services.AddScoped<
NovinCRM.Application.Common.Interfaces.IContactRepository,
NovinCRM.Services.CRM.Objects.ContactRepository>();
builder.Services.AddScoped<
NovinCRM.Application.Common.Interfaces.IDealRepository,
NovinCRM.Services.CRM.Objects.DealRepository>();
builder.Services.AddScoped<
NovinCRM.Application.Common.Interfaces.IOwnerRepository,
NovinCRM.Services.CRM.OwnerRepository>();
builder.Services.AddScoped<
NovinCRM.Application.Common.Interfaces.IPipelineRepository,
NovinCRM.Services.CRM.PipelineRepository>();
builder.Services.AddScoped<
NovinCRM.Application.Common.Interfaces.IAssociateService,
NovinCRM.Services.CRM.AssociateAdapter>();
builder.Services.AddScoped<
NovinCRM.Application.Common.Interfaces.ILineItemRepository,
NovinCRM.Services.CRM.Commerce.LineItemRepository>();
// ── Invoice sub-system (issue #96) ───────────────────────────────────────────
builder.Services.AddHttpClient<HubSpotInvoiceClient>((sp, client) =>
{
client.BaseAddress = new Uri("https://api.hubapi.com");
client.Timeout = TimeSpan.FromSeconds(30);
})
.ConfigurePrimaryHttpMessageHandler(() => new ShecanDnsHttpClientHandler());
builder.Services.AddScoped<
NovinCRM.Application.Common.Interfaces.IInvoiceService,
InvoiceService>();
builder.Services.AddSingleton<
NovinCRM.Application.Common.Interfaces.IInvoiceAccessTokenRepository,
NovinCRM.Infrastructure.Services.InMemoryInvoiceAccessTokenRepository>();
builder.Services.AddScoped<
NovinCRM.Application.Common.Interfaces.IIdentityVerificationService,
NovinCRM.Services.Identity.ZohalIdentityAdapter>();
builder.Services.AddScoped<
NovinCRM.Application.Common.Interfaces.IImageProcessingService,
NovinCRM.Services.Imaging.ImageProcessingAdapter>();
// ── Health checks ─────────────────────────────────────────────────────────────
// /health/live — liveness: process is running (no dependencies checked)
// /health/ready — readiness: webhook queue depth + memory
builder.Services.AddHealthChecks()
.AddCheck<NovinCRM.Infrastructure.Health.WebhookQueueHealthCheck>("webhook-queue")
.AddCheck("memory", () =>
{
var bytes = GC.GetTotalMemory(forceFullCollection: false);
const long limit = 512L * 1024 * 1024; // 512 MB
return bytes < limit
? Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckResult.Healthy($"{bytes / 1024 / 1024} MB")
: Microsoft.Extensions.Diagnostics.HealthChecks.HealthCheckResult.Degraded($"High memory: {bytes / 1024 / 1024} MB");
});
builder.Services.AddRazorPages();
// ── Nightly Backup sub-system (issue #97) ────────────────────────────────────
var backupCs = builder.Configuration.GetConnectionString("BackupDb");
if (!string.IsNullOrWhiteSpace(backupCs))
{
builder.Services.AddDbContextFactory<NovinBackupDbContext>(opts =>
opts.UseSqlServer(backupCs));
builder.Services.AddScoped<
NovinCRM.Application.Common.Interfaces.IHubSpotBackupService,
HubSpotBackupService>();
builder.Services.AddSingleton<
NovinCRM.Application.Common.Interfaces.IMaintenanceModeService,
NovinCRM.Infrastructure.Services.MaintenanceModeService>();
builder.Services.AddHostedService<NightlyBackupHostedService>();
}
else
{
// Register a no-op maintenance service so DI doesn't fail when backup is disabled
builder.Services.AddSingleton<
NovinCRM.Application.Common.Interfaces.IMaintenanceModeService,
NovinCRM.Infrastructure.Services.MaintenanceModeService>();
}
var app = builder.Build();
// Development startup diagnostics — presence only, never values
if (app.Environment.IsDevelopment())
{
var logger = app.Services.GetRequiredService<ILogger<Program>>();
var config = app.Services.GetRequiredService<IConfiguration>();
logger.LogInformation("=== Configuration Sources ===");
logger.LogInformation(".env file loaded: {EnvFileExists}", File.Exists(envPath));
logger.LogInformation("Environment: {Environment}", app.Environment.EnvironmentName);
logger.LogInformation("HubSpot Token configured: {IsConfigured}", !string.IsNullOrEmpty(config["HubSpot:Token"]));
logger.LogInformation("Zohal Token configured: {IsConfigured}", !string.IsNullOrEmpty(config["Zohal:Token"]));
logger.LogInformation("IPPanel ApiKey configured: {IsConfigured}", !string.IsNullOrEmpty(config["IPPanel:ApiKey"]));
logger.LogInformation("Liara ApiToken configured: {IsConfigured}", !string.IsNullOrEmpty(config["Liara:ApiToken"]));
logger.LogInformation("===========================");
}
// Pipeline
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
// Localization middleware
var locOptions = app.Services.GetRequiredService<Microsoft.Extensions.Options.IOptions<RequestLocalizationOptions>>().Value;
app.UseRequestLocalization(locOptions);
// Enable response compression
app.UseResponseCompression();
// ── Correlation-ID middleware — assigns / echoes X-Correlation-Id header ──
app.UseMiddleware<CorrelationIdMiddleware>();
// Rate limiting middleware — must come before endpoint routing
app.UseRateLimiter();
// Static files with caching in production
var cacheMaxAge = app.Environment.IsProduction()
? TimeSpan.FromDays(30)
: TimeSpan.FromSeconds(0);
app.UseStaticFiles(new StaticFileOptions
{
OnPrepareResponse = ctx =>
{
ctx.Context.Response.Headers.Append("Cache-Control", $"public,max-age={cacheMaxAge.TotalSeconds}");
}
});
// Culture switch endpoint
app.MapGet("/set-culture/{culture}", (string culture, string? redirectUri, HttpContext httpContext) =>
{
if (!string.IsNullOrWhiteSpace(culture))
{
httpContext.Response.Cookies.Append(
CookieRequestCultureProvider.DefaultCookieName,
CookieRequestCultureProvider.MakeCookieValue(new RequestCulture(culture)),
new CookieOptions { Expires = DateTimeOffset.UtcNow.AddYears(1) });
}
return Results.Redirect(redirectUri ?? "/");
});
app.UseAntiforgery();
// ── IPPanel diagnostics (development only) ───────────────────────────────────
// GET /diag/ippanel — validates the configured API key against IPPanel
if (app.Environment.IsDevelopment())
{
app.MapGet("/diag/ippanel", async (NovinCRM.Services.SMS.IpPanelClient client) =>
{
var result = await client.CheckTokenAsync();
return Results.Json(result);
});
}
// ── Health check endpoints ────────────────────────────────────────────────────
// Liveness — just proves the process is alive (no dependency checks)
app.MapHealthChecks("/health/live", new Microsoft.AspNetCore.Diagnostics.HealthChecks.HealthCheckOptions
{
Predicate = _ => false // skip all named checks — instant 200
});
// Readiness — runs webhook-queue + memory checks
app.MapHealthChecks("/health/ready");
// ── HubSpot Webhook Endpoint ──────────────────────────────────────────────────
// POST /webhooks/hubspot — antiforgery disabled (HMAC-SHA256 v3 signature used instead)
app.MapHubSpotWebhook();
app.MapRazorPages();
app.MapRazorComponents<App>()
.AddInteractiveServerRenderMode();
app.Run();