using System.Security.Claims; using System.Security.Cryptography; using System.Threading.RateLimiting; using GuestOps.Web; using Microsoft.AspNetCore.Antiforgery; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.RateLimiting; using Microsoft.AspNetCore.HttpOverrides; using System.Net; var bootstrap = args.Contains("--bootstrap"); var recoverOwner = args.Contains("--recover-owner"); var backupProbe=args.Contains("--backup-probe");var verifyBackupProbe=args.Contains("--verify-backup-probe"); var builder = WebApplication.CreateBuilder(args.Where(arg => arg != "--bootstrap" && arg != "--recover-owner" && arg != "--backup-probe" && arg != "--verify-backup-probe").ToArray()); if (builder.Configuration["Pms:ConfigFile"] is { Length: > 0 } pmsConfigFile) builder.Configuration.AddJsonFile(pmsConfigFile,optional:false,reloadOnChange:false); if (builder.Configuration["Payments:ConfigFile"] is { Length: > 0 } paymentConfigFile) builder.Configuration.AddJsonFile(paymentConfigFile,optional:false,reloadOnChange:false); builder.Logging.ClearProviders(); builder.Logging.AddConsole(); builder.Logging.AddFilter("Microsoft.AspNetCore.Hosting.Diagnostics", LogLevel.Warning); builder.Logging.AddFilter("System.Net.Http.HttpClient", LogLevel.Warning); var preview = builder.Configuration.GetValue("Preview"); if (preview && !builder.Environment.IsDevelopment()) throw new InvalidOperationException("Preview mode is Development-only."); builder.WebHost.ConfigureKestrel(o => o.Limits.MaxRequestBodySize = 128 * 1024); var protection = builder.Services.AddDataProtection().SetApplicationName("GuestOps-Web"); var keyPath = builder.Configuration["Keys:Path"]; if (!preview && string.IsNullOrWhiteSpace(keyPath)) throw new InvalidOperationException("Keys:Path must point to a persistent private directory."); if (keyPath != null) protection.PersistKeysToFileSystem(new DirectoryInfo(keyPath)); builder.Services.AddSingleton(s => preview ? new PreviewStore() : new MongoStore(s.GetRequiredService())); builder.Services.AddSingleton, PasswordHasher>(); builder.Services.AddHttpClient(c => c.Timeout = TimeSpan.FromSeconds(25)).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false }); builder.Services.AddHttpClient(c => c.Timeout = TimeSpan.FromSeconds(60)).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false }); builder.Services.AddSingleton(); builder.Services.AddHttpClient(c => c.Timeout = TimeSpan.FromSeconds(25)).ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false }); builder.Services.AddTransient(); builder.Services.AddHttpClient(c=>c.Timeout=TimeSpan.FromSeconds(25)).ConfigurePrimaryHttpMessageHandler(()=>new HttpClientHandler{AllowAutoRedirect=false}); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddTransient(); builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(o => { o.Cookie.Name = "guestops.session"; o.Cookie.HttpOnly = true; o.Cookie.SameSite = SameSiteMode.Lax; o.Cookie.SecurePolicy = preview ? CookieSecurePolicy.SameAsRequest : CookieSecurePolicy.Always; o.ExpireTimeSpan = TimeSpan.FromHours(8); o.SlidingExpiration = false; o.Events.OnRedirectToLogin = c => { c.Response.StatusCode = 401; return Task.CompletedTask; }; o.Events.OnRedirectToAccessDenied = c => { c.Response.StatusCode = 403; return Task.CompletedTask; }; o.Events.OnValidatePrincipal = async c => { var hotel = c.Principal?.FindFirstValue("hotel"); var id = c.Principal?.FindFirstValue(ClaimTypes.NameIdentifier); var user = hotel == null || id == null ? null : await c.HttpContext.RequestServices.GetRequiredService().Get(hotel, id); if (user == null || !TeamAccounts.SessionValid(user,c.Principal?.FindFirstValue("security_stamp")) || user.Role != c.Principal!.FindFirstValue(ClaimTypes.Role)) c.RejectPrincipal(); }; }); builder.Services.AddAuthorization(o => o.AddPolicy("Owner", p => p.RequireRole("Owner"))); builder.Services.Configure(o => { // Trust scheme and client address only from the explicitly configured host proxy. // The rewritten RemoteIpAddress is used by login throttling below. o.ForwardedHeaders = ForwardedHeaders.XForwardedProto | ForwardedHeaders.XForwardedFor; o.ForwardLimit = 1; if (builder.Configuration["Proxy:KnownAddress"] is { Length: > 0 } address) o.KnownProxies.Add(IPAddress.Parse(address)); }); builder.Services.AddAntiforgery(o => { o.HeaderName = "X-CSRF-TOKEN"; o.Cookie.Name = "guestops.csrf"; o.Cookie.HttpOnly = true; o.Cookie.SameSite = SameSiteMode.Strict; o.Cookie.SecurePolicy = preview ? CookieSecurePolicy.SameAsRequest : CookieSecurePolicy.Always; }); builder.Services.AddRateLimiter(o => { o.RejectionStatusCode = 429; o.AddPolicy("pms", context => RateLimitPartition.GetFixedWindowLimiter(context.User.FindFirstValue("hotel") ?? "anonymous", _ => new() { PermitLimit = 30, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 })); o.AddPolicy("ai", context => RateLimitPartition.GetFixedWindowLimiter(context.User.FindFirstValue("hotel") ?? "anonymous", _ => new() { PermitLimit = 6, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 })); o.AddPolicy("accounts", context => RateLimitPartition.GetFixedWindowLimiter(context.User.FindFirstValue("hotel") ?? context.Connection.RemoteIpAddress?.ToString() ?? "unknown", _ => new() { PermitLimit = 30, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 })); o.AddPolicy("login", context => RateLimitPartition.GetFixedWindowLimiter(context.Connection.RemoteIpAddress?.ToString() ?? "unknown", _ => new() { PermitLimit = 10, Window = TimeSpan.FromMinutes(1), QueueLimit = 0 })); }); var app = builder.Build(); if(backupProbe||verifyBackupProbe) { var provider=app.Services.GetRequiredService(); if(backupProbe)Console.WriteLine(BackupProbe.Create(provider)); else if(!BackupProbe.Verify(provider,Environment.GetEnvironmentVariable("BACKUP_PROBE")??""))throw new InvalidOperationException("Backup keys failed verification."); else Console.WriteLine("Backup keys verified."); return; } app.UseForwardedHeaders(); var store = app.Services.GetRequiredService(); await store.Initialize(); if(recoverOwner) { var email=Environment.GetEnvironmentVariable("RECOVERY_EMAIL")?.Trim().ToLowerInvariant()??""; var user=await store.FindLogin(email);if(user==null)throw new InvalidOperationException("An active owner account is required."); var recovery=await app.Services.GetRequiredService().RecoverOwner(user); Console.WriteLine("Private single-use recovery link (expires in 30 minutes). Share only with the verified account owner:");Console.WriteLine(recovery.Link);return; } if (bootstrap) { var email = Environment.GetEnvironmentVariable("BOOTSTRAP_EMAIL")?.Trim().ToLowerInvariant() ?? ""; var password = Environment.GetEnvironmentVariable("BOOTSTRAP_PASSWORD") ?? ""; var hotelName = Environment.GetEnvironmentVariable("BOOTSTRAP_HOTEL") ?? ""; if (!Input.Email(email) || !TeamAccounts.PasswordValid(password) || hotelName.Length < 2) throw new InvalidOperationException("Set BOOTSTRAP_EMAIL, BOOTSTRAP_PASSWORD (14 to 128 characters), and BOOTSTRAP_HOTEL."); if (await store.FindLogin(email) != null) throw new InvalidOperationException("Account already exists; bootstrap does not reset credentials."); var hotel = new Hotel { Name = hotelName }; hotel.HotelId = hotel.Id; var user = new StaffUser { HotelId = hotel.Id, Email = email, Name = "Hotel owner" }; user.PasswordHash = app.Services.GetRequiredService>().HashPassword(user, password); await store.Insert(hotel); await store.Insert(user); Console.WriteLine("Hotel and owner account created."); return; } app.Use(async (ctx, next) => { ctx.Response.Headers["X-Content-Type-Options"] = "nosniff"; ctx.Response.Headers["Referrer-Policy"] = "no-referrer"; ctx.Response.Headers["Content-Security-Policy"] = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'self'; form-action 'self'"; if (ctx.Request.Path.StartsWithSegments("/api") || ctx.Request.Path.StartsWithSegments("/account")) ctx.Response.Headers.CacheControl = "no-store"; try { await next(); } catch (MailboxConflict ex) { ctx.Response.StatusCode = 409; await ctx.Response.WriteAsJsonAsync(new { error = ex.Message }); } catch (GoogleFailure) { ctx.Response.StatusCode = 503; await ctx.Response.WriteAsJsonAsync(new { error = "Google could not complete this check. Review the mailbox status in Settings. No resend has been queued." }); } catch (AccountInvalid ex) { ctx.Response.StatusCode = 400; await ctx.Response.WriteAsJsonAsync(new { error = ex.Message }); } catch (AccountConflict ex) { ctx.Response.StatusCode = 409; await ctx.Response.WriteAsJsonAsync(new { error = ex.Message }); } catch (PaymentInvalid ex) { ctx.Response.StatusCode = 400; await ctx.Response.WriteAsJsonAsync(new { error = ex.Message }); } catch (PaymentConflict ex) { ctx.Response.StatusCode = 409; await ctx.Response.WriteAsJsonAsync(new { error = ex.Message }); } catch (PmsInvalid ex) { ctx.Response.StatusCode = 400; await ctx.Response.WriteAsJsonAsync(new { error = ex.Message }); } catch (PmsConflict ex) { ctx.Response.StatusCode = 409; await ctx.Response.WriteAsJsonAsync(new { error = ex.Message }); } catch (AntiforgeryValidationException) { ctx.Response.StatusCode = 400; await ctx.Response.WriteAsJsonAsync(new { error = "Your session needs refreshing. Reload the page and try again." }); } catch (Exception ex) { app.Logger.LogError("Request failed ({Type}), trace {Trace}", ex.GetType().Name, ctx.TraceIdentifier); if (!ctx.Response.HasStarted) { ctx.Response.StatusCode = 500; await ctx.Response.WriteAsJsonAsync(new { error = "The request could not be completed. Please try again.", trace = ctx.TraceIdentifier }); } } }); app.UseAuthentication(); app.UseAuthorization(); app.UseRateLimiter(); app.Use(async (ctx, next) => { if (ctx.Request.Path.StartsWithSegments("/api") && !HttpMethods.IsGet(ctx.Request.Method) && !HttpMethods.IsHead(ctx.Request.Method)) await ctx.RequestServices.GetRequiredService().ValidateRequestAsync(ctx); await next(); }); app.MapGet("/health", () => Results.Ok(new { status = "ready" })); app.MapGet("/api/session", (HttpContext c, IAntiforgery csrf) => Results.Ok(new { preview, csrfToken = csrf.GetAndStoreTokens(c).RequestToken, user = c.User.Identity?.IsAuthenticated == true ? new { id = c.User.FindFirstValue(ClaimTypes.NameIdentifier), name = c.User.Identity.Name, role = c.User.FindFirstValue(ClaimTypes.Role), hotelId = c.User.FindFirstValue("hotel") } : null })); app.MapPost("/api/auth/login", async (LoginInput input, HttpContext c, IPasswordHasher hasher) => { if (input.Email == null || input.Password == null || input.Email.Length > 254 || input.Password.Length > 256) return Results.BadRequest(new { error = "Invalid credentials." }); var user = await store.FindLogin(input.Email.Trim().ToLowerInvariant()); // Verify a dummy hash too so unknown accounts do not have a fast password path. var checkUser = user ?? new StaffUser(); var hash = string.IsNullOrEmpty(user?.PasswordHash) ? Input.DummyHash : user.PasswordHash; if (hasher.VerifyHashedPassword(checkUser, hash, input.Password) == PasswordVerificationResult.Failed || user?.Active != true) return Results.Json(new { error = "Email or password is incorrect." }, statusCode: 401); await Session.SignIn(c, user); return Results.Ok(); }).RequireRateLimiting("login"); app.MapPost("/api/auth/logout", async (HttpContext c, CancellationToken _) => { await c.SignOutAsync(); return Results.Ok(); }).RequireAuthorization(); if (preview) app.MapPost("/api/preview/start", async (HttpContext c, CancellationToken _) => { var user = await Demo.Seed(store); await Session.SignIn(c, user); return Results.Ok(); }).RequireRateLimiting("login"); var api = app.MapGroup("/api").RequireAuthorization(); PmsEndpoints.Map(api,preview); PaymentEndpoints.Map(api,preview); AutoReplyEndpoints.Map(api,preview); TeamEndpoints.Map(app,api,preview); MailboxManagement.Map(api,preview); Operations.Map(app,api,preview); api.MapGet("/hotel", async (HttpContext c, CancellationToken _) => Results.Ok(await store.Get(Session.Hotel(c), Session.Hotel(c)))); api.MapPut("/hotel", async (SettingsInput input, HttpContext c) => { if (!Input.Text(input.Name, 2, 120) || !Input.Text(input.Signature, 0, 2000)) return Results.BadRequest(new { error = "Enter a hotel name and a signature under 2,000 characters." }); try { _ = TimeZoneInfo.FindSystemTimeZoneById(input.Timezone); } catch { return Results.BadRequest(new { error = "Choose a valid timezone." }); } var hotel = await store.Get(Session.Hotel(c), Session.Hotel(c)); if (hotel == null) return Results.NotFound(); hotel.Name = input.Name.Trim(); hotel.Signature = input.Signature; hotel.Timezone = input.Timezone; hotel.Version = input.Version + 1; if (!await store.Replace(hotel.HotelId, hotel.Id, input.Version, hotel)) return Input.Conflict(); await Session.Audit(store, c, "Updated hotel settings"); return Results.Ok(hotel); }).RequireAuthorization("Owner"); api.MapGet("/conversations", async (HttpContext c, CancellationToken _) => Results.Ok((await store.List(Session.Hotel(c))).OrderByDescending(x => x.ReceivedAt))); api.MapGet("/conversations/page",async(string? cursor,HttpContext c)=>ConversationPaging.TryDecode(cursor,out var before,out var beforeId)?Results.Ok(await store.ConversationPage(Session.Hotel(c),cursor==null?null:before,beforeId,50)):Results.BadRequest(new{error="Invalid conversation cursor."})); api.MapGet("/conversations/{id}", async (string id, HttpContext c) => await store.Get(Session.Hotel(c), id) is { } item ? Results.Ok(item) : Results.NotFound()); api.MapPut("/conversations/{id}/draft", async (string id, DraftInput input, HttpContext c) => { if (!Input.Text(input.Draft, 0, 20000)) return Results.BadRequest(new { error = "Draft must be under 20,000 characters." }); var item = await store.Get(Session.Hotel(c), id); if (item == null) return Results.NotFound(); if (item.Delivery != null) return Results.Conflict(new { error = "This reply has already been approved for delivery. Its text is locked." }); item.Draft = input.Draft; item.Version = input.Version + 1; if (item.Status != "Completed") item.Status = input.Draft.Length > 0 ? "DraftReady" : "NeedsAttention"; if (!await store.Replace(item.HotelId, id, input.Version, item)) return Input.Conflict(); await Session.Audit(store, c, "Saved a reply draft"); return Results.Ok(item); }); api.MapPut("/conversations/{id}/status", async (string id, StatusInput input, HttpContext c) => { if (input.Status is not ("Completed" or "NeedsAttention")) return Results.BadRequest(); var item = await store.Get(Session.Hotel(c), id); if (item == null) return Results.NotFound(); if (item.Delivery != null && item.Delivery.State != "Sent") return Results.Conflict(new { error = "Resolve the pending delivery before changing this conversation." }); item.Status = input.Status; item.Version = input.Version + 1; if (!await store.Replace(item.HotelId, id, input.Version, item)) return Input.Conflict(); await Session.Audit(store, c, input.Status == "Completed" ? "Resolved a conversation" : "Reopened a conversation"); return Results.Ok(item); }); api.MapGet("/knowledge", async (HttpContext c, CancellationToken _) => Results.Ok(await store.List(Session.Hotel(c)))); api.MapPost("/knowledge", async (KnowledgeInput input, HttpContext c) => { if (!Input.Knowledge(input)) return Results.BadRequest(new { error = "Enter a title and answer within the allowed lengths." }); var item = new KnowledgeEntry { HotelId = Session.Hotel(c), Title = input.Title, Category = input.Category, Answer = input.Answer, Keywords = input.Keywords, Approved = input.Approved }; await store.Insert(item); await Session.Audit(store, c, "Added a hotel knowledge entry"); return Results.Ok(item); }).RequireAuthorization("Owner"); api.MapPut("/knowledge/{id}", async (string id, KnowledgeInput input, HttpContext c) => { if (!Input.Knowledge(input)) return Results.BadRequest(); var item = await store.Get(Session.Hotel(c), id); if (item == null) return Results.NotFound(); item.Title = input.Title; item.Category = input.Category; item.Answer = input.Answer; item.Keywords = input.Keywords; item.Approved = input.Approved; item.Version = input.Version + 1; if (!await store.Replace(item.HotelId, id, input.Version, item)) return Input.Conflict(); await Session.Audit(store, c, "Updated hotel knowledge"); return Results.Ok(item); }).RequireAuthorization("Owner"); api.MapGet("/activity", async (HttpContext c, CancellationToken _) => Results.Ok((await store.List(Session.Hotel(c))).OrderByDescending(x => x.At).Take(100))); api.MapGet("/mailboxes", async (HttpContext c, GoogleMailbox google, AiDrafts ai) => { var hotel=Session.Hotel(c);return Results.Ok(new { configured = !preview && google.Configured, sendingConfigured = !preview && google.SendingConfigured, aiConfigured = !preview && ai.Configured, timeZone=(await store.Get(hotel,hotel))?.Timezone??"UTC", items = (await store.List(hotel)).Select(MailboxManagement.View) }); }); api.MapPut("/reply-controls", async (ReplyControlsInput input, HttpContext c, GoogleMailbox google, AiDrafts ai) => { if ((input.AiDraftsEnabled && (preview || !ai.Configured)) || (input.StaffSendingEnabled && (preview || !google.SendingConfigured))) return Results.BadRequest(new { error = "The administrator must configure this capability first." }); var hotel = await store.Get(Session.Hotel(c), Session.Hotel(c)); if (hotel == null) return Results.NotFound(); hotel.AiDraftsEnabled = input.AiDraftsEnabled; hotel.StaffSendingEnabled = input.StaffSendingEnabled; hotel.ReplyMode = input.StaffSendingEnabled ? "StaffApproved" : "DraftOnly"; hotel.Version = input.Version + 1; if (!await store.Replace(hotel.HotelId, hotel.Id, input.Version, hotel)) return Input.Conflict(); await Session.Audit(store, c, "Updated AI and staff sending controls"); return Results.Ok(hotel); }).RequireAuthorization("Owner"); api.MapPost("/conversations/{id}/generate", async (string id, VersionInput input, HttpContext c, AiDrafts ai) => { var item = await store.Get(Session.Hotel(c), id); if (item == null) return Results.NotFound(); var hotel = await store.Get(item.HotelId, item.HotelId); if (preview || !ai.Configured || hotel?.AiDraftsEnabled != true) return Results.BadRequest(new { error = "AI drafts are not enabled for this hotel." }); if (item.Version != input.Version || item.Delivery != null) return Input.Conflict(); var sources = AiDrafts.SelectSources(item, await store.List(item.HotelId)); var result = await ai.Generate(item, sources, c.RequestAborted); // A knowledge edit during generation invalidates the result before it is saved. foreach (var source in sources) { var current = await store.Get(item.HotelId, source.Id); if (current?.Approved != true || current.Version != source.Version) return Input.Conflict(); } item.Draft = result.Draft.Length > 0 ? result.Draft + "\n\n" + hotel.Signature : ""; item.DraftSources = result.SourceIds; item.DraftReviewNote = result.Reason; item.Status = result.NeedsReview ? "NeedsAttention" : "DraftReady"; item.Version++; if (!await store.Replace(item.HotelId, item.Id, input.Version, item)) return Input.Conflict(); await Session.Audit(store, c, result.NeedsReview ? "AI requested staff handling" : "Generated a draft for staff review"); return Results.Ok(item); }).RequireRateLimiting("ai"); api.MapPost("/conversations/{id}/send", async (string id, SendInput input, HttpContext c, GoogleMailbox google) => { var item = await store.Get(Session.Hotel(c), id); if (item == null) return Results.NotFound(); if (item.Delivery != null) return Results.Conflict(new { error = "This message already has a delivery request. Refresh to see its status." }); var hotel = await store.Get(item.HotelId, item.HotelId); var mailbox = await store.Get(item.HotelId, item.MailboxId); if (preview || hotel?.StaffSendingEnabled != true || !google.SendingConfigured || mailbox?.CanSend != true || mailbox.Status != "Connected") return Results.BadRequest(new { error = "Enable staff sending and reconnect Google with send permission first." }); if (item.Version != input.Version) return Input.Conflict(); if (input.Recipient != item.ReplyAddress || string.IsNullOrWhiteSpace(item.ReplyAddress)) return Results.BadRequest(new { error = "The recipient must match the message's reply address." }); item.Delivery = new Delivery { MailboxEpoch=mailbox.ConnectionEpoch, Recipient = item.ReplyAddress, Body = item.Draft, ApprovedBy = c.User.FindFirstValue(ClaimTypes.NameIdentifier)! }; try { _ = ReplyMime.Build(item, mailbox); } catch { return Results.BadRequest(new { error = "This message lacks valid reply metadata or a saved draft. Reply in Gmail instead." }); } item.Version++; if (!await store.Replace(item.HotelId, item.Id, input.Version, item)) return Input.Conflict(); await Session.Audit(store, c, "Approved a saved reply for Gmail delivery"); return Results.Ok(item); }); api.MapPost("/conversations/{id}/delivery/release",async(string id,VersionInput input,HttpContext c,AutoReplyWork work)=> { var item=await store.Get(Session.Hotel(c),id);if(item==null)return Results.NotFound(); if(preview||!await work.ReturnToStaff(item,input.Version))return Input.Conflict(); await Session.Audit(store,c,"Returned an unsubmitted automatic reply to staff review");return Results.Ok(item); }); api.MapPost("/conversations/{id}/delivery/retry", async (string id, VersionInput input, HttpContext c) => { var item = await store.Get(Session.Hotel(c), id); if (item == null) return Results.NotFound(); if (preview || item.Delivery?.State != "Rejected" || item.Version != input.Version) return Input.Conflict(); var retryMailbox=await store.Get(item.HotelId,item.MailboxId); if(retryMailbox?.Status!="Connected"||!retryMailbox.CanSend)return Results.BadRequest(new{error="Reconnect the mailbox with sending permission first."}); item.Delivery.MailboxEpoch=retryMailbox.ConnectionEpoch; item.Delivery.State = "Pending"; item.Delivery.UpdatedAt = DateTime.UtcNow; item.Version++; if (!await store.Replace(item.HotelId, item.Id, input.Version, item)) return Input.Conflict(); await Session.Audit(store, c, "Retried a reply that had not reached Gmail sending"); return Results.Ok(item); }); api.MapPost("/conversations/{id}/delivery/verify", async (string id, VersionInput input, HttpContext c, GoogleMailbox google) => { var item = await store.Get(Session.Hotel(c), id); if (item == null) return Results.NotFound(); if (preview || item.Delivery?.State != "NeedsReview" || item.Version != input.Version) return Input.Conflict(); var mailbox = await store.Get(item.HotelId, item.MailboxId); if (mailbox == null) return Results.BadRequest(); var found = await google.FindSent(item, mailbox, c.RequestAborted); if (found == null) return Results.Conflict(new { error = "No unique matching sent message was found. Delivery remains uncertain; check Gmail manually. No resend was queued." }); item.Delivery.ProviderId = found; item.Delivery.State = "Sent"; item.Delivery.Detail = "Verified in Gmail Sent"; item.Delivery.UpdatedAt = DateTime.UtcNow; item.Status = "Completed"; item.Version++; if (!await store.Replace(item.HotelId, item.Id, input.Version, item)) return Input.Conflict(); await Session.Audit(store, c, "Verified uncertain delivery in Gmail Sent"); return Results.Ok(item); }); api.MapPost("/integrations/google/connect", async (HttpContext c, GoogleMailbox google) => { if (preview || !google.Configured) return Results.BadRequest(new { error = "Google connection has not been configured by the administrator." }); var state = new OAuthRequest { Id = Convert.ToHexString(RandomNumberGenerator.GetBytes(32)), HotelId = Session.Hotel(c), UserId = c.User.FindFirstValue(ClaimTypes.NameIdentifier)!, ExpiresAt = DateTime.UtcNow.AddMinutes(10) }; await store.Insert(state); return Results.Ok(new { url = google.AuthorizationUrl(state.Id) }); }).RequireAuthorization("Owner"); api.MapGet("/integrations/google/callback", async (HttpContext c, GoogleMailbox google) => { if (preview) return Results.BadRequest(); var state = await store.ConsumeOAuth(c.Request.Query["state"].ToString(), Session.Hotel(c), c.User.FindFirstValue(ClaimTypes.NameIdentifier)!); if (state == null) return Results.BadRequest(new { error = "The connection request expired. Start again from Settings." }); if (c.Request.Query.ContainsKey("error")) return Results.Redirect("/settings?google=cancelled"); try { await google.Connect(Session.Hotel(c), c.Request.Query["code"].ToString(),state.StartedAt,state.ExpectedEmail); await Session.Audit(store, c, "Connected Google mailbox"); } catch { return Results.Redirect("/settings?google=failed"); } return Results.Redirect("/settings?google=connected"); }).RequireAuthorization("Owner"); app.UseDefaultFiles(); app.UseStaticFiles(); app.MapFallbackToFile("index.html"); app.Run(); namespace GuestOps.Web { public static class Session { public static string Hotel(HttpContext c) => c.User.FindFirstValue("hotel") ?? throw new InvalidOperationException("Missing hotel membership"); public static Task SignIn(HttpContext c, StaffUser u) => c.SignInAsync(new ClaimsPrincipal(new ClaimsIdentity(new[] { new Claim(ClaimTypes.NameIdentifier, u.Id), new Claim(ClaimTypes.Name, u.Name), new Claim(ClaimTypes.Role, u.Role), new Claim("hotel", u.HotelId), new Claim("security_stamp", u.SecurityStamp) }, CookieAuthenticationDefaults.AuthenticationScheme))); public static Task Audit(IStore store, HttpContext c, string action) => store.Insert(new Activity { HotelId = Hotel(c), UserName = c.User.Identity?.Name ?? "Staff", Action = action }); } public static class Input { public static readonly string DummyHash = new PasswordHasher().HashPassword(new(), Convert.ToHexString(RandomNumberGenerator.GetBytes(32))); public static bool Text(string? s, int min, int max) => s != null && s.Trim().Length >= min && s.Length <= max; public static bool Email(string s) => System.Net.Mail.MailAddress.TryCreate(s, out var address) && address.Address == s; public static bool Knowledge(KnowledgeInput s) => Text(s.Title, 2, 120) && Text(s.Answer, 2, 5000) && Text(s.Category, 1, 50) && Text(s.Keywords, 0, 300); public static IResult Conflict() => Results.Conflict(new { error = "Someone changed this record. Reload it before saving again." }); } }