Program.cs 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219
  1. using Application;
  2. using Application.Abstractions.Chat;
  3. using Application.Abstractions.Hub;
  4. using Infrastructure;
  5. using SharedKernel;
  6. using System.Reflection;
  7. using System.Threading.RateLimiting;
  8. using Microsoft.AspNetCore.RateLimiting;
  9. using Microsoft.AspNetCore.ResponseCompression;
  10. using Microsoft.Extensions.Hosting.WindowsServices;
  11. using Serilog;
  12. using Web.Api;
  13. using Web.Api.Common;
  14. using Web.Api.Extensions;
  15. using Web.Api.Hubs;
  16. using Web.Api.Services;
  17. using Infrastructure.Hubs;
  18. var builder = WebApplication.CreateBuilder(args);
  19. var settings = builder.Configuration.Get<AppSettings>()!;
  20. if (!WindowsServiceHelpers.IsWindowsService())
  21. {
  22. Console.Title = settings.App.Name;
  23. }
  24. Console.WriteLine($"ENV={builder.Environment.EnvironmentName}");
  25. Console.WriteLine($"현재 시간: {DateTime.Now} / {TimeZoneInfo.Local.Id}");
  26. builder.Host.UseWindowsService();
  27. // Serilog — Production에서만 파일 로그
  28. if (builder.Environment.IsProduction())
  29. {
  30. Log.Logger = new LoggerConfiguration()
  31. .ReadFrom.Configuration(builder.Configuration)
  32. .WriteTo.File("logs/webapi-.log",
  33. rollingInterval: RollingInterval.Day,
  34. retainedFileCountLimit: 30,
  35. outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff} [{Level:u3}] {Message:lj}{NewLine}{Exception}")
  36. .CreateLogger();
  37. builder.Host.UseSerilog();
  38. }
  39. builder.Services.Configure<AppSettings>(builder.Configuration);
  40. builder.Services.AddApiForwardedHeaders(settings); // Cloudflare → IIS reverse proxy 헤더 신뢰
  41. builder.Services
  42. .AddApplication()
  43. .AddPresentation(settings)
  44. .AddApiInfrastructure(builder.Configuration);
  45. // 모든 DateTime 응답에 UTC(Z) 마커 강제 — SQL Server datetime2 + EF Core 가 Kind=Unspecified 로
  46. // 읽어서 JS new Date() 가 로컬 시간으로 오해하는 문제 해결 (KST 환경에서 9시간 차이).
  47. builder.Services.ConfigureHttpJsonOptions(opts =>
  48. {
  49. opts.SerializerOptions.Converters.Add(new UtcDateTimeConverter());
  50. opts.SerializerOptions.Converters.Add(new UtcNullableDateTimeConverter());
  51. });
  52. // CORS
  53. builder.Services.AddCors(options =>
  54. {
  55. options.AddPolicy(settings.CorsPolicy.Name, policy =>
  56. {
  57. policy
  58. .WithOrigins(settings.CorsPolicy.AllowedOrigins.ToArray())
  59. .AllowAnyHeader()
  60. .AllowAnyMethod()
  61. .AllowCredentials()
  62. .SetPreflightMaxAge(TimeSpan.FromSeconds(settings.CorsPolicy.PreflightMaxAgeSeconds));
  63. });
  64. });
  65. // SignalR
  66. builder.Services.AddSignalR();
  67. // Response 압축 (Brotli/Gzip) — JSON/HTML 응답 크기 대폭 절감
  68. builder.Services.AddResponseCompression(options =>
  69. {
  70. options.EnableForHttps = true;
  71. options.Providers.Add<BrotliCompressionProvider>();
  72. options.Providers.Add<GzipCompressionProvider>();
  73. });
  74. // Output cache 정책 등록 (글로벌 적용 X — endpoint 별 .CacheOutput("PublicShort") opt-in)
  75. builder.Services.AddOutputCache(options =>
  76. {
  77. options.AddPolicy("PublicShort", b => b.Cache().Expire(TimeSpan.FromSeconds(30)).SetVaryByQuery("*"));
  78. });
  79. // Rate limiter 등록 (글로벌 적용 X — endpoint 별 .RequireRateLimiting("api") opt-in)
  80. builder.Services.AddRateLimiter(options =>
  81. {
  82. options.AddFixedWindowLimiter("api", w =>
  83. {
  84. w.PermitLimit = 100;
  85. w.Window = TimeSpan.FromMinutes(1);
  86. w.QueueLimit = 0;
  87. });
  88. options.RejectionStatusCode = StatusCodes.Status429TooManyRequests;
  89. });
  90. // Chat
  91. builder.Services.AddSingleton<IChatHubService, ChatHubService>();
  92. builder.Services.AddHostedService<KickSubscriberService>();
  93. // Endpoints
  94. builder.Services.AddEndpoints(Assembly.GetExecutingAssembly());
  95. builder.Logging.AddConsole();
  96. /**
  97. * =======================================================================================================================================================
  98. */
  99. var app = builder.Build();
  100. /**
  101. * =======================================================================================================================================================
  102. */
  103. // NICE 본인인증 시크릿 미주입(placeholder) 감지 — Secret File 치환 누락 시, 사용자에게 혼란스러운
  104. // "권한 오류(1006)" 대신 부팅 로그로 운영자에게 즉시 경고. (IsConfigured=false 라 런타임은 "준비 중" 으로 안전 동작)
  105. {
  106. var niceOptions = app.Services.GetRequiredService<Microsoft.Extensions.Options.IOptions<Infrastructure.Kyc.Nice.NiceAuthOptions>>().Value;
  107. if (niceOptions.HasUnsubstitutedPlaceholder)
  108. {
  109. app.Logger.LogWarning("NICE 본인인증 설정에 미치환 placeholder(__INJECT_)가 남아 있습니다. Jenkins Secret File(PROD/DEV-DPOT-API) 주입 누락 — 본인인증은 '준비 중(NotConfigured)' 으로 동작합니다.");
  110. }
  111. }
  112. // 상태 확인\
  113. app.MapHealthChecks("/health");
  114. // ForwardedHeaders 는 다른 미들웨어보다 먼저 — Exception/Cors/Auth 가 client IP 를 알아야 정확.
  115. app.UseForwardedHeaders();
  116. app.UseExceptionHandler();
  117. app.UseResponseCompression();
  118. app.UseCors(settings.CorsPolicy.Name);
  119. // Swagger 는 UseCors 다음에 등록해야 swagger.json GET 응답에 CORS 헤더가 적용됨
  120. // (이전 순서에서는 preflight 만 통과하고 실제 GET 응답에 Access-Control-Allow-Origin 누락)
  121. //
  122. // Public swagger.json 은 모든 환경에 노출 — developers.dpot.live 의 Scalar 가 client-side fetch.
  123. // Internal swagger 는 외부 노출 금지 → Production 에서는 /swagger/internal/* 를 404 로 차단.
  124. if (!app.Environment.IsDevelopment())
  125. {
  126. app.Use(async (ctx, next) =>
  127. {
  128. if (ctx.Request.Path.StartsWithSegments("/swagger/internal"))
  129. {
  130. ctx.Response.StatusCode = StatusCodes.Status404NotFound;
  131. return;
  132. }
  133. await next();
  134. });
  135. }
  136. app.UseSwagger();
  137. if (app.Environment.IsDevelopment())
  138. {
  139. // NICE 통합인증 암복호화 invariants 자체 검증 (런타임/패키지 회귀 방지)
  140. Infrastructure.Kyc.Nice.NiceCryptoInvariants.EnsureOrThrow();
  141. app.UseSwaggerUI(c =>
  142. {
  143. c.SwaggerEndpoint("/swagger/internal/swagger.json", "DPOT Internal API");
  144. c.SwaggerEndpoint("/swagger/public/swagger.json", "DPOT Public API");
  145. });
  146. }
  147. // 외부 storage 경로 (deploy 영향 받지 않음) 의 업로드 파일 정적 서빙.
  148. var storageBase = builder.Configuration.GetSection(SharedKernel.Storage.StorageOptions.SectionName).Get<SharedKernel.Storage.StorageOptions>()?.BasePath;
  149. if (!string.IsNullOrWhiteSpace(storageBase) && Directory.Exists(storageBase))
  150. {
  151. var uploadsDir = Path.Combine(storageBase, "uploads");
  152. if (Directory.Exists(uploadsDir))
  153. {
  154. app.UseStaticFiles(new Microsoft.AspNetCore.Builder.StaticFileOptions
  155. {
  156. FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(uploadsDir),
  157. RequestPath = "/uploads"
  158. });
  159. }
  160. var editorsDir = Path.Combine(storageBase, "editors");
  161. if (Directory.Exists(editorsDir))
  162. {
  163. app.UseStaticFiles(new Microsoft.AspNetCore.Builder.StaticFileOptions
  164. {
  165. FileProvider = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(editorsDir),
  166. RequestPath = "/editors"
  167. });
  168. }
  169. }
  170. app.UseStaticFiles();
  171. app.UseAuthentication();
  172. app.UseAuthorization();
  173. app.UseOutputCache();
  174. app.UseRateLimiter();
  175. app.UseMiddleware<Web.Api.Middleware.ApiRequestLogMiddleware>();
  176. app.UseMiddleware<Web.Api.Middleware.RateLimitMiddleware>();
  177. app.MapEndpoints();
  178. app.MapHub<ChatHub>("/hubs/chat");
  179. app.MapHub<AppHub>("/hubs/app");
  180. app.MapHub<DonationHub>("/hubs/donation");
  181. // 서버 시작 시 stale 연결 정보 초기화 (Web.Api 비정상 종료 후 남은 고아 데이터 제거).
  182. // 모든 SignalR client 는 reconnect 시 OnConnected 로 재등록됨.
  183. using (var scope = app.Services.CreateScope())
  184. {
  185. await scope.ServiceProvider.GetRequiredService<IChatConnectionTracker>().ClearAllAsync();
  186. await scope.ServiceProvider.GetRequiredService<IPresenceTracker>().ClearAllAsync();
  187. await scope.ServiceProvider.GetRequiredService<IVisitorTracker>().ClearAllAsync();
  188. }
  189. app.Run();