diff --git a/EssentialCSharp.Chat.Shared/Models/AIOptions.cs b/EssentialCSharp.Chat.Shared/Models/AIOptions.cs index d0574fba..5fb2d13e 100644 --- a/EssentialCSharp.Chat.Shared/Models/AIOptions.cs +++ b/EssentialCSharp.Chat.Shared/Models/AIOptions.cs @@ -53,4 +53,13 @@ public class AIOptions /// MCP tools. Should only be set in non-production environments. /// public bool AllowAllMcpTools { get; set; } + + /// + /// Maximum tokens the model may generate for one chat response, including reasoning tokens. + /// Bounds the cost of a single request. Set to 0 to leave the provider's default (no app-side cap). + /// + public int MaxOutputTokens { get; set; } = DefaultMaxOutputTokens; + + /// Default for . + public const int DefaultMaxOutputTokens = 8192; } diff --git a/EssentialCSharp.Chat.Shared/Services/AIChatService.cs b/EssentialCSharp.Chat.Shared/Services/AIChatService.cs index 7a94f920..1165c548 100644 --- a/EssentialCSharp.Chat.Shared/Services/AIChatService.cs +++ b/EssentialCSharp.Chat.Shared/Services/AIChatService.cs @@ -519,6 +519,16 @@ private async Task CreateResponseOptionsAsync( } } + // Bound what one request can cost: cap the output, and let the provider drop the oldest turns of a long + // conversation (continued through previous_response_id) instead of sending the whole chain every time. + if (_Options.MaxOutputTokens > 0) + { + options.MaxOutputTokenCount = _Options.MaxOutputTokens; + } +#pragma warning disable OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. + options.TruncationMode = ResponseTruncationMode.Auto; +#pragma warning restore OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. + // Add reasoning options if specified if (reasoningEffortLevel.HasValue) { diff --git a/EssentialCSharp.Chat.Tests/AIChatServiceCostLimitTests.cs b/EssentialCSharp.Chat.Tests/AIChatServiceCostLimitTests.cs new file mode 100644 index 00000000..403d33bc --- /dev/null +++ b/EssentialCSharp.Chat.Tests/AIChatServiceCostLimitTests.cs @@ -0,0 +1,84 @@ +using System.ClientModel; +using System.ClientModel.Primitives; +using System.Net; +using System.Text; +using System.Text.Json; +using EssentialCSharp.Chat; +using EssentialCSharp.Chat.Common.Services; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using OpenAI.Responses; + +namespace EssentialCSharp.Chat.Tests; + +/// +/// Regression tests: every chat request sent to the model provider caps its output and lets the provider truncate a +/// long continued conversation, so one permitted request can't run up an unbounded token bill. +/// +public class AIChatServiceCostLimitTests +{ + [Test] + public async Task GetChatCompletion_SendsTheConfiguredOutputCapAndAutoTruncation() + { + CapturingHandler handler = new(); + AIChatService service = CreateService(handler, new AIOptions { ChatDeploymentName = "test-deployment", MaxOutputTokens = 1234 }); + + await service.GetChatCompletion("hello", previousResponseId: "resp_previous"); + + using JsonDocument body = JsonDocument.Parse(handler.LastRequestBody!); + using (Assert.Multiple()) + { + await Assert.That(body.RootElement.GetProperty("max_output_tokens").GetInt32()).IsEqualTo(1234); + await Assert.That(body.RootElement.GetProperty("truncation").GetString()).IsEqualTo("auto"); + await Assert.That(body.RootElement.GetProperty("previous_response_id").GetString()).IsEqualTo("resp_previous"); + } + } + + [Test] + public async Task GetChatCompletion_UsesADefaultOutputCapWhenNoneIsConfigured() + { + CapturingHandler handler = new(); + AIChatService service = CreateService(handler, new AIOptions { ChatDeploymentName = "test-deployment" }); + + await service.GetChatCompletion("hello"); + + using JsonDocument body = JsonDocument.Parse(handler.LastRequestBody!); + await Assert.That(body.RootElement.GetProperty("max_output_tokens").GetInt32()).IsEqualTo(AIOptions.DefaultMaxOutputTokens); + } + + private static AIChatService CreateService(CapturingHandler handler, AIOptions aiOptions) + { +#pragma warning disable OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. + ResponsesClientOptions options = new() + { + Endpoint = new Uri("http://localhost/openai/deployments/test-deployment"), + Transport = new HttpClientPipelineTransport(new HttpClient(handler)), + }; + ResponsesClient responseClient = new(new ApiKeyCredential("test-key"), options); +#pragma warning restore OPENAI001 // Type is for evaluation purposes only and is subject to change or removal in future updates. Suppress this diagnostic to proceed. + + return new AIChatService(Options.Create(aiOptions), searchService: null!, responseClient, NullLogger.Instance); + } + + private sealed class CapturingHandler : HttpMessageHandler + { + private const string CompletedResponse = + """{"id":"resp_new","object":"response","created_at":0,"status":"completed","model":"test-deployment","output":[{"id":"msg_1","type":"message","status":"completed","role":"assistant","content":[{"type":"output_text","text":"hi","annotations":[]}]}]}"""; + + public string? LastRequestBody { get; private set; } + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + LastRequestBody = request.Content is null ? null : await request.Content.ReadAsStringAsync(cancellationToken); + return CreateResponse(); + } + + // The response goes to the HttpClient pipeline, which disposes it. + private static HttpResponseMessage CreateResponse() + { + HttpResponseMessage response = new(HttpStatusCode.OK); + response.Content = new StringContent(CompletedResponse, Encoding.UTF8, "application/json"); + return response; + } + } +} diff --git a/EssentialCSharp.Web.Tests/ChatRateLimitTests.cs b/EssentialCSharp.Web.Tests/ChatRateLimitTests.cs new file mode 100644 index 00000000..55631355 --- /dev/null +++ b/EssentialCSharp.Web.Tests/ChatRateLimitTests.cs @@ -0,0 +1,54 @@ +using System.Net; +using System.Net.Http.Json; +using EssentialCSharp.Web.Services; +using Microsoft.AspNetCore.Mvc.Testing; +using Microsoft.Extensions.DependencyInjection; + +namespace EssentialCSharp.Web.Tests; + +/// +/// Regression tests: the configured ChatThrottling per-window message cap is enforced per user, in addition to +/// the per-minute burst limit. It used to exist only in configuration. +/// +public class ChatRateLimitTests : IntegrationTestBase +{ + private const string HCaptchaTestToken = "10000000-aaaa-bbbb-cccc-000000000001"; + + private static async Task SendChatMessageAsync(HttpClient client, (string Name, string Value) cookie) + { + using HttpRequestMessage request = new(HttpMethod.Post, "/api/chat/message") + { + Content = JsonContent.Create(new { message = "Hello", enableContextualSearch = false, captchaResponse = HCaptchaTestToken }) + }; + McpTestHelper.AddCookie(request, cookie.Name, cookie.Value); + using HttpResponseMessage response = await client.SendAsync(request); + return response.StatusCode; + } + + [Test] + public async Task ChatMessages_BeyondTheConfiguredWindowCap_AreRejectedWith429() + { + WebApplicationFactory factory = Factory.Inner.WithWebHostBuilder(builder => builder.ConfigureServices(services => + services.PostConfigure(options => options.MaxMessagesPerWindow = 3))); + HttpClient client = factory.CreateClient(new WebApplicationFactoryClientOptions { AllowAutoRedirect = false }); + string userId = await McpTestHelper.CreateUserAsync(factory.Services, "chat-hourly-cap"); + (string Name, string Value) cookie = await McpTestHelper.CreateIdentityApplicationCookieAsync(factory.Services, userId); + string otherUserId = await McpTestHelper.CreateUserAsync(factory.Services, "chat-hourly-cap-other"); + (string Name, string Value) otherCookie = await McpTestHelper.CreateIdentityApplicationCookieAsync(factory.Services, otherUserId); + + List statuses = []; + for (int i = 0; i < 4; i++) + { + statuses.Add(await SendChatMessageAsync(client, cookie)); + } + HttpStatusCode otherUser = await SendChatMessageAsync(client, otherCookie); + + using (Assert.Multiple()) + { + // The test chat backend is unavailable, so permitted requests return 503. + await Assert.That(statuses.Take(3)).DoesNotContain(HttpStatusCode.TooManyRequests); + await Assert.That(statuses[3]).IsEqualTo(HttpStatusCode.TooManyRequests); + await Assert.That(otherUser).IsNotEqualTo(HttpStatusCode.TooManyRequests); + } + } +} diff --git a/EssentialCSharp.Web.Tests/ChatStorageIsolationTests.cs b/EssentialCSharp.Web.Tests/ChatStorageIsolationTests.cs new file mode 100644 index 00000000..69eae9fe --- /dev/null +++ b/EssentialCSharp.Web.Tests/ChatStorageIsolationTests.cs @@ -0,0 +1,85 @@ +using System.Net; +using System.Text.RegularExpressions; + +namespace EssentialCSharp.Web.Tests; + +/// +/// Regression tests: AI chat history kept in browser storage must not carry over to the next account that signs in +/// on the same browser. Logout clears site storage, and each page tells the chat widget whose state it may reuse. +/// +public partial class ChatStorageIsolationTests : IntegrationTestBase +{ + [GeneratedRegex("window\\.CHAT_STORAGE_OWNER = (null|\"[0-9A-F]{32}\");")] + private static partial Regex StorageOwnerScript(); + + private static async Task GetStorageOwnerAsync(HttpClient client, (string Name, string Value)? cookie) + { + using HttpRequestMessage request = new(HttpMethod.Get, "/home"); + if (cookie is { } c) + { + McpTestHelper.AddCookie(request, c.Name, c.Value); + } + using HttpResponseMessage response = await client.SendAsync(request); + Match match = StorageOwnerScript().Match(await response.Content.ReadAsStringAsync()); + if (!match.Success) + { + throw new InvalidOperationException($"CHAT_STORAGE_OWNER not found on /home ({(int)response.StatusCode})."); + } + return match.Groups[1].Value; + } + + [Test] + public async Task Logout_ClearsSiteStorage() + { + string userId = await McpTestHelper.CreateUserAsync(Factory, "chat-logout"); + (string Name, string Value) cookie = await McpTestHelper.CreateIdentityApplicationCookieAsync(Factory, userId); + using HttpClient client = CreateClientWithoutAutoRedirect(); + + using HttpRequestMessage page = new(HttpMethod.Get, "/Identity/Account/Logout"); + McpTestHelper.AddCookie(page, cookie.Name, cookie.Value); + using HttpResponseMessage pageResponse = await client.SendAsync(page); + string html = await pageResponse.Content.ReadAsStringAsync(); + string token = Regex.Match(html, "name=\"__RequestVerificationToken\"[^>]*value=\"([^\"]+)\"").Groups[1].Value; + string antiforgeryCookie = pageResponse.Headers.GetValues("Set-Cookie") + .Select(v => v.Split(';')[0]) + .First(v => v.StartsWith(".AspNetCore.Antiforgery.", StringComparison.Ordinal)); + + using HttpRequestMessage logout = new(HttpMethod.Post, "/Identity/Account/Logout") + { + Content = new FormUrlEncodedContent(new Dictionary { ["__RequestVerificationToken"] = token }) + }; + logout.Headers.Add("Cookie", $"{cookie.Name}={cookie.Value}; {antiforgeryCookie}"); + using HttpResponseMessage response = await client.SendAsync(logout); + + using (Assert.Multiple()) + { + await Assert.That(response.StatusCode).IsEqualTo(HttpStatusCode.Redirect); + await Assert.That(response.Headers.TryGetValues("Clear-Site-Data", out IEnumerable? values)).IsTrue(); + await Assert.That(string.Join(",", values ?? [])).IsEqualTo("\"storage\""); + } + } + + [Test] + public async Task Pages_ExposeAStorageOwnerThatDiffersPerUserAndIsNullWhenSignedOut() + { + string userA = await McpTestHelper.CreateUserAsync(Factory, "chat-owner-a"); + string userB = await McpTestHelper.CreateUserAsync(Factory, "chat-owner-b"); + (string Name, string Value) cookieA = await McpTestHelper.CreateIdentityApplicationCookieAsync(Factory, userA); + (string Name, string Value) cookieB = await McpTestHelper.CreateIdentityApplicationCookieAsync(Factory, userB); + using HttpClient client = CreateClientWithoutAutoRedirect(); + + string ownerA = await GetStorageOwnerAsync(client, cookieA); + string ownerAAgain = await GetStorageOwnerAsync(client, cookieA); + string ownerB = await GetStorageOwnerAsync(client, cookieB); + string anonymous = await GetStorageOwnerAsync(client, null); + + using (Assert.Multiple()) + { + await Assert.That(ownerA).IsNotEqualTo("null"); + await Assert.That(ownerA).IsEqualTo(ownerAAgain); + await Assert.That(ownerB).IsNotEqualTo(ownerA); + await Assert.That(anonymous).IsEqualTo("null"); + await Assert.That(ownerA).DoesNotContain(userA); + } + } +} diff --git a/EssentialCSharp.Web/Areas/Identity/Pages/Account/Logout.cshtml.cs b/EssentialCSharp.Web/Areas/Identity/Pages/Account/Logout.cshtml.cs index 3d19b48c..0c98b3e4 100644 --- a/EssentialCSharp.Web/Areas/Identity/Pages/Account/Logout.cshtml.cs +++ b/EssentialCSharp.Web/Areas/Identity/Pages/Account/Logout.cshtml.cs @@ -11,11 +11,16 @@ public async Task OnPost(string? returnUrl = null) { await signInManager.SignOutAsync(); LogUserLoggedOut(logger); + // Remove what the signed-in user left in browser storage (the AI chat history and its conversation ID), + // so the next person to sign in on this browser doesn't see or continue it. Browsers honor this on HTTPS. + Response.Headers["Clear-Site-Data"] = ClearSiteDataStorage; // This needs to be a redirect so that the browser performs a new // request and the identity for the user gets updated. return returnUrl is not null ? LocalRedirect(returnUrl) : RedirectToPage(); } + internal const string ClearSiteDataStorage = "\"storage\""; + [LoggerMessage(Level = LogLevel.Information, Message = "User logged out.")] private static partial void LogUserLoggedOut(ILogger logger); } diff --git a/EssentialCSharp.Web/Extensions/ClaimsExtensions.cs b/EssentialCSharp.Web/Extensions/ClaimsExtensions.cs index b969f5cf..ffff9b32 100644 --- a/EssentialCSharp.Web/Extensions/ClaimsExtensions.cs +++ b/EssentialCSharp.Web/Extensions/ClaimsExtensions.cs @@ -1,4 +1,6 @@ using System.Security.Claims; +using System.Security.Cryptography; +using System.Text; namespace EssentialCSharp.Web.Extensions; @@ -24,5 +26,22 @@ public static class ClaimsExtensions return httpContext?.User?.GetReferrerId(); } + /// + /// A non-secret marker of the signed-in user that the browser stores next to the AI chat history, so a page + /// loaded by a different account (or after sign-out) can tell the stored conversation isn't its own. + /// + /// A hash of the user ID, or when nobody is signed in. + public static string? GetChatStorageOwner(this ClaimsPrincipal claimsPrincipal) + { + if (claimsPrincipal.Identity?.IsAuthenticated != true + || claimsPrincipal.FindFirstValue(ClaimTypes.NameIdentifier) is not { Length: > 0 } userId) + { + return null; + } + + byte[] hash = SHA256.HashData(Encoding.UTF8.GetBytes($"EssentialCSharp.ChatStorageOwner:{userId}")); + return Convert.ToHexString(hash, 0, 16); + } + public const string ReferrerIdClaimType = "ReferrerId"; } diff --git a/EssentialCSharp.Web/Program.cs b/EssentialCSharp.Web/Program.cs index 38d55fb0..96ef322e 100644 --- a/EssentialCSharp.Web/Program.cs +++ b/EssentialCSharp.Web/Program.cs @@ -176,6 +176,10 @@ private static void Main(string[] args) builder.Services.AddMailjetEmailSender(builder.Configuration.GetSection(AuthMessageSenderOptions.AuthMessageSender), builder.Environment); builder.Services.Configure(builder.Configuration.GetSection(SiteSettings.SectionName)); builder.Services.Configure(builder.Configuration.GetSection(ContentRateLimitOptions.SectionName)); + builder.Services.AddOptions() + .Bind(builder.Configuration.GetSection(ChatThrottlingOptions.SectionName)) + .ValidateDataAnnotations() + .ValidateOnStart(); // Add services to the container. builder.Services.AddRazorPages(); @@ -253,23 +257,9 @@ private static void Main(string[] args) }); }); - options.AddPolicy("ChatEndpoint", httpContext => - { - // Partitioned per-user (when authenticated) or per-IP (anonymous) - var partitionKey = httpContext.User.Identity?.IsAuthenticated == true - ? $"chat-user:{httpContext.User.FindFirstValue(ClaimTypes.NameIdentifier) ?? "unknown-user"}" - : $"chat-ip:{httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown-ip"}"; - - return RateLimitPartition.GetFixedWindowLimiter( - partitionKey: partitionKey, - factory: _ => new FixedWindowRateLimiterOptions - { - PermitLimit = 15, - Window = TimeSpan.FromMinutes(1), - QueueProcessingOrder = QueueProcessingOrder.OldestFirst, - QueueLimit = 0 - }); - }); + // 15 per minute plus the configured ChatThrottling per-window cap, per user (or IP when anonymous). + // See Services/ChatRateLimiterPolicy.cs. + options.AddPolicy(ChatRateLimiterPolicy.PolicyName); // Combined per-minute burst (10/min) + per-hour cap (150/hr) for book content pages. // A scraper cycling through the full ~400-page book needs 2+ hours at minimum. diff --git a/EssentialCSharp.Web/Services/ChatRateLimiterPolicy.cs b/EssentialCSharp.Web/Services/ChatRateLimiterPolicy.cs new file mode 100644 index 00000000..5de23b85 --- /dev/null +++ b/EssentialCSharp.Web/Services/ChatRateLimiterPolicy.cs @@ -0,0 +1,59 @@ +using System.ComponentModel.DataAnnotations; +using System.Security.Claims; +using System.Threading.RateLimiting; +using Microsoft.AspNetCore.RateLimiting; +using Microsoft.Extensions.Options; + +namespace EssentialCSharp.Web.Services; + +/// Configuration section ChatThrottling. +public sealed class ChatThrottlingOptions +{ + public const string SectionName = "ChatThrottling"; + + /// Length of the longer chat budget window, in minutes. + [Range(1, 24 * 60)] + public int ThrottlingWindowMinutes { get; set; } = 60; + + /// Messages one user (or one IP, when anonymous) may send per . + [Range(1, 10_000)] + public int MaxMessagesPerWindow { get; set; } = 50; +} + +/// +/// Rate limiting for the chat API: a 15-per-minute burst limit chained with the configured +/// per , +/// both partitioned by user ID (or IP when anonymous). +/// +internal sealed class ChatRateLimiterPolicy(IOptions options) : IRateLimiterPolicy +{ + internal const string PolicyName = "ChatEndpoint"; + internal const int PerMinuteLimit = 15; + + // Null defers to the global OnRejected handler registered in Program.cs, which writes the JSON error. + public Func? OnRejected => null; + + public RateLimitPartition GetPartition(HttpContext httpContext) + { + string partitionKey = httpContext.User.Identity?.IsAuthenticated == true + ? $"chat-user:{httpContext.User.FindFirstValue(ClaimTypes.NameIdentifier) ?? "unknown-user"}" + : $"chat-ip:{httpContext.Connection.RemoteIpAddress?.ToString() ?? "unknown-ip"}"; + + ChatThrottlingOptions throttling = options.Value; + return RateLimitPartition.Get(partitionKey, _ => new CombinedRateLimiter( + new FixedWindowRateLimiter(new FixedWindowRateLimiterOptions + { + PermitLimit = PerMinuteLimit, + Window = TimeSpan.FromMinutes(1), + QueueProcessingOrder = QueueProcessingOrder.OldestFirst, + QueueLimit = 0 + }), + new FixedWindowRateLimiter(new FixedWindowRateLimiterOptions + { + PermitLimit = throttling.MaxMessagesPerWindow, + Window = TimeSpan.FromMinutes(throttling.ThrottlingWindowMinutes), + QueueProcessingOrder = QueueProcessingOrder.OldestFirst, + QueueLimit = 0 + }))); + } +} diff --git a/EssentialCSharp.Web/Views/Home/CookiePolicy.cshtml b/EssentialCSharp.Web/Views/Home/CookiePolicy.cshtml index 876688a8..d5f464ec 100644 --- a/EssentialCSharp.Web/Views/Home/CookiePolicy.cshtml +++ b/EssentialCSharp.Web/Views/Home/CookiePolicy.cshtml @@ -99,13 +99,13 @@ aiChatHistory localStorage Stores recent authenticated AI chat messages in your browser so the chat widget can restore the latest conversation state. - Up to 2 hours unless you clear it sooner + Up to 2 hours, or until you log out, unless you clear it sooner aiChatLastResponseId sessionStorage Stores the last AI response identifier for the current tab to continue the active chat safely. - Current browser tab session + Current browser tab session, or until you log out sidebarShown diff --git a/EssentialCSharp.Web/Views/Shared/_Layout.cshtml b/EssentialCSharp.Web/Views/Shared/_Layout.cshtml index cab6bfa6..4f6e89d0 100644 --- a/EssentialCSharp.Web/Views/Shared/_Layout.cshtml +++ b/EssentialCSharp.Web/Views/Shared/_Layout.cshtml @@ -222,6 +222,7 @@ window.TOC_DATA = @Json.Serialize(tocData); window.REFERRAL_ID = @Json.Serialize(ViewBag.ReferralId); window.IS_AUTHENTICATED = @Json.Serialize(SignInManager.IsSignedIn(User)); + window.CHAT_STORAGE_OWNER = @Json.Serialize(SignInManager.IsSignedIn(User) ? User.GetChatStorageOwner() : null); window.TRYDOTNET_ORIGIN = @Json.Serialize(Configuration["TryDotNet:Origin"]); window.APPLICATIONINSIGHTS_CONNECTION_STRING = @Json.Serialize(Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"]); window.APPLICATIONINSIGHTS_APP_ID = @Json.Serialize(Configuration["APPLICATIONINSIGHTS_APP_ID"]); diff --git a/EssentialCSharp.Web/wwwroot/js/chat-module.js b/EssentialCSharp.Web/wwwroot/js/chat-module.js index 57fd64ed..0722c775 100644 --- a/EssentialCSharp.Web/wwwroot/js/chat-module.js +++ b/EssentialCSharp.Web/wwwroot/js/chat-module.js @@ -24,6 +24,52 @@ function getTraceHeaders() { return headers; } +const chatHistoryKey = 'aiChatHistory'; +const lastResponseIdKey = 'aiChatLastResponseId'; + +/** + * Stored chat state belongs to one account. Returns the stored history and response ID only when they were saved + * for `owner` (the signed-in user's marker); otherwise removes them, so the next account on a shared browser + * neither sees the previous user's conversation nor continues it. Exported for tests. + */ +export function readOwnedChatState(owner, local = localStorage, session = sessionStorage, now = Date.now()) { + const clear = () => { + local.removeItem(chatHistoryKey); + session.removeItem(lastResponseIdKey); + return { messages: [], lastResponseId: null }; + }; + if (!owner) { + return clear(); + } + + let history = null; + let responseState = null; + try { + const savedHistory = local.getItem(chatHistoryKey); + history = savedHistory ? JSON.parse(savedHistory) : null; + const savedResponse = session.getItem(lastResponseIdKey); + responseState = savedResponse ? JSON.parse(savedResponse) : null; + } catch { + return clear(); + } + + // Older saves have no owner, so they can't be attributed to this user either. + if ((history && history.owner !== owner) || (responseState && responseState.owner !== owner)) { + return clear(); + } + + // Reject history older than 2 hours to align with server-side response ID cache window + const twoHoursMs = 2 * 60 * 60 * 1000; + if (history && !(history.timestamp && (now - history.timestamp) < twoHoursMs)) { + return clear(); + } + + return { + messages: history?.messages || [], + lastResponseId: typeof responseState?.id === 'string' ? responseState.id : null + }; +} + // The server rejects contextual search for backends without support (e.g. local Ollama). const chatSupportsContextualSearch = window.CHAT_SUPPORTS_CONTEXTUAL_SEARCH !== false; @@ -140,6 +186,8 @@ function resetCaptchaWidget() { export function useChatWidget() { // Authentication state const isAuthenticated = ref(window.IS_AUTHENTICATED || false); + // Non-secret marker of the signed-in user; stored chat state is only reused for the same marker. + const storageOwner = window.IS_AUTHENTICATED ? (window.CHAT_STORAGE_OWNER || null) : null; // Chat state with persistence const showChatDialog = ref(false); @@ -153,21 +201,11 @@ export function useChatWidget() { // Load chat history from localStorage on initialization function loadChatHistory() { try { - const saved = localStorage.getItem('aiChatHistory'); - if (saved) { - const data = JSON.parse(saved); - // Reject history older than 2 hours to align with server-side response ID cache window - const twoHoursMs = 2 * 60 * 60 * 1000; - if (data.timestamp && (Date.now() - data.timestamp) < twoHoursMs) { - chatMessages.value = data.messages || []; - } else { - localStorage.removeItem('aiChatHistory'); - // Clear the stale response ID too — it belongs to the expired session - sessionStorage.removeItem('aiChatLastResponseId'); - } - } + // Clears storage when nobody is signed in or it was saved by another account. + const state = readOwnedChatState(storageOwner); + chatMessages.value = state.messages; // lastResponseId is kept in sessionStorage (clears on tab close) to limit persistent exposure - lastResponseId.value = sessionStorage.getItem('aiChatLastResponseId') || null; + lastResponseId.value = state.lastResponseId; } catch (error) { console.warn('Failed to load chat history:', error); } @@ -180,16 +218,20 @@ export function useChatWidget() { const maxMessages = 100; const messagesToSave = chatMessages.value.slice(-maxMessages); + if (!storageOwner) { + return; + } const data = { + owner: storageOwner, messages: messagesToSave, timestamp: Date.now() }; - localStorage.setItem('aiChatHistory', JSON.stringify(data)); + localStorage.setItem(chatHistoryKey, JSON.stringify(data)); // Store lastResponseId in sessionStorage — it clears on tab close, reducing persistent exposure if (lastResponseId.value) { - sessionStorage.setItem('aiChatLastResponseId', lastResponseId.value); + sessionStorage.setItem(lastResponseIdKey, JSON.stringify({ owner: storageOwner, id: lastResponseId.value })); } else { - sessionStorage.removeItem('aiChatLastResponseId'); + sessionStorage.removeItem(lastResponseIdKey); } } catch (error) { console.warn('Failed to save chat history:', error); @@ -197,10 +239,11 @@ export function useChatWidget() { try { const recentMessages = chatMessages.value.slice(-20); const fallbackData = { + owner: storageOwner, messages: recentMessages, timestamp: Date.now() }; - localStorage.setItem('aiChatHistory', JSON.stringify(fallbackData)); + localStorage.setItem(chatHistoryKey, JSON.stringify(fallbackData)); } catch (fallbackError) { console.error('Failed to save even minimal chat history:', fallbackError); } @@ -246,8 +289,8 @@ export function useChatWidget() { function clearChatHistory() { chatMessages.value = []; lastResponseId.value = null; - localStorage.removeItem('aiChatHistory'); - sessionStorage.removeItem('aiChatLastResponseId'); + localStorage.removeItem(chatHistoryKey); + sessionStorage.removeItem(lastResponseIdKey); // Force a scroll to top to make it obvious the messages are gone nextTick(() => {