feat: remote config for compat

This commit is contained in:
AdenMGB committed 2026-10-30 19:34:57 +10:30
1 parent c043d4dfaa
commit db7fff63e3
25 files changed
+1392 -31

No files matched your search

+27 -6
View File
@@ -12,6 +12,14 @@ import { initializeHideSensitiveToggle } from "@/seqta/utils/hideSensitiveToggle
import { installSeqtaMenuColourPatch } from "@/seqta/utils/patchSeqtaMenuUpdateColours";
import { installThemeImagePagePatch } from "@/seqta/utils/patchThemeImagesPageContext";
import { initVerboseLogging, verboseInfo } from "@/utils/verboseLog";
import {
hydrateRemoteConfigFromStorage,
installRemoteConfigStorageListener,
isEffectiveBsplusEnabled,
notifyRemoteConfigPageContext,
ensureKilledModeSettingsAccess,
} from "@/seqta/utils/remoteConfig/runtime";
import { runStartupPopupQueue } from "@/seqta/utils/Openers/StartupPopupQueue";
function registerFetchSeqtaAppLinkListener() {
browser.runtime.onMessage.addListener((request, _sender, sendResponse) => {
@@ -113,14 +121,27 @@ async function init() {
await delay(5);
}
await main();
await hydrateRemoteConfigFromStorage();
notifyRemoteConfigPageContext(location.hostname);
installRemoteConfigStorageListener(() => {
location.reload();
});
const { init: Monofile } = await import("@/plugins/monofile");
Monofile();
const bsplusEnabled = isEffectiveBsplusEnabled();
if (settingsState.onoff) {
const { initializePlugins } = await import("@/plugins/index");
await initializePlugins();
if (bsplusEnabled) {
await main();
const { init: Monofile } = await import("@/plugins/monofile");
Monofile();
if (settingsState.onoff) {
const { initializePlugins } = await import("@/plugins/index");
await initializePlugins();
}
} else {
await ensureKilledModeSettingsAccess();
void runStartupPopupQueue();
}
if (settingsState.devMode) {
+17 -1
View File
@@ -19,7 +19,12 @@ import {
registerGoogleCalendarMessageHandlers,
registerOutlookCalendarMessageHandlers,
} from "./background/calendarBackground";
import { createCustomThemesHandlers } from "./background/customThemesHandlers";
import {
createRemoteConfigHandlers,
initRemoteConfigBackground,
refreshRemoteConfig,
} from "./background/remoteConfig";
import { BSPLUS_INSTALL_REGISTERED_AT_KEY } from "@/seqta/utils/remoteConfig/storageKeys";
import { handleSearchThemeStockPhotos } from "./background/searchThemeStockPhotos";
import { initTimetableClassmatesBackgroundSync } from "./background/timetableClassmatesSync";
@@ -515,8 +520,11 @@ const customThemesHandlers = createCustomThemesHandlers({
getAccessTokenFromStorage,
});
const remoteConfigHandlers = createRemoteConfigHandlers(apiBase);
const MESSAGE_HANDLERS: Record<string, MessageHandler> = {
...customThemesHandlers,
...remoteConfigHandlers,
searchThemeStockPhotos: handleSearchThemeStockPhotos,
reloadTabs: () => reloadSeqtaPages(),
setDevApiBase: handleSetDevApiBase,
@@ -765,8 +773,15 @@ browser.runtime.onInstalled.addListener(function (event) {
void migrateGlobalSearchDefaultsFor365Upgrade(event.previousVersion);
void resetThemeOfTheMonthDisabledFor366Upgrade(event.previousVersion);
void resetThemeOfTheMonthDismissalFor370Upgrade(event.previousVersion);
void browser.storage.local.remove(BSPLUS_INSTALL_REGISTERED_AT_KEY).then(() => {
void refreshRemoteConfig(apiBase);
});
reloadSeqtaPages();
}
if (event.reason === "install") {
void refreshRemoteConfig(apiBase);
}
});
browser.runtime.onStartup.addListener(() => {
@@ -774,5 +789,6 @@ browser.runtime.onStartup.addListener(() => {
});
initCloudSettingsAutoSync({ reloadSeqtaPages });
initRemoteConfigBackground(apiBase);
initTimetableClassmatesBackgroundSync();
void ensureSyncableStorageDefaults();
+9
View File
@@ -16,6 +16,7 @@ import {
getLastUploadedSnapshot,
setKnownRemoteUpdatedAt,
} from "@/seqta/utils/cloudSettingsSync";
import { isRemoteCloudSyncDisabled } from "./remoteConfig";
const ACCOUNTS_BASE = "https://accounts.betterseqta.org";
export const CLOUD_SUMMARY_URL = `${ACCOUNTS_BASE}/api/user/cloud-summary`;
@@ -216,6 +217,9 @@ async function putSettingsOnce(token: string): Promise<PutResult> {
export async function performCloudSettingsUploadWithRetry(
token: string,
): Promise<{ success: boolean; error?: string; updated_at?: string; skipped?: boolean }> {
if (await isRemoteCloudSyncDisabled()) {
return { success: false, error: "Cloud sync disabled by remote config", skipped: true };
}
let t = token;
for (let attempt = 0; attempt < 2; attempt++) {
const res = await putSettingsOnce(t);
@@ -332,6 +336,8 @@ async function downloadIfNeeded(token: string): Promise<void> {
}
async function runCloudSettingsPollInner(): Promise<void> {
if (await isRemoteCloudSyncDisabled()) return;
const all = (await browser.storage.local.get()) as Record<string, unknown>;
if (!isAutoCloudSyncEnabled(all)) return;
@@ -409,6 +415,7 @@ function scheduleDebouncedUpload(): void {
/** Call after store theme install (and similar) so cloud upload runs even if storage events are flaky. */
export function requestCloudSettingsDebouncedUpload(): void {
void (async () => {
if (await isRemoteCloudSyncDisabled()) return;
const all = (await browser.storage.local.get()) as Record<string, unknown>;
if (!isAutoCloudSyncEnabled(all)) return;
if (suppressAutoUploadDuringRestore) return;
@@ -418,6 +425,7 @@ export function requestCloudSettingsDebouncedUpload(): void {
}
async function runDebouncedUploadJob(): Promise<void> {
if (await isRemoteCloudSyncDisabled()) return;
const all = (await browser.storage.local.get()) as Record<string, unknown>;
if (!isAutoCloudSyncEnabled(all)) return;
const token = await getAccessToken();
@@ -449,6 +457,7 @@ function onStorageChanged(
if (!keys.some((k) => isKeyIncludedInCloudUploadPayload(k))) return;
void (async () => {
if (await isRemoteCloudSyncDisabled()) return;
const all = (await browser.storage.local.get()) as Record<string, unknown>;
if (!isAutoCloudSyncEnabled(all)) return;
if (suppressAutoUploadDuringRestore) return;
+297
View File
@@ -0,0 +1,297 @@
import browser from "webextension-polyfill";
import { getOrCreateInstallId } from "@/seqta/utils/feedback/installId";
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
import {
mergeGithubConfigFiles,
normalizeRemoteConfigSnapshot,
} from "@/seqta/utils/remoteConfig/normalize";
import {
BSPLUS_INSTALL_REGISTERED_AT_KEY,
BSPLUS_REMOTE_CONFIG_ETAG_KEY,
BSPLUS_REMOTE_CONFIG_FETCHED_AT_KEY,
BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY,
BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY,
BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY,
BS_STATUS_MANIFEST_URL,
REGISTER_INTERVAL_MS,
REMOTE_CONFIG_ALARM,
REMOTE_CONFIG_POLL_MINUTES,
} from "@/seqta/utils/remoteConfig/storageKeys";
import type { RemoteConfigSnapshot } from "@/seqta/utils/remoteConfig/types";
type MessageSender = { (response?: unknown): void };
function extensionChannel(): string {
if (typeof __UPDATE_CHANNEL__ !== "undefined") {
if (__UPDATE_CHANNEL__ === "nightly") return "nightly";
if (__UPDATE_CHANNEL__ === "stable") return "stable";
}
return "unknown";
}
function extensionVersion(): string {
try {
return browser.runtime.getManifest().version;
} catch {
return "0";
}
}
async function parseJson(r: Response): Promise<unknown> {
const text = await r.text();
try {
return text ? JSON.parse(text) : {};
} catch {
return null;
}
}
async function readLastHostname(): Promise<string | undefined> {
const stored = await browser.storage.local.get(BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY);
const hostname = stored[BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY];
return typeof hostname === "string" && hostname.length > 0 ? hostname : undefined;
}
async function fetchGithubSnapshot(): Promise<RemoteConfigSnapshot | null> {
try {
const manifestRes = await fetch(BS_STATUS_MANIFEST_URL, { cache: "no-store" });
if (!manifestRes.ok) return null;
const manifest = (await parseJson(manifestRes)) as Record<string, unknown> | null;
if (!manifest?.files || typeof manifest.files !== "object") return null;
const base =
BS_STATUS_MANIFEST_URL.replace(/manifest\.json$/, "") ||
"https://raw.githubusercontent.com/BetterSEQTA/BS-Status/main/config/";
const files: Record<string, unknown> = {};
for (const [key, fileName] of Object.entries(
manifest.files as Record<string, string>,
)) {
if (typeof fileName !== "string") continue;
const url = fileName.startsWith("http") ? fileName : `${base}${fileName}`;
if (!isAllowedFetchUrl(url)) continue;
const fr = await fetch(url, { cache: "no-store" });
if (!fr.ok) continue;
files[key] = await parseJson(fr);
}
return mergeGithubConfigFiles(manifest, files);
} catch (e) {
console.warn("[BetterSEQTA+] GitHub remote config fallback failed:", e);
return null;
}
}
async function registerInstall(
apiBase: string,
primaryOk: boolean,
force = false,
): Promise<void> {
if (!primaryOk) return;
const stored = await browser.storage.local.get(BSPLUS_INSTALL_REGISTERED_AT_KEY);
const last = Number(stored[BSPLUS_INSTALL_REGISTERED_AT_KEY] ?? 0);
if (!force && Date.now() - last < REGISTER_INTERVAL_MS) return;
const installId = await getOrCreateInstallId();
const { bsplus_token, bsplus_user } = await browser.storage.local.get([
"bsplus_token",
"bsplus_user",
]);
const userId =
bsplus_user && typeof bsplus_user === "object" && "id" in bsplus_user
? String((bsplus_user as { id: string }).id)
: undefined;
const hostname = await readLastHostname();
const body = {
installId,
extension: {
version: extensionVersion(),
channel: extensionChannel(),
browser: "chrome",
},
userId,
lastSeenAt: new Date().toISOString(),
...(hostname ? { hostname } : {}),
};
try {
const headers: Record<string, string> = {
Accept: "application/json",
"Content-Type": "application/json",
};
if (typeof bsplus_token === "string" && bsplus_token.length > 0) {
headers.Authorization = `Bearer ${bsplus_token}`;
}
const r = await fetch(`${apiBase}/api/bsplus/installs/register`, {
method: "POST",
headers,
body: JSON.stringify(body),
cache: "no-store",
});
if (r.ok) {
await browser.storage.local.set({
[BSPLUS_INSTALL_REGISTERED_AT_KEY]: Date.now(),
});
}
} catch (e) {
console.warn("[BetterSEQTA+] install register failed:", e);
}
}
export async function refreshRemoteConfig(apiBase: () => string): Promise<{
snapshot: RemoteConfigSnapshot;
fromNetwork: boolean;
primaryOk: boolean;
}> {
const base = apiBase();
const installId = await getOrCreateInstallId();
const hostname = await readLastHostname();
const params = new URLSearchParams({
installId,
extensionVersion: extensionVersion(),
channel: extensionChannel(),
});
if (hostname) params.set("hostname", hostname);
const stored = await browser.storage.local.get([
BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY,
BSPLUS_REMOTE_CONFIG_ETAG_KEY,
]);
const etag = stored[BSPLUS_REMOTE_CONFIG_ETAG_KEY] as string | undefined;
const prior = stored[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY];
let primaryOk = false;
let snapshot: RemoteConfigSnapshot | null = null;
try {
const headers: Record<string, string> = { Accept: "application/json" };
if (etag) headers["If-None-Match"] = etag;
const r = await fetch(`${base}/api/bsplus/remote-config?${params}`, {
cache: "no-store",
headers,
});
if (r.status === 304 && prior) {
primaryOk = true;
snapshot = normalizeRemoteConfigSnapshot(prior);
snapshot.source = "cache";
} else if (r.ok) {
primaryOk = true;
const json = await parseJson(r);
snapshot = normalizeRemoteConfigSnapshot(json);
snapshot.source = "api";
const newEtag = r.headers.get("ETag") ?? snapshot.etag;
if (newEtag) snapshot.etag = newEtag;
await browser.storage.local.set({
[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY]: snapshot,
[BSPLUS_REMOTE_CONFIG_FETCHED_AT_KEY]: Date.now(),
[BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY]: true,
...(newEtag ? { [BSPLUS_REMOTE_CONFIG_ETAG_KEY]: newEtag } : {}),
});
}
} catch (e) {
console.warn("[BetterSEQTA+] remote-config primary fetch failed:", e);
}
if (!snapshot) {
snapshot = await fetchGithubSnapshot();
if (snapshot) {
await browser.storage.local.set({
[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY]: snapshot,
[BSPLUS_REMOTE_CONFIG_FETCHED_AT_KEY]: Date.now(),
[BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY]: false,
});
} else if (prior) {
snapshot = normalizeRemoteConfigSnapshot(prior);
snapshot.source = "cache";
} else {
snapshot = normalizeRemoteConfigSnapshot(null);
}
}
if (primaryOk) {
await browser.storage.local.set({ [BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY]: true });
}
void registerInstall(base, primaryOk);
return { snapshot, fromNetwork: primaryOk, primaryOk };
}
export function initRemoteConfigBackground(apiBase: () => string): void {
void refreshRemoteConfig(apiBase);
browser.alarms.create(REMOTE_CONFIG_ALARM, {
periodInMinutes: REMOTE_CONFIG_POLL_MINUTES,
});
browser.alarms.onAlarm.addListener((alarm) => {
if (alarm.name === REMOTE_CONFIG_ALARM) void refreshRemoteConfig(apiBase);
});
browser.storage.onChanged.addListener((changes, area) => {
if (area !== "local") return;
if (changes.bsplus_token || changes.bsplus_user) {
void (async () => {
const lastPrimary = await browser.storage.local.get(BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY);
const primaryOk = lastPrimary[BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY] === true;
if (primaryOk) {
await registerInstall(apiBase(), true, true);
} else {
const res = await refreshRemoteConfig(apiBase);
if (res.primaryOk) await registerInstall(apiBase(), true, true);
}
})();
}
});
}
export function createRemoteConfigHandlers(apiBase: () => string): Record<
string,
(request: unknown, sendResponse: MessageSender) => boolean
> {
function handleRefresh(_req: unknown, sendResponse: MessageSender): boolean {
void refreshRemoteConfig(apiBase)
.then((res) => sendResponse(res))
.catch((err) =>
sendResponse({
error: err instanceof Error ? err.message : "Refresh failed",
}),
);
return true;
}
function handleGetSnapshot(_req: unknown, sendResponse: MessageSender): boolean {
void browser.storage.local
.get(BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY)
.then((stored) => {
sendResponse({
snapshot: normalizeRemoteConfigSnapshot(
stored[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY],
),
});
});
return true;
}
function handleSetPageContext(req: { hostname?: string }, sendResponse: MessageSender): boolean {
const hostname = typeof req.hostname === "string" ? req.hostname.trim() : "";
if (hostname) {
void browser.storage.local
.set({ [BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY]: hostname })
.then(() => sendResponse({ ok: true }));
} else {
sendResponse({ ok: false });
}
return true;
}
return {
refreshRemoteConfig: handleRefresh,
getRemoteConfigSnapshot: handleGetSnapshot,
setRemoteConfigPageContext: handleSetPageContext,
};
}
export async function isRemoteCloudSyncDisabled(): Promise<boolean> {
const stored = await browser.storage.local.get(BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY);
const snap = normalizeRemoteConfigSnapshot(stored[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY]);
return snap.global.disableCloudSync === true;
}
@@ -0,0 +1,79 @@
<script lang="ts">
import {
getRemoteConfigSnapshot,
isEffectiveBsplusEnabled,
isRemoteKillActive,
setLocalOverrideOnoff,
} from "@/seqta/utils/remoteConfig/runtime";
import { getRemoteStatusMessage } from "@/seqta/utils/remoteConfig/apply";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { requestSettingsDestination } from "@/seqta/utils/settingsNavigation";
import browser from "webextension-polyfill";
import { onMount } from "svelte";
let localOverride = $state(false);
const snapshot = $derived(getRemoteConfigSnapshot());
const killActive = $derived(isRemoteKillActive());
const statusMessage = $derived(getRemoteStatusMessage(snapshot));
const allowOverride = $derived(snapshot.global.allowLocalOverride !== false);
const showStrip = $derived(
killActive ||
!!statusMessage ||
!!snapshot.global.maintenance?.body ||
!!snapshot.global.maintenance?.title,
);
onMount(() => {
void browser.storage.local.get("bsplus_local_override_onoff").then((stored) => {
localOverride = stored.bsplus_local_override_onoff === true;
});
});
async function enableLocalRun() {
await setLocalOverrideOnoff(true);
localOverride = true;
location.reload();
}
function openGeneralSettings() {
requestSettingsDestination({ section: "general" });
}
</script>
{#if showStrip}
<div
class="shrink-0 border-b border-amber-200/80 bg-amber-50 px-4 py-3 text-sm text-amber-950 dark:border-amber-900/60 dark:bg-amber-950/40 dark:text-amber-50"
role="status"
>
<p class="leading-relaxed">
{statusMessage ??
"BetterSEQTA+ is temporarily limited. You can review settings for details."}
</p>
<div class="mt-2 flex flex-wrap items-center gap-2">
{#if killActive && !isEffectiveBsplusEnabled() && allowOverride}
<button
type="button"
class="rounded-lg bg-amber-600 px-3 py-1.5 text-xs font-semibold text-white transition-all duration-200 hover:scale-105 active:scale-95 focus:outline-none focus:ring-2 focus:ring-amber-500 focus:ring-offset-2 dark:focus:ring-offset-zinc-900"
onclick={enableLocalRun}
>
Run locally anyway
</button>
{:else if killActive && localOverride && isEffectiveBsplusEnabled()}
<span class="text-xs text-amber-800 dark:text-amber-200/90">
Running locally (override). Reload SEQTA after the operator clears the kill switch.
</span>
{/if}
<button
type="button"
class="rounded-lg border border-amber-300/80 px-3 py-1.5 text-xs font-medium transition-colors duration-200 hover:bg-amber-100/80 focus:outline-none focus:ring-2 focus:ring-amber-500 focus:ring-offset-2 dark:border-amber-800 dark:hover:bg-amber-900/50 dark:focus:ring-offset-zinc-900"
onclick={openGeneralSettings}
>
General settings
</button>
{#if $settingsState.onoff === false}
<span class="text-xs opacity-80">Master toggle is off in General.</span>
{/if}
</div>
</div>
{/if}
@@ -13,6 +13,7 @@ import {
getThemeApplyButtonStyles,
resolveStoreVariantAccentColor,
} from '@/interface/utils/themeListFilters'
import { isRemoteThemeStoreDisabled } from '@/seqta/utils/remoteConfig/runtime'
let {
theme,
currentThemes,
@@ -51,6 +52,7 @@ adminPreviewMode?: boolean
}>()
const installActionLabel = $derived(adminPreviewMode ? 'Preview & apply' : 'Install')
const isCommunity = $derived(variant === 'community')
const themeStoreInstallLocked = $derived(isRemoteThemeStoreDisabled() && !adminPreviewMode)
const showFavorites = $derived(!isCommunity)
function variantApplyStyles(variantId: string) {
if (!theme) {
@@ -155,6 +157,7 @@ setDisplayTheme(relatedTheme ?? null)
}, 100)
}
async function runInstall(id: string) {
if (themeStoreInstallLocked) return
installingId = id
try {
await onInstall(id)
@@ -163,6 +166,7 @@ installingId = null
}
}
async function runRemove(id: string) {
if (themeStoreInstallLocked) return
installingId = id
try {
await onRemove(id)
+7 -2
View File
@@ -21,6 +21,8 @@
import { settingsPopup } from "@/seqta/utils/settingsPopup";
import { armDevModeUnlock } from "@/seqta/utils/devModeUnlock";
import { consumeOpenFeedbackRequest } from "@/seqta/utils/feedback/client";
import RemoteConfigStatusStrip from "../components/RemoteConfigStatusStrip.svelte";
import { isRemoteSettingsSectionVisible } from "@/seqta/utils/remoteConfig/runtime";
import {
consumeSettingsDestination,
SETTINGS_NAVIGATION_EVENT,
@@ -90,7 +92,7 @@
{ id: "account", label: "My Account" },
{ id: "general", label: "General" },
{ id: "appearance", label: "Appearance" },
];
].filter((item) => isRemoteSettingsSectionVisible(item.id));
$effect(() => {
if (!$settingsState.devMode && activeSection === "advanced") activeSection = "general";
@@ -102,7 +104,7 @@
{ id: "features", label: "Features" },
...($settingsState.devMode ? [{ id: "advanced", label: "Advanced" }] : []),
{ id: "shortcuts", label: "Shortcuts" },
]);
].filter((item) => isRemoteSettingsSectionVisible(item.id)));
const settingsNavGroups = $derived([
{ label: "User Settings", items: userNav },
@@ -551,6 +553,8 @@
onToggleSize={standalone ? undefined : toggleExpanded}
/>
<RemoteConfigStatusStrip />
<!-- Body: left nav + content -->
<div class="flex flex-1 min-h-0 overflow-hidden">
<nav
@@ -730,6 +734,7 @@
<div
class="flex h-full min-h-0 flex-col gap-2 overflow-hidden bg-white dark:bg-zinc-800 dark:text-white"
>
<RemoteConfigStatusStrip />
<div
class="grid shrink-0 items-center border-b border-zinc-200/40 dark:border-zinc-700/40 {standalone ? 'grid-cols-1' : 'grid-cols-[minmax(0,1fr)_44px] gap-2 px-2'}"
>
@@ -12,10 +12,13 @@
} from "@/seqta/utils/performanceMode";
import browser from "webextension-polyfill";
import { matchesSearch, type SettingsSectionSharedProps } from "../shared";
import { checkRemoteFeature } from "@/seqta/utils/remoteConfig/runtime";
let { searchQuery = "" }: SettingsSectionSharedProps = $props();
const isEngage = isSeqtaEngageExperience();
const onoffGate = $derived(checkRemoteFeature("settings.control.onoff"));
const onoffGreyedOut = $derived(onoffGate.mode === "greyout");
const generalOptions = $derived([
{
@@ -144,7 +147,19 @@
{#if generalOptions.some((option) => matchesSearch(searchQuery, option.title, option.description))}
<SettingsCard class="divide-y divide-zinc-200/60 dark:divide-zinc-700/40">
{#each generalOptions as option (option.id)}
<SettingRow {...option} {searchQuery} />
{#if option.id === 12}
<div
class:opacity-50={onoffGreyedOut}
class:pointer-events-none={onoffGreyedOut}
title={onoffGreyedOut
? (onoffGate.message?.body ?? "Disabled by site operator")
: undefined}
>
<SettingRow {...option} {searchQuery} />
</div>
{:else}
<SettingRow {...option} {searchQuery} />
{/if}
{#if option.id === 0 && $settingsState.performanceMode && matchesSearch(searchQuery, "Performance Mode", "Global Search", "Assessment Averages", "enable anyway", "paused")}
<div class="border-none -mt-px">
<div
@@ -9,6 +9,7 @@ import { processMenuItemNode } from "@/seqta/utils/sidebarMenuIcons";
import { ChangeMenuItemPositions } from "@/seqta/utils/Openers/menuOrder";
import { isMenuOptionsOpen } from "@/seqta/utils/Openers/menuOptionsState";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { checkRemoteFeature } from "@/seqta/utils/remoteConfig/runtime";
import { applyMenuItemVisibility } from "@/seqta/utils/menuItemVisibility";
import { getNativeMenuList } from "@/seqta/ui/sidebar/parseNativeMenu";
import { rafThrottle } from "@/seqta/utils/rafThrottle";
@@ -29,6 +30,9 @@ export async function injectAnalyticsMenuItem(): Promise<() => void> {
if (isSeqtaEngageExperience()) {
return () => {};
}
if (checkRemoteFeature("page.analytics").hide) {
return () => {};
}
document
.querySelectorAll(
+4
View File
@@ -13,6 +13,7 @@ import { createPluginAPI } from "./createAPI";
import browser from "webextension-polyfill";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { verboseInfo } from "@/utils/verboseLog";
import { isRemotePluginStartAllowed } from "@/seqta/utils/remoteConfig/runtime";
import { isPluginAllowedInPerformanceMode } from "@/seqta/utils/performanceMode";
interface PluginSettingsStorage {
@@ -241,6 +242,9 @@ export class PluginManager {
if (settingsState.onoff === false || !isPluginAllowedInPerformanceMode(plugin.id)) {
return false;
}
if (!isRemotePluginStartAllowed(plugin.id)) {
return false;
}
if (!plugin.disableToggle) return true;
const all = settingsState.getAll() as unknown as Record<string, unknown>;
const stored = all[`plugin.${plugin.id}.settings`] as PluginSettingsStorage | undefined;
+7 -2
View File
@@ -23,6 +23,7 @@ import { LUCIDE_MOON_ICON_SVG } from "@/lib/icons/lucideMoon";
import { LUCIDE_SUN_ICON_SVG } from "@/lib/icons/lucideSun";
import { ensureTitlebarFounderBadgeMounted, refreshTitlebarFounderBadge } from "@/seqta/ui/founderBadge/mountTitlebarFounderBadge";
import { isPerformanceMode } from "@/seqta/utils/performanceMode";
import { checkRemoteFeature } from "@/seqta/utils/remoteConfig/runtime";
import { rafThrottle } from "@/seqta/utils/rafThrottle";
import {
installSidebarDrillReturn,
@@ -143,8 +144,12 @@ export async function AddBetterSEQTAElements() {
const menu = document.getElementById("menu")!;
const menuList = menu.firstChild as HTMLElement;
createHomeButton(fragment, menuList);
createNewsButton(fragment, menu);
if (!checkRemoteFeature("page.home").hide) {
createHomeButton(fragment, menuList);
}
if (!checkRemoteFeature("page.news").hide) {
createNewsButton(fragment, menu);
}
menuList.insertBefore(fragment, menuList.firstChild);
+8
View File
@@ -22,6 +22,10 @@ import {
import { resolveNoticeFilterTokens } from "@/seqta/utils/notices/noticeLabelFilters";
import { setupNoticesSection } from "@/seqta/utils/notices/noticeHomeUi";
import { lessonsSubtitleForViewDate } from "@/seqta/utils/Loaders/timetableSubtitle";
import {
applyPageFeatureGateEarly,
injectPageFeatureBanner,
} from "@/seqta/utils/remoteConfig/runtime";
let lessonInterval: ReturnType<typeof setInterval> | null = null;
let homeTeardown: (() => void) | null = null;
@@ -36,6 +40,8 @@ function clearLessonInterval(): void {
}
export async function loadHomePage() {
if (applyPageFeatureGateEarly("home")) return;
homeTeardown?.();
homeTeardown = null;
clearLessonInterval();
@@ -99,6 +105,8 @@ export async function loadHomePage() {
</div>`);
homeContainer.appendChild(skeletonStructure.firstChild!);
injectPageFeatureBanner("home", "#home-container");
injectPageFeatureBanner("home", "#home-container");
if (settingsState.animations) {
animate(
+30 -18
View File
@@ -1,3 +1,5 @@
import semver from "semver";
import browser from "webextension-polyfill";
import { settingsState } from "../listeners/SettingsState";
import { OpenWhatsNewPopup } from "./OpenWhatsNewPopup";
import {
@@ -17,25 +19,40 @@ import {
openTermsOfServicePopup,
shouldShowTermsOfServicePopup,
} from "./OpenTermsOfServicePopup";
import { getCampaignSeen, getRemoteConfigSnapshot } from "@/seqta/utils/remoteConfig/runtime";
import type { RemoteCampaign } from "@/seqta/utils/remoteConfig/types";
import { openRemoteCampaignPopup } from "./openRemoteCampaignPopup";
type QueueStep = (goNext: () => void) => void;
/**
* Runs startup modals in order: What's New (if the extension just updated),
* Courses/Assessments fix notice (only if features are off),
* Theme of the Month (when the user hasn't dismissed this calendar month),
* feedback reply notifications for pending submissions, then terms of service
* acceptance (always last, and only once signed in to Cloud).
*/
function remoteCampaignSteps(): QueueStep[] {
const now = Date.now();
const version = browser.runtime.getManifest().version;
const seen = getCampaignSeen();
return [...getRemoteConfigSnapshot().campaigns]
.filter((c) => {
if (!c.id) return false;
if (c.activeFrom && now < Date.parse(c.activeFrom)) return false;
if (c.activeTo && now > Date.parse(c.activeTo)) return false;
const hit = seen[c.id];
if (hit && (!c.requireAcknowledge || hit.ack)) return false;
if (c.minVersion && semver.valid(version) && semver.lt(version, c.minVersion)) return false;
if (c.maxVersion && semver.valid(version) && semver.gt(version, c.maxVersion)) return false;
return true;
})
.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0))
.map((campaign: RemoteCampaign) => (goNext: () => void) => {
openRemoteCampaignPopup(campaign, goNext);
});
}
export async function runStartupPopupQueue() {
// Make sure the background script knows about any dev-mode API override
// before we start firing requests.
syncApiBaseToBackground();
const steps: QueueStep[] = [];
const afterWhatsNew = !!settingsState.justupdated;
const steps: QueueStep[] = [...remoteCampaignSteps()];
if (afterWhatsNew) {
if (settingsState.justupdated) {
steps.push((goNext) => OpenWhatsNewPopup(goNext));
}
@@ -43,8 +60,6 @@ export async function runStartupPopupQueue() {
steps.push((goNext) => OpenCoursesAssessmentsFixPopup(goNext));
}
// Fetch the Theme of the Month before queueing so we don't show an empty
// popup if the network or server is unavailable.
const themeOfTheMonth = await fetchThemeOfTheMonth();
if (shouldShowThemeOfTheMonth(themeOfTheMonth)) {
steps.push((goNext) => {
@@ -53,13 +68,10 @@ export async function runStartupPopupQueue() {
}
const feedbackReplyStep = await maybeQueueFeedbackReplyPopup();
if (feedbackReplyStep) {
steps.push(feedbackReplyStep);
}
if (feedbackReplyStep) steps.push(feedbackReplyStep);
steps.push((goNext) => {
void (async () => {
// Nothing is sent to BetterSEQTA servers until the user signs in to Cloud.
if (!(await cloudAuth.getStoredToken())) {
goNext();
return;
@@ -0,0 +1,79 @@
import stringToHTML from "../stringToHTML";
import { closePopup, openPopup } from "./PopupManager";
import { createPopupHeroVideo } from "./attachPopupMediaFullscreen";
import { markCampaignSeen } from "@/seqta/utils/remoteConfig/runtime";
import type { RemoteCampaign } from "@/seqta/utils/remoteConfig/types";
import { requestSettingsDestination } from "@/seqta/utils/settingsNavigation";
import { openSettingsPopup } from "@/seqta/utils/setupSettingsButton";
function campaignHero(campaign: RemoteCampaign): HTMLElement | null {
const hero = campaign.hero;
if (!hero?.url) return null;
if (hero.type === "video") {
return createPopupHeroVideo(hero.url, hero.alt ?? "");
}
const img = document.createElement("img");
img.src = hero.url;
img.alt = hero.alt ?? "";
img.className = "whatsnewHeroImage";
img.loading = "lazy";
return img;
}
export function openRemoteCampaignPopup(
campaign: RemoteCampaign,
onDismissed?: () => void,
): void {
const title = campaign.header?.title ?? "BetterSEQTA+";
const subtitle = campaign.header?.subtitle ?? "";
const header = stringToHTML(
/* html */ `<div class="whatsnewHeader"><h1>${title}</h1>${subtitle ? `<p>${subtitle}</p>` : ""}</div>`,
).firstChild as HTMLElement;
const body = stringToHTML(/* html */ `<div class="whatsnewTextContainer"></div>`)
.firstChild as HTMLElement;
if (campaign.bodyHtml) body.innerHTML = campaign.bodyHtml;
const buttons = campaign.buttons?.length
? campaign.buttons
: [{ id: "dismiss", label: "Dismiss", action: "dismiss" as const }];
const footer = stringToHTML(
/* html */ `<div class="bsplus-campaign-actions flex flex-wrap gap-2 justify-end p-4">${buttons
.map(
(btn) =>
`<button type="button" id="bsplus-campaign-${campaign.id}-${btn.id}" class="bsplus-tos-btn bsplus-tos-btn--primary">${btn.label}</button>`,
)
.join("")}</div>`,
).firstChild as HTMLElement;
const content: HTMLElement[] = [];
const hero = campaignHero(campaign);
if (hero) content.push(hero);
content.push(body, footer);
const actions = buttons.map((btn) => ({
id: `bsplus-campaign-${campaign.id}-${btn.id}`,
onClick: async () => {
if (btn.action === "url" && btn.url) {
window.open(btn.url, "_blank", "noopener,noreferrer");
} else if (btn.action === "openSettingsSection" && btn.section) {
requestSettingsDestination({ section: btn.section });
await openSettingsPopup();
}
await markCampaignSeen(campaign.id, campaign.requireAcknowledge === true);
await closePopup();
},
}));
openPopup({
header,
content,
actions,
afterClose: () => {
void markCampaignSeen(campaign.id);
onDismissed?.();
},
});
}
+7 -1
View File
@@ -7,8 +7,14 @@ import LogoLightOutline from "@/resources/icons/betterseqta-light-outline.png";
import { resolveExtensionAssetUrl } from "@/lib/extensionAssetUrl";
import { animate, stagger } from "motion";
import { verboseInfo } from "@/utils/verboseLog";
import {
applyPageFeatureGateEarly,
injectPageFeatureBanner,
} from "@/seqta/utils/remoteConfig/runtime";
export async function SendNewsPage() {
if (applyPageFeatureGateEarly("news")) return;
verboseInfo("[BetterSEQTA+] Started Loading News Page");
document.title = "News ― SEQTA Learn";
await delay(10);
@@ -47,6 +53,7 @@ export async function SendNewsPage() {
</div>`);
main.append(html.firstChild!);
injectPageFeatureBanner("news", "#news-container");
void import("@/seqta/ui/titlebar/mountCustomTitleBar").then((mod) => {
mod.setCustomTitleBarText("News");
@@ -121,7 +128,6 @@ export async function SendNewsPage() {
fragment.append(newsarticle);
});
// Single DOM update to append all articles
newscontainer?.append(fragment);
if (!settingsState.animations) return;
+17
View File
@@ -1,6 +1,14 @@
import browser from "webextension-polyfill";
import isEqual from "@/seqta/utils/isEqual";
import { BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY } from "@/seqta/utils/calendarSync/settings";
import {
BSPLUS_CAMPAIGN_SEEN_KEY,
BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY,
BSPLUS_INSTALL_REGISTERED_AT_KEY,
BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY,
BSPLUS_REMOTE_CONFIG_ETAG_KEY,
BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY,
} from "@/seqta/utils/remoteConfig/storageKeys";
/** Matches the contract in docs/CLOUD_SETTINGS_SYNC_SERVER.md */
export const CLOUD_SETTINGS_SYNC_SCHEMA_VERSION = 1;
@@ -44,6 +52,15 @@ export const KEYS_OMITTED_FROM_CLOUD_UPLOAD = [
"bsplus_install_id",
/** Pending feedback ids awaiting a reply notification — device-local. */
"bsplus_pending_feedback_ids",
BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY,
BSPLUS_REMOTE_CONFIG_ETAG_KEY,
BSPLUS_CAMPAIGN_SEEN_KEY,
BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY,
BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY,
BSPLUS_INSTALL_REGISTERED_AT_KEY,
BSPLUS_REMOTE_CONFIG_FETCHED_AT_KEY,
BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY,
BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY,
BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY,
] as const;
+9
View File
@@ -16,6 +16,7 @@ import {
type FeedbackProduct,
} from "./constants";
import { getOrCreateInstallId } from "./installId";
import { isRemoteFeedbackSubmitDisabled } from "@/seqta/utils/remoteConfig/runtime";
export class FeedbackApiError extends Error {
constructor(
@@ -144,6 +145,14 @@ export async function submitFeedback(form: FeedbackFormInput): Promise<{ id: str
const err = validateFeedbackForm(form);
if (err) throw new FeedbackApiError(err, 422);
if (isRemoteFeedbackSubmitDisabled()) {
throw new FeedbackApiError(
"Feedback submissions are temporarily disabled.",
503,
"REMOTE_DISABLED",
);
}
const installId = await getOrCreateInstallId();
const host = getInstanceHostname();
const product: FeedbackProduct = isSeqtaEngageExperience() ? "engage" : "learn";
@@ -53,6 +53,12 @@ const EXCLUDED_FROM_SETTINGS_SURFACE = new Set([
"cloudUsername",
"bsplus_install_id",
"bsplus_pending_feedback_ids",
"bsplus_remote_config_snapshot",
"bsplus_remote_config_etag",
"bsplus_campaign_seen",
"bsplus_local_override_onoff",
"bsplus_features_hidden_until_version",
"bsplus_install_registered_at",
]);
function isExcludedSettingsKey(key: string): boolean {
+136
View File
@@ -0,0 +1,136 @@
import {
computeEffectiveEnabled,
isRemoteFeatureAllowed,
resolveFeatureMode,
} from "./apply";
import { DEFAULT_REMOTE_CONFIG } from "./normalize";
import type { RemoteConfigSnapshot } from "./types";
function snapshot(partial: Partial<RemoteConfigSnapshot>): RemoteConfigSnapshot {
return {
...DEFAULT_REMOTE_CONFIG,
...partial,
global: { ...DEFAULT_REMOTE_CONFIG.global, ...partial.global },
features: { ...DEFAULT_REMOTE_CONFIG.features, ...partial.features },
};
}
describe("computeEffectiveEnabled", () => {
it("respects user master toggle", () => {
expect(computeEffectiveEnabled(false, snapshot({}), false)).toBe(false);
});
it("allows when remote mode is on", () => {
expect(computeEffectiveEnabled(true, snapshot({ global: { mode: "on" } }), false)).toBe(
true,
);
});
it("blocks when remote kill without local override", () => {
expect(
computeEffectiveEnabled(
true,
snapshot({ global: { mode: "off", allowLocalOverride: true } }),
false,
),
).toBe(false);
});
it("allows local override when permitted", () => {
expect(
computeEffectiveEnabled(
true,
snapshot({ global: { mode: "off", allowLocalOverride: true } }),
true,
),
).toBe(true);
});
it("ignores local override when server forbids it", () => {
expect(
computeEffectiveEnabled(
true,
snapshot({ global: { mode: "off", allowLocalOverride: false } }),
true,
),
).toBe(false);
});
it("blocks hostname on denylist unless local override", () => {
const snap = snapshot({
global: {
mode: "on",
hostnamePolicy: { mode: "denylist", suffixes: ["blocked.edu.au"] },
},
});
expect(computeEffectiveEnabled(true, snap, false, "learn.blocked.edu.au")).toBe(false);
expect(computeEffectiveEnabled(true, snap, true, "learn.blocked.edu.au")).toBe(true);
});
});
describe("resolveFeatureMode", () => {
it("treats temp_hide as hide only for matching config version", () => {
const snap = snapshot({
configVersion: "42",
features: { "page.news": { mode: "temp_hide" } },
});
expect(resolveFeatureMode("page.news", snap, { "page.news": "41" })).toBe("allow");
expect(resolveFeatureMode("page.news", snap, { "page.news": "42" })).toBe("hide");
});
it("maps banner to allowed but not hide", () => {
const snap = snapshot({
features: { "plugin.grade-analytics": { mode: "banner" } },
});
expect(isRemoteFeatureAllowed("plugin.grade-analytics", snap)).toBe(true);
expect(resolveFeatureMode("plugin.grade-analytics", snap)).toBe("banner");
});
});
describe("SEQTA boot decision", () => {
it("would skip monofile when effective enablement is false", () => {
const shouldBootFull = computeEffectiveEnabled(
true,
snapshot({ global: { mode: "off", allowLocalOverride: true } }),
false,
);
expect(shouldBootFull).toBe(false);
});
});
describe("hydrateRemoteConfigFromStorage", () => {
it("requests cached snapshot before background refresh when storage is empty", async () => {
jest.resetModules();
jest.doMock("webextension-polyfill", () => ({
storage: {
local: {
get: jest.fn(async () => ({})),
set: jest.fn(async () => {}),
},
onChanged: { addListener: jest.fn() },
},
runtime: {
getManifest: () => ({ version: "3.7.6" }),
sendMessage: jest.fn(async (msg: { type?: string }) =>
msg.type === "getRemoteConfigSnapshot"
? { snapshot: { configVersion: "1", global: { mode: "on" }, features: {}, campaigns: [] } }
: {},
),
},
}));
jest.doMock("@/seqta/utils/listeners/SettingsState", () => ({
settingsState: { onoff: true },
}));
const { hydrateRemoteConfigFromStorage } = await import("./runtime");
await hydrateRemoteConfigFromStorage();
const browser = jest.requireMock("webextension-polyfill");
const types = browser.runtime.sendMessage.mock.calls.map(
(c: [{ type?: string }]) => c[0]?.type,
);
expect(types).toContain("getRemoteConfigSnapshot");
expect(types).toContain("refreshRemoteConfig");
expect(types.indexOf("getRemoteConfigSnapshot")).toBeLessThan(
types.indexOf("refreshRemoteConfig"),
);
});
});
+112
View File
@@ -0,0 +1,112 @@
import type { FeatureMode, RemoteConfigSnapshot, RemoteFeatureGate } from "./types";
import { DEFAULT_REMOTE_CONFIG } from "./normalize";
import semver from "semver";
import browser from "webextension-polyfill";
function normalizeHostname(hostname: string): string {
return hostname.trim().toLowerCase().replace(/\.$/, "");
}
export function isHostnameAllowedByPolicy(
snapshot: RemoteConfigSnapshot,
hostname: string,
): boolean {
const policy = snapshot.global.hostnamePolicy;
if (!policy?.suffixes?.length) return true;
const host = normalizeHostname(hostname);
const suffixes = policy.suffixes.map((s) => normalizeHostname(s));
const matches = suffixes.some(
(suffix) => host === suffix || host.endsWith(`.${suffix}`),
);
if (policy.mode === "denylist") return !matches;
if (policy.mode === "allowlist") return matches;
return true;
}
export function isExtensionVersionBelowMinimum(snapshot: RemoteConfigSnapshot): boolean {
const min = snapshot.global.minExtensionVersion;
if (!min || !semver.valid(min)) return false;
const current = browser.runtime.getManifest().version;
if (!semver.valid(current)) return false;
return semver.lt(current, min);
}
export function getMinVersionStatusMessage(snapshot: RemoteConfigSnapshot): string | null {
if (!isExtensionVersionBelowMinimum(snapshot)) return null;
const min = snapshot.global.minExtensionVersion;
const url = snapshot.global.forceUpdateUrl;
const base = `BetterSEQTA+ ${min ?? "a newer version"} or later is required for full features.`;
return url ? `${base} Update: ${url}` : base;
}
export function computeEffectiveEnabled(
userOnoff: boolean,
snapshot: RemoteConfigSnapshot,
localOverride: boolean,
hostname = typeof location !== "undefined" ? location.hostname : "",
): boolean {
if (!userOnoff) return false;
if (!isHostnameAllowedByPolicy(snapshot, hostname)) {
if (snapshot.global.allowLocalOverride === false) return false;
return localOverride;
}
if (snapshot.global.mode !== "off") return true;
if (snapshot.global.allowLocalOverride === false) return false;
return localOverride;
}
export function getRemoteStatusMessage(snapshot: RemoteConfigSnapshot): string | null {
const minMsg = getMinVersionStatusMessage(snapshot);
if (minMsg) return minMsg;
if (snapshot.global.mode === "off" && snapshot.global.statusMessage) {
return snapshot.global.statusMessage;
}
const maint = snapshot.global.maintenance;
if (maint?.body) return maint.body;
if (maint?.title) return maint.title;
if (!isHostnameAllowedByPolicy(snapshot, typeof location !== "undefined" ? location.hostname : "")) {
return "BetterSEQTA+ is not enabled for this SEQTA site.";
}
return snapshot.global.mode === "off"
? "BetterSEQTA+ is temporarily disabled by the site operator."
: null;
}
export function resolveFeatureMode(
key: string,
snapshot: RemoteConfigSnapshot = DEFAULT_REMOTE_CONFIG,
hiddenUntilVersion: Record<string, string> = {},
): FeatureMode {
const gate: RemoteFeatureGate | undefined = snapshot.features[key];
if (!gate?.mode || gate.mode === "allow") return "allow";
if (gate.mode === "temp_hide") {
const pinned = hiddenUntilVersion[key];
if (pinned && pinned === snapshot.configVersion) return "hide";
return "allow";
}
return gate.mode;
}
export function isRemoteFeatureAllowed(
key: string,
snapshot: RemoteConfigSnapshot,
hiddenUntilVersion: Record<string, string> = {},
): boolean {
const mode = resolveFeatureMode(key, snapshot, hiddenUntilVersion);
return mode === "allow" || mode === "banner";
}
export function shouldHideFeature(
key: string,
snapshot: RemoteConfigSnapshot,
hiddenUntilVersion: Record<string, string> = {},
): boolean {
return resolveFeatureMode(key, snapshot, hiddenUntilVersion) === "hide";
}
export function getFeatureMessage(
key: string,
snapshot: RemoteConfigSnapshot,
): RemoteFeatureGate["message"] | undefined {
return snapshot.features[key]?.message;
}
@@ -0,0 +1,39 @@
import {
DEFAULT_REMOTE_CONFIG,
mergeGithubConfigFiles,
normalizeRemoteConfigSnapshot,
} from "./normalize";
describe("normalizeRemoteConfigSnapshot", () => {
it("returns defaults for empty input", () => {
expect(normalizeRemoteConfigSnapshot(null)).toEqual(DEFAULT_REMOTE_CONFIG);
});
it("unwraps API envelope data", () => {
const snap = normalizeRemoteConfigSnapshot({
success: true,
data: {
configVersion: "9",
global: { mode: "off", statusMessage: "Maintenance" },
},
});
expect(snap.configVersion).toBe("9");
expect(snap.global.mode).toBe("off");
expect(snap.global.statusMessage).toBe("Maintenance");
});
});
describe("mergeGithubConfigFiles", () => {
it("merges manifest file map into snapshot", () => {
const snap = mergeGithubConfigFiles(
{ version: "1", updatedAt: "2026-01-01" },
{
global: { mode: "on" },
features: { "page.news": { mode: "hide" } },
campaigns: [],
},
);
expect(snap.source).toBe("github");
expect(snap.features["page.news"]?.mode).toBe("hide");
});
});
+120
View File
@@ -0,0 +1,120 @@
import type { RemoteConfigSnapshot, RemoteFeatureGate, RemoteGlobalConfig } from "./types";
export const DEFAULT_REMOTE_CONFIG: RemoteConfigSnapshot = {
configVersion: "0",
source: "default",
global: { mode: "on", allowLocalOverride: true },
features: {},
campaigns: [],
};
function normalizeGlobal(raw: unknown): RemoteGlobalConfig {
if (!raw || typeof raw !== "object") return DEFAULT_REMOTE_CONFIG.global;
const g = raw as Record<string, unknown>;
return {
mode: g.mode === "off" ? "off" : "on",
allowLocalOverride: g.allowLocalOverride !== false,
statusMessage: typeof g.statusMessage === "string" ? g.statusMessage : null,
maintenance:
g.maintenance && typeof g.maintenance === "object"
? (g.maintenance as RemoteGlobalConfig["maintenance"])
: null,
minExtensionVersion:
typeof g.minExtensionVersion === "string" ? g.minExtensionVersion : null,
forceUpdateUrl: typeof g.forceUpdateUrl === "string" ? g.forceUpdateUrl : null,
disableCloudSync: g.disableCloudSync === true,
disableThemeStore: g.disableThemeStore === true,
disableFeedbackSubmit: g.disableFeedbackSubmit === true,
hostnamePolicy:
g.hostnamePolicy && typeof g.hostnamePolicy === "object"
? {
mode:
(g.hostnamePolicy as { mode?: string }).mode === "allowlist" ||
(g.hostnamePolicy as { mode?: string }).mode === "denylist"
? ((g.hostnamePolicy as { mode: "allowlist" | "denylist" }).mode)
: undefined,
suffixes: Array.isArray((g.hostnamePolicy as { suffixes?: unknown }).suffixes)
? ((g.hostnamePolicy as { suffixes: string[] }).suffixes.filter(
(s) => typeof s === "string",
))
: undefined,
}
: null,
};
}
function normalizeFeatures(raw: unknown): Record<string, RemoteFeatureGate> {
if (!raw || typeof raw !== "object") return {};
const out: Record<string, RemoteFeatureGate> = {};
for (const [key, value] of Object.entries(raw as Record<string, unknown>)) {
if (!value || typeof value !== "object") continue;
const v = value as Record<string, unknown>;
const mode = v.mode;
if (
mode !== "allow" &&
mode !== "hide" &&
mode !== "banner" &&
mode !== "block" &&
mode !== "greyout" &&
mode !== "temp_hide"
) {
continue;
}
const msg = v.message;
out[key] = {
mode,
message:
msg && typeof msg === "object" && typeof (msg as { body?: string }).body === "string"
? {
title: typeof (msg as { title?: string }).title === "string"
? (msg as { title: string }).title
: undefined,
body: (msg as { body: string }).body,
severity:
(msg as { severity?: string }).severity === "warning" ||
(msg as { severity?: string }).severity === "error" ||
(msg as { severity?: string }).severity === "info"
? ((msg as { severity: "info" | "warning" | "error" }).severity)
: undefined,
}
: undefined,
};
}
return out;
}
export function normalizeRemoteConfigSnapshot(raw: unknown): RemoteConfigSnapshot {
if (!raw || typeof raw !== "object") return { ...DEFAULT_REMOTE_CONFIG };
const r = raw as Record<string, unknown>;
const data =
r.data && typeof r.data === "object" ? (r.data as Record<string, unknown>) : r;
return {
configVersion:
typeof data.configVersion === "string" ? data.configVersion : "0",
etag: typeof data.etag === "string" ? data.etag : undefined,
source:
data.source === "api" ||
data.source === "github" ||
data.source === "cache" ||
data.source === "default"
? data.source
: "cache",
global: normalizeGlobal(data.global),
features: normalizeFeatures(data.features),
campaigns: Array.isArray(data.campaigns) ? (data.campaigns as RemoteConfigSnapshot["campaigns"]) : [],
};
}
/** Merge GitHub manifest + partial files into one snapshot. */
export function mergeGithubConfigFiles(
manifest: Record<string, unknown>,
files: Record<string, unknown>,
): RemoteConfigSnapshot {
return normalizeRemoteConfigSnapshot({
configVersion: manifest.configVersion ?? manifest.updatedAt ?? "0",
source: "github",
global: files.global ?? {},
features: files.features ?? {},
campaigns: files.campaigns ?? [],
});
}
+277
View File
@@ -0,0 +1,277 @@
import browser from "webextension-polyfill";
import stringToHTML from "@/seqta/utils/stringToHTML";
import { addExtensionSettings } from "@/seqta/utils/Adders/AddExtensionSettings";
import { setupSettingsButton } from "@/seqta/utils/setupSettingsButton";
import { waitForElm } from "@/seqta/utils/waitForElm";
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
import { isPerformanceMode } from "@/seqta/utils/performanceMode";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import {
BSPLUS_CAMPAIGN_SEEN_KEY,
BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY,
BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY,
BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY,
BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY,
} from "./storageKeys";
import { normalizeRemoteConfigSnapshot } from "./normalize";
import type { CampaignSeenRecord, RemoteConfigSnapshot } from "./types";
import {
computeEffectiveEnabled,
getFeatureMessage,
isExtensionVersionBelowMinimum,
isRemoteFeatureAllowed,
resolveFeatureMode,
shouldHideFeature,
} from "./apply";
let snapshot: RemoteConfigSnapshot = normalizeRemoteConfigSnapshot(null);
let localOverride = false;
let hiddenUntilVersion: Record<string, string> = {};
let campaignSeen: CampaignSeenRecord = {};
const SNAPSHOT_FETCH_TIMEOUT_MS = 200;
export function getRemoteConfigSnapshot(): RemoteConfigSnapshot {
return snapshot;
}
export function getHiddenUntilVersion(): Record<string, string> {
return hiddenUntilVersion;
}
export function getCampaignSeen(): CampaignSeenRecord {
return campaignSeen;
}
export function isEffectiveBsplusEnabled(userOnoff = settingsState.onoff !== false): boolean {
return computeEffectiveEnabled(userOnoff, snapshot, localOverride, location.hostname);
}
export function isRemoteKillActive(): boolean {
return snapshot.global.mode === "off";
}
export function isRemoteThemeStoreDisabled(): boolean {
return snapshot.global.disableThemeStore === true;
}
export function isRemoteFeedbackSubmitDisabled(): boolean {
return snapshot.global.disableFeedbackSubmit === true;
}
export async function setLocalOverrideOnoff(enabled: boolean): Promise<void> {
localOverride = enabled;
await browser.storage.local.set({ [BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY]: enabled });
}
function applyRemoteRuntime(
next: RemoteConfigSnapshot,
override: boolean,
hidden: Record<string, string>,
seen: CampaignSeenRecord,
): void {
snapshot = next;
localOverride = override;
hiddenUntilVersion = hidden;
campaignSeen = seen;
pinTempHideVersions(next);
}
function pinTempHideVersions(next: RemoteConfigSnapshot): void {
let changed = false;
for (const [key, gate] of Object.entries(next.features)) {
if (gate.mode === "temp_hide" && hiddenUntilVersion[key] !== next.configVersion) {
hiddenUntilVersion = { ...hiddenUntilVersion, [key]: next.configVersion };
changed = true;
}
}
if (changed) {
void browser.storage.local.set({
[BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY]: hiddenUntilVersion,
});
}
}
export async function hydrateRemoteConfigFromStorage(): Promise<RemoteConfigSnapshot> {
const stored = await browser.storage.local.get([
BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY,
BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY,
BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY,
BSPLUS_CAMPAIGN_SEEN_KEY,
]);
let raw = stored[BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY];
if (!raw) {
try {
const res = (await Promise.race([
browser.runtime.sendMessage({ type: "getRemoteConfigSnapshot" }),
new Promise<null>((resolve) => setTimeout(() => resolve(null), SNAPSHOT_FETCH_TIMEOUT_MS)),
])) as { snapshot?: unknown } | null;
if (res?.snapshot) raw = res.snapshot;
} catch {
// SW unavailable
}
void browser.runtime.sendMessage({ type: "refreshRemoteConfig" }).catch(() => {});
}
applyRemoteRuntime(
normalizeRemoteConfigSnapshot(raw),
stored[BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY] === true,
(stored[BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY] as Record<string, string>) ?? {},
(stored[BSPLUS_CAMPAIGN_SEEN_KEY] as CampaignSeenRecord) ?? {},
);
return snapshot;
}
export function notifyRemoteConfigPageContext(hostname: string): void {
void browser.storage.local.set({ [BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY]: hostname });
void browser.runtime
.sendMessage({ type: "setRemoteConfigPageContext", hostname })
.catch(() => {});
}
export async function markCampaignSeen(campaignId: string, ack?: boolean): Promise<void> {
campaignSeen = {
...campaignSeen,
[campaignId]: { seenAt: new Date().toISOString(), ack },
};
await browser.storage.local.set({ [BSPLUS_CAMPAIGN_SEEN_KEY]: campaignSeen });
}
const REMOTE_STORAGE_WATCH_KEYS = new Set([
BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY,
BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY,
BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY,
]);
export function installRemoteConfigStorageListener(onEffectiveChange: () => void): void {
let priorEnabled = isEffectiveBsplusEnabled();
browser.storage.onChanged.addListener((changes, area) => {
if (area !== "local") return;
if (!Object.keys(changes).some((k) => REMOTE_STORAGE_WATCH_KEYS.has(k))) return;
void hydrateRemoteConfigFromStorage().then(() => {
const next = isEffectiveBsplusEnabled();
if (next !== priorEnabled) {
priorEnabled = next;
onEffectiveChange();
}
});
});
}
export function checkRemoteFeature(key: string) {
const hidden = hiddenUntilVersion;
return {
mode: resolveFeatureMode(key, snapshot, hidden),
allowed: isRemoteFeatureAllowed(key, snapshot, hidden),
hide: shouldHideFeature(key, snapshot, hidden),
message: getFeatureMessage(key, snapshot),
};
}
export function isRemoteSettingsSectionVisible(sectionId: string): boolean {
const key =
sectionId === "account" ? "settings.nav.cloud" : `settings.section.${sectionId}`;
return !checkRemoteFeature(key).hide;
}
export function isRemotePluginStartAllowed(pluginId: string): boolean {
const remote = checkRemoteFeature(`plugin.${pluginId}`);
if (remote.hide || remote.mode === "greyout" || remote.mode === "block") return false;
if (isExtensionVersionBelowMinimum(snapshot)) return false;
return remote.allowed;
}
/** Returns true when navigation should stop (hide or block). */
export function applyPageFeatureGateEarly(page: string): boolean {
const gate = checkRemoteFeature(`page.${page}`);
if (gate.hide) return true;
if (gate.mode !== "block") return false;
const main = document.getElementById("main");
if (main) {
const title = gate.message?.title ?? "Page unavailable";
const body = gate.message?.body ?? "This BetterSEQTA+ page is temporarily unavailable.";
main.innerHTML = "";
main.append(
stringToHTML(
/* html */ `<div class="home-root"><div class="home-container"><h1 class="bsplus-rounded">${title}</h1><p>${body}</p></div></div>`,
).firstChild!,
);
}
return true;
}
export function injectPageFeatureBanner(page: string, containerSelector: string): void {
const gate = checkRemoteFeature(`page.${page}`);
if (gate.mode !== "banner" || !gate.message?.body) return;
const container = document.querySelector(containerSelector);
if (!container || container.querySelector(`[data-bsplus-page-banner="${page}"]`)) return;
const severity = gate.message.severity ?? "info";
container.insertBefore(
stringToHTML(/* html */ `
<div data-bsplus-page-banner="${page}" class="bsplus-remote-page-banner bsplus-remote-page-banner--${severity} mb-4 rounded-lg border px-4 py-3 text-sm">
${gate.message.title ? `<p class="font-semibold mb-1">${gate.message.title}</p>` : ""}
<p>${gate.message.body}</p>
</div>
`).firstChild!,
container.firstChild,
);
}
/** Remote kill path: settings popup + toolbar cog without monofile. */
export async function ensureKilledModeSettingsAccess(): Promise<void> {
addExtensionSettings();
if (document.getElementById("AddedSettings")) {
setupSettingsButton();
return;
}
const fallback =
document.getElementById("content") ??
document.getElementById("container") ??
document.body;
const mountParent = async (): Promise<Element> => {
if (isSeqtaEngageExperience()) {
try {
const el = await waitForElm(
"#content > div.connectedNotificationsWrapper > div",
true,
100,
40,
);
return el.parentElement ?? el;
} catch {
return fallback;
}
}
try {
return await waitForElm(
"#content > div.connectedNotificationsWrapper",
true,
isPerformanceMode() ? 120 : 80,
50,
);
} catch {
return fallback;
}
};
mountParent().then((parent) => {
if (document.getElementById("AddedSettings")) return;
parent.append(
stringToHTML(/* html */ `
<button class="addedButton tooltip" id="AddedSettings" type="button" aria-label="BetterSEQTA+ settings">
<svg width="24" height="24" viewBox="0 0 24 24" aria-hidden="true">
<path d="M23.182,6.923c-.29,0-3.662,2.122-4.142,2.4l-2.8-1.555V4.511l4.257-2.456a.518.518,0,0,0,.233-.408.479.479,0,0,0-.233-.407,6.511,6.511,0,1,0-3.327,12.107,6.582,6.582,0,0,0,6.148-4.374,5.228,5.228,0,0,0,.333-1.542A.461.461,0,0,0,23.182,6.923Z"></path>
<path d="M9.73,10.418,7.376,12.883c-.01.01-.021.016-.03.025L1.158,19.1a2.682,2.682,0,1,0,3.793,3.793l4.583-4.582,0,0,4.1-4.005-.037-.037A9.094,9.094,0,0,1,9.73,10.418ZM3.053,21.888A.894.894,0,1,1,3.946,21,.893.893,0,0,1,3.053,21.888Z"></path>
</svg>
<div class="tooltiptext topmenutooltip">BetterSEQTA+ Settings</div>
</button>
`).firstChild!,
);
setupSettingsButton();
});
}
@@ -0,0 +1,17 @@
export const BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY = "bsplus_remote_config_snapshot";
export const BSPLUS_REMOTE_CONFIG_ETAG_KEY = "bsplus_remote_config_etag";
export const BSPLUS_CAMPAIGN_SEEN_KEY = "bsplus_campaign_seen";
export const BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY = "bsplus_local_override_onoff";
export const BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY =
"bsplus_features_hidden_until_version";
export const BSPLUS_INSTALL_REGISTERED_AT_KEY = "bsplus_install_registered_at";
export const BSPLUS_REMOTE_CONFIG_FETCHED_AT_KEY = "bsplus_remote_config_fetched_at";
export const BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY = "bsplus_remote_config_last_hostname";
export const BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY = "bsplus_remote_last_primary_ok";
export const REMOTE_CONFIG_ALARM = "bsplus_remote_config_poll";
export const REMOTE_CONFIG_POLL_MINUTES = 20;
export const REGISTER_INTERVAL_MS = 24 * 60 * 60 * 1000;
export const BS_STATUS_MANIFEST_URL =
"https://raw.githubusercontent.com/BetterSEQTA/BS-Status/main/config/manifest.json";
+64
View File
@@ -0,0 +1,64 @@
export type FeatureMode =
| "allow"
| "hide"
| "banner"
| "block"
| "greyout"
| "temp_hide";
export type RemoteFeatureGate = {
mode?: FeatureMode;
message?: { title?: string; body?: string; severity?: "info" | "warning" | "error" };
};
export type RemoteGlobalConfig = {
mode?: "on" | "off";
allowLocalOverride?: boolean;
statusMessage?: string | null;
maintenance?: { title?: string; body?: string } | null;
minExtensionVersion?: string | null;
forceUpdateUrl?: string | null;
disableCloudSync?: boolean;
disableThemeStore?: boolean;
disableFeedbackSubmit?: boolean;
hostnamePolicy?: {
mode?: "allowlist" | "denylist";
suffixes?: string[];
} | null;
};
export type RemoteCampaignButton = {
id: string;
label: string;
action: "dismiss" | "url" | "openSettingsSection";
url?: string;
section?: string;
};
export type RemoteCampaign = {
id: string;
priority?: number;
activeFrom?: string;
activeTo?: string;
header?: { title?: string; subtitle?: string };
hero?: { type?: "image" | "video"; url?: string; alt?: string };
bodyHtml?: string;
buttons?: RemoteCampaignButton[];
requireAcknowledge?: boolean;
minVersion?: string;
maxVersion?: string;
};
export type RemoteConfigSnapshot = {
configVersion: string;
etag?: string;
source?: "api" | "github" | "default" | "cache";
global: RemoteGlobalConfig;
features: Record<string, RemoteFeatureGate>;
campaigns: RemoteCampaign[];
};
export type CampaignSeenRecord = Record<
string,
{ seenAt: string; ack?: boolean }
>;