-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
251 lines (218 loc) · 10 KB
/
Copy pathProgram.cs
File metadata and controls
251 lines (218 loc) · 10 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
using EnterpriseChat.Licensing.Abstractions;
using EnterpriseChat.Server.ApiDocs;
using EnterpriseChat.Server.ApiKeys;
using EnterpriseChat.Server.Auth;
using EnterpriseChat.Server.Bootstrap;
using EnterpriseChat.Server.Crypto;
using EnterpriseChat.Server.Data;
using EnterpriseChat.Server.Admin;
using EnterpriseChat.Server.Engagement;
using EnterpriseChat.Server.Files;
using EnterpriseChat.Server.Hubs;
using EnterpriseChat.Server.Licensing;
using EnterpriseChat.Server.Rooms;
using EnterpriseChat.Server.Search;
using EnterpriseChat.Server.Users;
using Serilog;
// Two-stage Serilog init: bootstrap logger first so anything that fails before
// the host is built (config load, plugin scan, port binding) still gets logged.
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information()
.WriteTo.Console()
.CreateBootstrapLogger();
try
{
var resetRequested = EnterpriseChat.Server.Bootstrap.AdminPasswordResetCli.TryExtractPassword(args, out var newAdminPwd, out var remainingArgs);
args = remainingArgs;
if (resetRequested)
{
Environment.ExitCode = await EnterpriseChat.Server.Bootstrap.AdminPasswordResetCli.RunAsync(newAdminPwd);
return;
}
var backupRequested = EnterpriseChat.Server.Bootstrap.BackupCli.TryExtractBackup(args, out var backupPath, out var backupForce, out args);
if (backupRequested)
{
Environment.ExitCode = await EnterpriseChat.Server.Bootstrap.BackupCli.RunBackupAsync(backupPath, backupForce, AppContext.BaseDirectory);
return;
}
var restoreRequested = EnterpriseChat.Server.Bootstrap.BackupCli.TryExtractRestore(args, out var restorePath, out var restoreYes, out args);
if (restoreRequested)
{
Environment.ExitCode = await EnterpriseChat.Server.Bootstrap.BackupCli.RunRestoreAsync(restorePath, restoreYes, AppContext.BaseDirectory);
return;
}
EnterpriseChat.Server.Bootstrap.InteractiveLauncher.RunIfInteractive(args, Directory.GetCurrentDirectory());
Log.Information("EnterpriseChat.Server arrancando.");
// Cuando el server corre como Windows Service, sc.exe no fija el
// WorkingDirectory: el SCM arranca el proceso con CurrentDirectory =
// C:\Windows\System32. Eso rompe la resolución relativa de wwwroot/,
// data/chat.db y los logs configurados con paths relativos. Forzamos
// ContentRootPath = AppContext.BaseDirectory (la carpeta donde está
// el .exe / .dll del server) para que las paths relativas funcionen
// igual que en Linux (systemd ya pone WorkingDirectory=/opt/enterprisechat).
var builder = WebApplication.CreateBuilder(new WebApplicationOptions
{
Args = args,
ContentRootPath = AppContext.BaseDirectory,
});
Directory.SetCurrentDirectory(AppContext.BaseDirectory);
// Same binary runs as console (dev), Windows Service or systemd unit.
builder.Host.UseWindowsService(o => o.ServiceName = "EnterpriseChat");
builder.Host.UseSystemd();
builder.Host.UseSerilog((ctx, services, lc) => lc
.ReadFrom.Configuration(ctx.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext());
// Master key del crypto symmetric. Tiene que estar lista ANTES de
// que se registren providers externos: cifran credenciales con ella
// y abortar tarde implicaría un fallo en la primera petición admin.
using (var bootstrapLoggerFactory = LoggerFactory.Create(b => b.AddSerilog(Log.Logger)))
{
var masterKeyBytes = MasterKeyInitializer.EnsureMasterKey(
builder.Configuration,
builder.Environment,
bootstrapLoggerFactory.CreateLogger("Bootstrap.MasterKey"));
builder.Services.AddSingleton(new AppCrypto(masterKeyBytes));
}
builder.Services.AddSignalR();
builder.Services.AddSingleton<Microsoft.AspNetCore.SignalR.IUserIdProvider, EnterpriseChat.Server.Auth.SubClaimUserIdProvider>();
builder.Services.AddChatPersistence(builder.Configuration);
builder.Services.AddChatAuth(builder.Configuration);
// CORS: only needed for `npm run dev` of the Vue SPA (different origin).
// Production builds copy the SPA to wwwroot and are served from the same
// origin, so CORS is irrelevant there.
builder.Services.AddCors(options =>
{
options.AddPolicy("WebSpaDev", policy =>
{
var origins = builder.Configuration
.GetSection("EnterpriseChat:Cors:DevOrigins")
.Get<string[]>()
?? new[] { "http://localhost:5173", "http://127.0.0.1:5173" };
policy
.WithOrigins(origins)
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
// Licensing: load Pro plugin if present, otherwise fall back to FreeLicenseValidator.
builder.Services.AddEnterpriseChatLicensing(builder.Configuration, builder.Environment);
builder.Services.AddSingleton<ConcurrentSessionCounter>();
// OpenAPI + Swagger UI público en /docs/api.
builder.Services.AddEnterpriseChatSwagger();
var app = builder.Build();
await app.Services.InitializeChatDatabaseAsync();
await AdminSeeder.SeedAdminIfEmptyAsync(
app.Services,
app.Configuration,
app.Services.GetRequiredService<ILoggerFactory>().CreateLogger("Bootstrap"));
await app.Services.GetRequiredService<EnterpriseChat.Server.Auth.Providers.AuthProviderRegistry>()
.ReloadAsync();
await LicenseStartupRestorer.RestoreAsync(
app.Services,
app.Services.GetRequiredService<ILoggerFactory>().CreateLogger("Licensing"));
app.UseSerilogRequestLogging();
// Default + static files: serves the Vue SPA bundled into wwwroot/. In dev
// the SPA runs via `npm run dev` on its own port and hits the API via CORS;
// wwwroot may be empty during that flow, which is fine.
app.UseDefaultFiles();
// Habilitamos .md como text/markdown para que GET /docs/*.md devuelva
// el contenido en lugar de 404 (UseStaticFiles por defecto rechaza
// extensiones que no estén en el FileExtensionContentTypeProvider).
var staticContentTypes = new Microsoft.AspNetCore.StaticFiles.FileExtensionContentTypeProvider();
staticContentTypes.Mappings[".md"] = "text/markdown; charset=utf-8";
app.UseStaticFiles(new StaticFileOptions { ContentTypeProvider = staticContentTypes });
if (app.Environment.IsDevelopment())
{
app.UseCors("WebSpaDev");
}
app.UseAuthentication();
app.UseAuthorization();
app.UseRateLimiter();
app.MapGet("/healthz", () => Results.Ok(new { status = "ok" }));
app.MapGet("/license", (ILicenseValidator licensing) => Results.Ok(licensing.Current));
app.MapAuthEndpoints();
app.MapUserEndpoints();
app.MapAdminEndpoints();
app.MapAuthProviderAdminEndpoints();
app.MapRoomEndpoints();
app.MapSearchEndpoints();
app.MapFileEndpoints();
app.MapLicenseAdminEndpoints();
app.MapApiKeyAdminEndpoints();
app.MapEngagementEndpoints();
app.MapHub<ChatHub>("/hubs/chat");
// Swagger UI + OpenAPI JSON. Tiene que ir ANTES de MapFallbackToFile
// para que el SPA Vue no se trague /docs/api y devuelva index.html.
app.UseEnterpriseChatSwagger();
// Atajo: GET /docs → /docs/api (la landing de Swagger UI).
app.MapGet("/docs", () => Results.Redirect("/docs/api/"))
.ExcludeFromDescription();
// SPA fallback: anything that didn't match an API route or a real static
// file is served by index.html so the Vue Router can handle client-side
// paths like /channels/42, /dm/7, /login, etc.
app.MapFallbackToFile("index.html");
var licInfo = app.Services.GetRequiredService<ILicenseValidator>().Current;
Log.Information(
"Edición activa: {Edition} (máx. {Max} usuarios concurrentes).",
licInfo.Edition,
licInfo.MaxConcurrentUsers);
// Pre-bind check so port-in-use is reported with a friendly message
// before Kestrel throws a noisy stack trace.
//
// Se salta en Testing: WebApplicationFactory sirve con TestServer in-process
// y NUNCA enlaza un puerto real, así que aquí la comprobación no sólo sobra
// — es dañina. Con el servidor de desarrollo o el servicio de producción
// escuchando en :5080, el pre-check fallaba, este `return` dejaba la app sin
// construir y TODA la suite se caía con un
// "The server has not been started or no web application was configured"
// que no apunta a la causa por ningún lado.
if (!app.Environment.IsEnvironment("Testing")
&& !PortAvailabilityCheck.TryEnsureAvailable(app.Configuration, out _))
{
PortAvailabilityCheck.WaitForExitKey();
Environment.ExitCode = 2;
return;
}
StartupBanner.Register(app);
app.Run();
}
catch (Exception ex) when (ex is not HostAbortedException)
{
// Detect "address in use" anywhere in the InnerException chain — Kestrel
// wraps the SocketException inside IOException → AddressInUseException.
var addrInUse = false;
for (Exception? current = ex; current is not null; current = current.InnerException)
{
if (current is System.Net.Sockets.SocketException se
&& se.SocketErrorCode == System.Net.Sockets.SocketError.AddressAlreadyInUse)
{
addrInUse = true;
break;
}
}
if (addrInUse)
{
Log.Fatal("Kestrel no pudo enlazarse al puerto (otro proceso lo está usando).");
PortAvailabilityCheck.RenderPortBusyForCaught(app: null, config: null);
Environment.ExitCode = 2;
}
else
{
Log.Fatal(ex, "EnterpriseChat.Server ha terminado por una excepción no controlada.");
Environment.ExitCode = 1;
}
if (Environment.UserInteractive && !Console.IsOutputRedirected)
{
PortAvailabilityCheck.WaitForExitKey();
}
}
finally
{
Log.CloseAndFlush();
}
// Exposed so WebApplicationFactory<Program> in the test project can host
// this server in-process. Required because top-level statements emit
// `internal class Program` otherwise.
public partial class Program;