From 2f566756ffab4ae636049f010a16672d6c37127a Mon Sep 17 00:00:00 2001 From: support Date: Thu, 26 Nov 2026 19:58:51 +0100 Subject: [PATCH] Write the push notification settings into the service worker as escaped strings The settings went into firebase-messaging-sw.js between plain quotes, so a quote, a backslash or a line break typed in one of them broke the script and with it the push notifications. Each line was also found by a Contains check, so a value that mentioned another key took over that key's line on the next save. Values are now written as JSON string literals, and a line is matched by the key it starts with. --- ...SettingControllerPushNotificationsTests.cs | 90 +++++++++++++++++++ .../Controllers/SettingController.cs | 21 +++-- 2 files changed, 104 insertions(+), 7 deletions(-) create mode 100644 src/Tests/Grand.Web.Admin.Tests/Controllers/SettingControllerPushNotificationsTests.cs diff --git a/src/Tests/Grand.Web.Admin.Tests/Controllers/SettingControllerPushNotificationsTests.cs b/src/Tests/Grand.Web.Admin.Tests/Controllers/SettingControllerPushNotificationsTests.cs new file mode 100644 index 000000000..5239d835b --- /dev/null +++ b/src/Tests/Grand.Web.Admin.Tests/Controllers/SettingControllerPushNotificationsTests.cs @@ -0,0 +1,90 @@ +using Grand.Business.Core.Interfaces.Checkout.Orders; +using Grand.Business.Core.Interfaces.Common.Configuration; +using Grand.Business.Core.Interfaces.Common.Directory; +using Grand.Business.Core.Interfaces.Common.Localization; +using Grand.Business.Core.Interfaces.Storage; +using Grand.Domain.PushNotifications; +using Grand.Infrastructure.Caching; +using Grand.Infrastructure.Mapper; +using Grand.Mapping; +using Grand.Web.Admin.Controllers; +using Grand.Web.AdminShared.Mapper; +using Grand.Web.AdminShared.Models.Settings; +using Grand.Web.Common.Helpers; +using Grand.Web.Common.Localization; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.ViewFeatures; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.VisualStudio.TestTools.UnitTesting; +using Moq; + +namespace Grand.Web.Admin.Tests.Controllers; + +[TestClass] +public class SettingControllerPushNotificationsTests +{ + private const string Template = "var config = {\napiKey: \"\",\nappId: \"\",\nauthDomain: \"\",\ndatabaseURL: \"\",\nprojectId: \"\",\nstorageBucket: \"\",\nmessagingSenderId: \"\",\n};"; + private SettingController _controller; + private Mock _fileStore; + private string _written; + + [TestInitialize] + public void Init() + { + AutoMapperConfig.Init(new MapperConfiguration(cfg => cfg.AddProfile())); + var settingService = new Mock(); + settingService.Setup(x => x.LoadSetting(It.IsAny())) + .ReturnsAsync(new PushNotificationsSettings()); + + _fileStore = new Mock(); + _fileStore.Setup(x => x.GetFileInfo("firebase-messaging-sw.js")).ReturnsAsync(new Mock().Object); + _fileStore.Setup(x => x.ReadAllText("firebase-messaging-sw.js")).ReturnsAsync(() => _written ?? Template); + _fileStore.Setup(x => x.WriteAllText("firebase-messaging-sw.js", It.IsAny())) + .Callback((_, text) => _written = text) + .Returns(Task.CompletedTask); + + var adminStoreService = new Mock(); + adminStoreService.Setup(x => x.GetActiveStore()).ReturnsAsync(""); + var services = new ServiceCollection().AddSingleton(adminStoreService.Object).BuildServiceProvider(); + var httpContext = new DefaultHttpContext { RequestServices = services }; + + _controller = new SettingController(settingService.Object, new Mock().Object, + new Mock().Object, new Mock().Object, + new Mock().Object, new Mock().Object, + new Mock().Object) { + ControllerContext = new ControllerContext { HttpContext = httpContext }, + TempData = new TempDataDictionary(httpContext, new Mock().Object), + Url = new Mock().Object + }; + } + + [TestMethod] + public async Task PushNotifications_Post_WritesValuesAsJavaScriptStrings() + { + var model = new PushNotificationsSettingsModel { + PushApiKey = "key\"; alert(1); \"", AuthDomain = "back\\slash", ProjectId = "line\nbreak", AppId = "app-1" + }; + + await _controller.PushNotifications(model, _fileStore.Object); + + StringAssert.Contains(_written, "apiKey: \"key\\u0022; alert(1); \\u0022\","); + StringAssert.Contains(_written, "authDomain: \"back\\\\slash\","); + StringAssert.Contains(_written, "projectId: \"line\\nbreak\","); + StringAssert.Contains(_written, "appId: \"app-1\","); + } + + [TestMethod] + public async Task PushNotifications_Post_ValueNamingAnotherKey_ReplacesOnlyItsOwnLine() + { + await _controller.PushNotifications(new PushNotificationsSettingsModel { PushApiKey = "appId", AppId = "first" }, + _fileStore.Object); + + //saved again: the apiKey line now mentions appId, it must stay the apiKey line + await _controller.PushNotifications(new PushNotificationsSettingsModel { PushApiKey = "appId", AppId = "second" }, + _fileStore.Object); + + StringAssert.Contains(_written, "apiKey: \"appId\","); + StringAssert.Contains(_written, "appId: \"second\","); + } +} diff --git a/src/Web/Grand.Web.Admin/Controllers/SettingController.cs b/src/Web/Grand.Web.Admin/Controllers/SettingController.cs index 009d80ea9..e5bfd638d 100644 --- a/src/Web/Grand.Web.Admin/Controllers/SettingController.cs +++ b/src/Web/Grand.Web.Admin/Controllers/SettingController.cs @@ -38,6 +38,7 @@ using Grand.Mediator; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; +using System.Text.Json; using OperatingSystem = Grand.Infrastructure.OperatingSystem; namespace Grand.Web.Admin.Controllers; @@ -801,17 +802,23 @@ private static string[] UpdateFileLines(string[] lines, PushNotificationsSetting { for (var i = 0; i < lines.Length; i++) { - if (lines[i].Contains("apiKey")) lines[i] = $"apiKey: \"{model.PushApiKey}\","; - if (lines[i].Contains("authDomain")) lines[i] = $"authDomain: \"{model.AuthDomain}\","; - if (lines[i].Contains("databaseURL")) lines[i] = $"databaseURL: \"{model.DatabaseUrl}\","; - if (lines[i].Contains("projectId")) lines[i] = $"projectId: \"{model.ProjectId}\","; - if (lines[i].Contains("storageBucket")) lines[i] = $"storageBucket: \"{model.StorageBucket}\","; - if (lines[i].Contains("messagingSenderId")) lines[i] = $"messagingSenderId: \"{model.SenderId}\","; - if (lines[i].Contains("appId")) lines[i] = $"appId: \"{model.AppId}\","; + if (IsKeyLine(lines[i], "apiKey")) lines[i] = $"apiKey: {JsString(model.PushApiKey)},"; + if (IsKeyLine(lines[i], "authDomain")) lines[i] = $"authDomain: {JsString(model.AuthDomain)},"; + if (IsKeyLine(lines[i], "databaseURL")) lines[i] = $"databaseURL: {JsString(model.DatabaseUrl)},"; + if (IsKeyLine(lines[i], "projectId")) lines[i] = $"projectId: {JsString(model.ProjectId)},"; + if (IsKeyLine(lines[i], "storageBucket")) lines[i] = $"storageBucket: {JsString(model.StorageBucket)},"; + if (IsKeyLine(lines[i], "messagingSenderId")) lines[i] = $"messagingSenderId: {JsString(model.SenderId)},"; + if (IsKeyLine(lines[i], "appId")) lines[i] = $"appId: {JsString(model.AppId)},"; } return lines; } + //the line of the template that sets the key, not any line whose value mentions it + private static bool IsKeyLine(string line, string key) => line.TrimStart().StartsWith(key + ":", StringComparison.Ordinal); + + //a JavaScript string literal: a quote, a backslash or a line break typed in a setting must not end it + private static string JsString(string value) => JsonSerializer.Serialize(value ?? ""); + public async Task AdminSearch() { var settings = await settingService.LoadSetting();