diff --git a/src/background.ts b/src/background.ts index ca7660f7..199e3253 100644 --- a/src/background.ts +++ b/src/background.ts @@ -20,15 +20,8 @@ import { type CalendarMessageHandlerMap, } 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 { DEFAULT_BACKGROUND_PENDING_KEY } from "@/seqta/ui/defaultBackgroundKey"; import { handleSearchThemeStockPhotos } from "./background/searchThemeStockPhotos"; -import { bsplusApiQueryParams, withBsplusApiQuery } from "@/seqta/utils/bsplusClientContext"; import { initTimetableClassmatesBackgroundSync } from "./background/timetableClassmatesSync"; import { runStorageMigrations } from "./background/storageMigrations"; @@ -113,11 +106,7 @@ function normalizeFetchThemesResponse(json: unknown): { function handleFetchThemes(_request: unknown, sendResponse: MessageSender): boolean { void (async () => { const token = await getAccessTokenFromStorage(); - const params = await bsplusApiQueryParams(); - params.set("type", "betterseqta"); - params.set("limit", "100"); - params.set("nocache", String(Date.now())); - const apiUrl = `${apiBase()}/api/themes?${params}`; + const apiUrl = `${apiBase()}/api/themes?type=betterseqta&limit=100&nocache=${Date.now()}`; const githubUrl = `https://raw.githubusercontent.com/BetterSEQTA/BetterSEQTA-Themes/main/store/themes.json?nocache=${Date.now()}`; const headers: Record = {}; if (token) headers["Authorization"] = `Bearer ${token}`; @@ -166,10 +155,7 @@ function handleFetchThemeDetails(request: BackgroundRequest, sendResponse: Messa const token = await getAccessTokenFromStorage(); const headers: Record = {}; if (token) headers["Authorization"] = `Bearer ${token}`; - const detailUrl = await withBsplusApiQuery( - `${apiBase()}/api/themes/${encodeURIComponent(themeId)}`, - ); - fetch(detailUrl, { cache: "no-store", headers }) + fetch(`${apiBase()}/api/themes/${themeId}`, { cache: "no-store", headers }) .then((r) => r.json()) .then(sendResponse) .catch((err) => { @@ -561,11 +547,8 @@ const customThemesHandlers = createCustomThemesHandlers({ getAccessTokenFromStorage, }); -const remoteConfigHandlers = createRemoteConfigHandlers(apiBase); - const MESSAGE_HANDLERS: Record = { ...customThemesHandlers, - ...remoteConfigHandlers, searchThemeStockPhotos: handleSearchThemeStockPhotos, reloadTabs: () => reloadSeqtaPages(), setDevApiBase: handleSetDevApiBase, @@ -710,14 +693,10 @@ browser.runtime.onInstalled.addListener(function (event) { if (event.reason === "update" && event.previousVersion) { void runStorageMigrations(event.previousVersion); - void browser.storage.local.remove(BSPLUS_INSTALL_REGISTERED_AT_KEY).then(() => { - void refreshRemoteConfig(apiBase); - }); reloadSeqtaPages(); } if (event.reason === "install") { - void refreshRemoteConfig(apiBase); void browser.storage.local.set({ [DEFAULT_BACKGROUND_PENDING_KEY]: true }); void defaultsReady .catch(() => undefined) @@ -734,6 +713,5 @@ browser.runtime.onStartup.addListener(() => { }); initCloudSettingsAutoSync({ reloadSeqtaPages }); -initRemoteConfigBackground(apiBase); initTimetableClassmatesBackgroundSync(); void ensureSyncableStorageDefaults(); diff --git a/src/background/cloudSettingsAutoSync.ts b/src/background/cloudSettingsAutoSync.ts index 1599386d..14086a53 100644 --- a/src/background/cloudSettingsAutoSync.ts +++ b/src/background/cloudSettingsAutoSync.ts @@ -16,7 +16,11 @@ import { getLastUploadedSnapshot, setKnownRemoteUpdatedAt, } from "@/seqta/utils/cloudSettingsSync"; -import { isRemoteCloudSyncDisabled } from "./remoteConfig"; +import { readRemoteStatus } from "@/seqta/utils/remoteStatus"; + +async function isCloudSyncDisabled(): Promise { + return (await readRemoteStatus()).disabledFeatures.includes("cloud.sync"); +} const ACCOUNTS_BASE = "https://accounts.betterseqta.org"; export const CLOUD_SUMMARY_URL = `${ACCOUNTS_BASE}/api/user/cloud-summary`; @@ -226,8 +230,8 @@ async function putSettingsOnce(token: string): Promise { 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 }; + if (await isCloudSyncDisabled()) { + return { success: false, error: "Cloud sync is temporarily disabled", skipped: true }; } let t = token; for (let attempt = 0; attempt < 2; attempt++) { @@ -345,7 +349,7 @@ async function downloadIfNeeded(token: string): Promise { } async function runCloudSettingsPollInner(): Promise { - if (await isRemoteCloudSyncDisabled()) return; + if (await isCloudSyncDisabled()) return; const all = (await browser.storage.local.get()) as Record; if (!isAutoCloudSyncEnabled(all)) return; @@ -422,7 +426,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; + if (await isCloudSyncDisabled()) return; const all = (await browser.storage.local.get()) as Record; if (!isAutoCloudSyncEnabled(all)) return; if (suppressAutoUploadDuringRestore) return; @@ -432,7 +436,7 @@ export function requestCloudSettingsDebouncedUpload(): void { } async function runDebouncedUploadJob(): Promise { - if (await isRemoteCloudSyncDisabled()) return; + if (await isCloudSyncDisabled()) return; const all = (await browser.storage.local.get()) as Record; if (!isAutoCloudSyncEnabled(all)) return; const token = await getAccessToken(); @@ -464,7 +468,7 @@ function onStorageChanged( if (!keys.some((k) => isKeyIncludedInCloudUploadPayload(k))) return; void (async () => { - if (await isRemoteCloudSyncDisabled()) return; + if (await isCloudSyncDisabled()) return; const all = (await browser.storage.local.get()) as Record; if (!isAutoCloudSyncEnabled(all)) return; if (suppressAutoUploadDuringRestore) return; diff --git a/src/background/customThemesHandlers.ts b/src/background/customThemesHandlers.ts index cd1150dc..da1c3d19 100644 --- a/src/background/customThemesHandlers.ts +++ b/src/background/customThemesHandlers.ts @@ -1,5 +1,4 @@ import { normalizeCustomThemeApiResponse } from "@/seqta/utils/customThemes/parseApiEnvelope"; -import { bsplusApiQueryParams } from "@/seqta/utils/bsplusClientContext"; import { base64ToBlob } from "@/seqta/utils/base64"; type MessageSender = { (response?: unknown): void }; @@ -105,7 +104,6 @@ export function createCustomThemesHandlers(deps: { params.set("type", "betterseqta"); params.set("page", String(request.page ?? 1)); params.set("limit", String(request.limit ?? 20)); - (await bsplusApiQueryParams()).forEach((value, key) => params.set(key, value)); if (request.sort) params.set("sort", String(request.sort)); const searchRaw = request.search; const search = typeof searchRaw === "string" ? searchRaw.trim() : ""; @@ -134,7 +132,6 @@ export function createCustomThemesHandlers(deps: { params.set("page", String(request.page ?? 1)); params.set("limit", String(request.limit ?? 20)); params.set("type", "betterseqta"); - (await bsplusApiQueryParams()).forEach((value, key) => params.set(key, value)); if (request.status) params.set("status", String(request.status)); sendResponse(await customThemesJsonFetch(`/api/custom-themes/mine?${params}`, {}, true)); } catch (err) { diff --git a/src/background/remoteConfig.ts b/src/background/remoteConfig.ts deleted file mode 100644 index 86708518..00000000 --- a/src/background/remoteConfig.ts +++ /dev/null @@ -1,369 +0,0 @@ -import browser from "@/lib/browser"; -import { getBsplusDeviceName } from "@/seqta/utils/bsplusDeviceName"; -import { bsplusApiQueryParams, bsplusExtensionPayload } from "@/seqta/utils/bsplusClientContext"; -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 }; - -const ACCOUNTS_BASE = "https://accounts.betterseqta.org"; - -async function linkCloudInstall(token: string, installId: string): Promise { - try { - const extension = bsplusExtensionPayload(); - const r = await fetch(`${ACCOUNTS_BASE}/api/bsplus/installs/link`, { - method: "POST", - headers: { - Accept: "application/json", - "Content-Type": "application/json", - Authorization: `Bearer ${token}`, - }, - body: JSON.stringify({ - installId, - extensionVersion: extension.version, - extension, - deviceName: await getBsplusDeviceName(), - lastSeenAt: new Date().toISOString(), - }), - cache: "no-store", - }); - if (!r.ok) console.warn("[BetterSEQTA+] cloud install link failed:", r.status); - } catch (e) { - console.warn("[BetterSEQTA+] cloud install link failed:", e); - } -} - -async function parseJson(r: Response): Promise { - const text = await r.text(); - try { - return text ? JSON.parse(text) : {}; - } catch { - return null; - } -} - -async function readLastHostname(): Promise { - 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 { - try { - const manifestRes = await fetch(BS_STATUS_MANIFEST_URL, { cache: "no-store" }); - if (!manifestRes.ok) return null; - const manifest = (await parseJson(manifestRes)) as Record | 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 = {}; - for (const [key, fileName] of Object.entries(manifest.files as Record)) { - 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 { - 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 extension = bsplusExtensionPayload(); - const { bsplus_token, bsplus_user } = await browser.storage.local.get([ - "bsplus_token", - "bsplus_user", - ]); - const token = - typeof bsplus_token === "string" && bsplus_token.length > 0 ? bsplus_token : undefined; - 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, - extensionVersion: extension.version, - extension, - userId, - lastSeenAt: new Date().toISOString(), - ...(hostname ? { hostname } : {}), - }; - - try { - const headers: Record = { - Accept: "application/json", - "Content-Type": "application/json", - }; - if (token) headers.Authorization = `Bearer ${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); - } - if (token) void linkCloudInstall(token, installId); -} - -export async function refreshRemoteConfig(apiBase: () => string): Promise<{ - snapshot: RemoteConfigSnapshot; - fromNetwork: boolean; - primaryOk: boolean; -}> { - const base = apiBase(); - const hostname = await readLastHostname(); - const params = await bsplusApiQueryParams(); - 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 = { 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); - else { - const { bsplus_token } = await browser.storage.local.get("bsplus_token"); - if (typeof bsplus_token === "string" && bsplus_token) { - void linkCloudInstall(bsplus_token, await getOrCreateInstallId()); - } - } - } - })(); - } - }); -} - -export function createRemoteConfigHandlers( - apiBase: () => string, -): Record 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: unknown, sendResponse: MessageSender): boolean { - const { hostname: rawHostname } = req as { hostname?: unknown }; - const hostname = typeof rawHostname === "string" ? rawHostname.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; - } - - function handleFetchRemoteThemePackage(req: unknown, sendResponse: MessageSender): boolean { - const { packageId: rawPackageId } = req as { packageId?: unknown }; - const packageId = typeof rawPackageId === "string" ? rawPackageId.trim() : ""; - if (!packageId) { - sendResponse({ error: "Missing packageId" }); - return false; - } - void (async () => { - try { - const hostname = await readLastHostname(); - const params = await bsplusApiQueryParams(); - if (hostname) params.set("hostname", hostname); - const base = apiBase(); - const url = `${base}/api/bsplus/remote-theme-packages/${encodeURIComponent(packageId)}?${params}`; - if (!isAllowedFetchUrl(url)) { - sendResponse({ error: "URL not allowed" }); - return; - } - const r = await fetch(url, { cache: "no-store", headers: { Accept: "application/json" } }); - if (!r.ok) { - sendResponse({ error: `HTTP ${r.status}` }); - return; - } - const json = await parseJson(r); - if (!json || typeof json !== "object") { - sendResponse({ error: "Invalid package response" }); - return; - } - sendResponse({ package: json }); - } catch (e) { - sendResponse({ - error: e instanceof Error ? e.message : "Fetch failed", - }); - } - })(); - return true; - } - - function handleFetchRemoteThemePackageUrl(req: unknown, sendResponse: MessageSender): boolean { - const { url: rawUrl } = req as { url?: unknown }; - const url = typeof rawUrl === "string" ? rawUrl.trim() : ""; - if (!url || !isAllowedFetchUrl(url)) { - sendResponse({ error: "URL not allowed" }); - return false; - } - void (async () => { - try { - const r = await fetch(url, { cache: "no-store" }); - if (!r.ok) { - sendResponse({ error: `HTTP ${r.status}` }); - return; - } - const theme = await parseJson(r); - if (!theme || typeof theme !== "object") { - sendResponse({ error: "Invalid theme JSON" }); - return; - } - sendResponse({ theme }); - } catch (e) { - sendResponse({ - error: e instanceof Error ? e.message : "Fetch failed", - }); - } - })(); - return true; - } - - return { - refreshRemoteConfig: handleRefresh, - getRemoteConfigSnapshot: handleGetSnapshot, - setRemoteConfigPageContext: handleSetPageContext, - fetchRemoteThemePackage: handleFetchRemoteThemePackage, - fetchRemoteThemePackageUrl: handleFetchRemoteThemePackageUrl, - }; -} - -export async function isRemoteCloudSyncDisabled(): Promise { - 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; -} diff --git a/src/background/storageMigrations.ts b/src/background/storageMigrations.ts index 0016dd62..4691255b 100644 --- a/src/background/storageMigrations.ts +++ b/src/background/storageMigrations.ts @@ -7,7 +7,7 @@ function crossedUpgrade(previousVersion: string, boundary: string): boolean { return prev != null && curr != null && !semver.lt(curr, boundary) && semver.lt(prev, boundary); } -/** One-time storage patches when crossing 3.6.5 / 3.6.6 / 3.7.0 (see git history on main). */ +/** One-time storage patches when crossing 3.6.5 / 3.6.6 / 3.7.0 / 3.7.7 (see git history on main). */ export async function runStorageMigrations(previousVersion: string): Promise { if (crossedUpgrade(previousVersion, "3.6.5")) { try { @@ -47,4 +47,25 @@ export async function runStorageMigrations(previousVersion: string): Promise - import { - dismissOptionalRemoteTheme, - getRemoteConfigSnapshot, - isEffectiveBsplusEnabled, - isRemoteKillActive, - resolveEffectiveRemoteTheme, - 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 "@/lib/browser"; - import { onMount } from "svelte"; - - let localOverride = $state(false); - - const snapshot = $derived(getRemoteConfigSnapshot()); - const activeTheme = $derived(resolveEffectiveRemoteTheme(snapshot)); - const killActive = $derived(isRemoteKillActive()); - const statusMessage = $derived(getRemoteStatusMessage(snapshot)); - const allowOverride = $derived(snapshot.global.allowLocalOverride !== false); - const showStrip = $derived( - killActive || - activeTheme?.mode === "optional" || - !!statusMessage || - !!snapshot.global.maintenance?.body || - !!snapshot.global.maintenance?.title, - ); - - async function turnOffOptionalTheme() { - await dismissOptionalRemoteTheme(snapshot); - location.reload(); - } - - 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({ page: "settings", section: "general" }); - } - - -{#if showStrip} -
-

- {activeTheme?.mode === "optional" && activeTheme.message?.body - ? activeTheme.message.body - : statusMessage ?? - "BetterSEQTA+ is temporarily limited. You can review settings for details."} -

-
- {#if activeTheme?.mode === "optional" && snapshot.remoteTheme?.allowUserOptOut !== false} - - {/if} - {#if killActive && !isEffectiveBsplusEnabled() && allowOverride} - - {:else if killActive && localOverride && isEffectiveBsplusEnabled()} - - Running locally (override). Reload SEQTA after the operator clears the kill switch. - - {/if} - - {#if $settingsState.onoff === false} - Master toggle is off in General. - {/if} -
-
-{/if} diff --git a/src/interface/components/RemoteStatusStrip.svelte b/src/interface/components/RemoteStatusStrip.svelte new file mode 100644 index 00000000..7aee119e --- /dev/null +++ b/src/interface/components/RemoteStatusStrip.svelte @@ -0,0 +1,15 @@ + + +{#if message} +
+

{message}

+
+{/if} diff --git a/src/interface/components/store/ThemeModal.svelte b/src/interface/components/store/ThemeModal.svelte index 40824119..bc7667a2 100644 --- a/src/interface/components/store/ThemeModal.svelte +++ b/src/interface/components/store/ThemeModal.svelte @@ -13,7 +13,7 @@ import { getThemeApplyButtonStyles, resolveStoreVariantAccentColor, } from '@/interface/utils/themeListFilters' -import { isRemoteThemeStoreDisabled } from '@/seqta/utils/remoteConfig/runtime' +import { isFeatureDisabled } from '@/seqta/utils/remoteStatus' let { theme, currentThemes, @@ -52,7 +52,7 @@ adminPreviewMode?: boolean } = $props() const installActionLabel = $derived(adminPreviewMode ? 'Preview & apply' : 'Install') const isCommunity = $derived(variant === 'community') -const themeStoreInstallLocked = $derived(isRemoteThemeStoreDisabled() && !adminPreviewMode) +const themeStoreInstallLocked = $derived(isFeatureDisabled('themeStore.install') && !adminPreviewMode) const showFavorites = $derived(!isCommunity) function variantApplyStyles(variantId: string) { if (!theme) { diff --git a/src/interface/components/themes/ThemeSelector.svelte b/src/interface/components/themes/ThemeSelector.svelte index 44059257..16241a7a 100644 --- a/src/interface/components/themes/ThemeSelector.svelte +++ b/src/interface/components/themes/ThemeSelector.svelte @@ -10,13 +10,8 @@ import ThemePlaceholderCover from '@/interface/components/themes/ThemePlaceholderCover.svelte' import { isLocalCustomTheme } from '@/interface/utils/themeListFilters' import { formatCustomThemeApiError } from '@/seqta/utils/customThemes/apiErrors' - import { getRemoteConfigSnapshot, resolveEffectiveRemoteTheme } from '@/seqta/utils/remoteConfig/runtime' const themeManager = ThemeManager.getInstance(); - const remoteDirective = $derived(resolveEffectiveRemoteTheme(getRemoteConfigSnapshot())); - const remoteThemeForced = $derived( - remoteDirective?.mode === 'forced' && (remoteDirective.applicationMode ?? 'replace') === 'replace', - ); let themes = $state(null); let { isEditMode, showNavigation = true }: { @@ -41,7 +36,7 @@ }); const handleThemeClick = async (theme: CustomTheme, e: MouseEvent) => { - if (isEditMode || remoteThemeForced) return; + if (isEditMode) return; if (theme.id === themes?.selectedTheme) { themeManager.setTransitionPoint(e.clientX, e.clientY); await themeManager.disableTheme(); @@ -167,12 +162,7 @@ role="list" tabindex="-1" > - {#if remoteThemeForced} -

- Your school has applied a theme. Theme selection is locked until it is removed. -

- {/if} -
+
{#if themes} {#each themes.themes as theme (theme.id)} + `).firstChild!, + ); + setupSettingsButton(); + }); +} diff --git a/src/seqta/utils/feedback/client.ts b/src/seqta/utils/feedback/client.ts index 0404d1c1..9bafc6bc 100644 --- a/src/seqta/utils/feedback/client.ts +++ b/src/seqta/utils/feedback/client.ts @@ -16,7 +16,7 @@ import { type FeedbackProduct, } from "./constants"; import { getOrCreateInstallId } from "./installId"; -import { isRemoteFeedbackSubmitDisabled } from "@/seqta/utils/remoteConfig/runtime"; +import { isFeatureDisabled } from "@/seqta/utils/remoteStatus"; export class FeedbackApiError extends Error { constructor( @@ -149,7 +149,7 @@ export async function submitFeedback(form: FeedbackFormInput): Promise<{ id: str const err = validateFeedbackForm(form); if (err) throw new FeedbackApiError(err, 422); - if (isRemoteFeedbackSubmitDisabled()) { + if (isFeatureDisabled("feedback.submit")) { throw new FeedbackApiError( "Feedback submissions are temporarily disabled.", 503, diff --git a/src/seqta/utils/listeners/SettingsState.ts b/src/seqta/utils/listeners/SettingsState.ts index 667f7969..1ba32aa2 100644 --- a/src/seqta/utils/listeners/SettingsState.ts +++ b/src/seqta/utils/listeners/SettingsState.ts @@ -54,12 +54,7 @@ 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", + "bsplus_remote_status", ]); function isExcludedSettingsKey(key: string): boolean { diff --git a/src/seqta/utils/loaders/LoadHomePage.ts b/src/seqta/utils/loaders/LoadHomePage.ts index 309338a9..993afcf6 100644 --- a/src/seqta/utils/loaders/LoadHomePage.ts +++ b/src/seqta/utils/loaders/LoadHomePage.ts @@ -23,10 +23,7 @@ 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"; +import { isFeatureDisabled } from "@/seqta/utils/remoteStatus"; import type { ActiveSubjectLike, DateSortable, @@ -50,7 +47,7 @@ function clearLessonInterval(): void { } export async function loadHomePage() { - if (applyPageFeatureGateEarly("home")) return; + if (isFeatureDisabled("page.home")) return; homeTeardown?.(); homeTeardown = null; @@ -113,8 +110,6 @@ export async function loadHomePage() {
`); homeContainer.appendChild(skeletonStructure.firstChild!); - injectPageFeatureBanner("home", "#home-container"); - injectPageFeatureBanner("home", "#home-container"); if (settingsState.animations) { animate( diff --git a/src/seqta/utils/openers/OpenThemeOfTheMonthPopup.ts b/src/seqta/utils/openers/OpenThemeOfTheMonthPopup.ts index 27daedf6..fda47cca 100644 --- a/src/seqta/utils/openers/OpenThemeOfTheMonthPopup.ts +++ b/src/seqta/utils/openers/OpenThemeOfTheMonthPopup.ts @@ -3,7 +3,6 @@ import stringToHTML from "../stringToHTML"; import { settingsState } from "../listeners/SettingsState"; import { closePopup } from "./PopupManager"; import { getApiBase } from "../DevApiBase"; -import { withBsplusApiQuery } from "../bsplusClientContext"; import { openThemeStoreWithHighlight } from "../openThemeStoreWithHighlight"; import type { Theme } from "@/interface/types/Theme"; import { buildModalHeroSlides, normalizeStoreTheme } from "@/interface/utils/themeStoreFlavours"; @@ -59,8 +58,7 @@ async function writeCachedThemeOfTheMonth(entry: ThemeOfTheMonthEntry): Promise< */ export async function fetchThemeOfTheMonth(): Promise { try { - const url = await withBsplusApiQuery(`${getApiBase()}/api/theme-of-the-month/current`); - const res = await fetch(url, { + const res = await fetch(`${getApiBase()}/api/theme-of-the-month/current`, { cache: "no-store", signal: AbortSignal.timeout(TOTM_FETCH_TIMEOUT_MS), }); diff --git a/src/seqta/utils/openers/StartupPopupQueue.ts b/src/seqta/utils/openers/StartupPopupQueue.ts index ce5b8749..fc9b2891 100644 --- a/src/seqta/utils/openers/StartupPopupQueue.ts +++ b/src/seqta/utils/openers/StartupPopupQueue.ts @@ -1,5 +1,3 @@ -import semver from "semver"; -import browser from "@/lib/browser"; import { settingsState } from "../listeners/SettingsState"; import { OpenWhatsNewPopup } from "./OpenWhatsNewPopup"; import { @@ -19,38 +17,13 @@ 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; -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() { syncApiBaseToBackground(); - const steps: QueueStep[] = [...remoteCampaignSteps()]; + const steps: QueueStep[] = []; if (settingsState.justupdated) { steps.push((goNext) => OpenWhatsNewPopup(goNext)); diff --git a/src/seqta/utils/openers/openRemoteCampaignPopup.ts b/src/seqta/utils/openers/openRemoteCampaignPopup.ts deleted file mode 100644 index ce40c25a..00000000 --- a/src/seqta/utils/openers/openRemoteCampaignPopup.ts +++ /dev/null @@ -1,82 +0,0 @@ -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"; - -export function openRemoteCampaignPopup(campaign: RemoteCampaign, onDismissed?: () => void): void { - const title = campaign.header?.title ?? "BetterSEQTA+"; - const subtitle = campaign.header?.subtitle ?? ""; - let acknowledged = false; - - const header = stringToHTML( - /* html */ `

${title}

${subtitle ? `

${subtitle}

` : ""}
`, - ).firstChild as HTMLElement; - - const buttons = campaign.buttons?.length - ? campaign.buttons - : [{ id: "dismiss", label: "Dismiss", action: "dismiss" as const }]; - - const actionsHtml = buttons - .map( - (btn, i) => - ``, - ) - .join(""); - - const text = stringToHTML(/* html */ ` -
-
-
${actionsHtml}
-
- `).firstChild as HTMLElement; - - const bodySlot = text.querySelector(".bsplus-campaign-body"); - if (bodySlot && campaign.bodyHtml) bodySlot.innerHTML = campaign.bodyHtml; - - const content: HTMLElement[] = []; - const hero = campaign.hero; - if (hero?.url) { - if (hero.type === "video") { - content.push(createPopupHeroVideo(hero.url, hero.alt ?? "")); - } else { - const wrap = stringToHTML(/* html */ `
`) - .firstChild as HTMLElement; - const img = document.createElement("img"); - img.src = hero.url; - img.alt = hero.alt ?? ""; - img.className = "whatsnewImg"; - img.loading = "lazy"; - wrap.append(img); - content.push(wrap); - } - } - content.push(text); - - 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({ page: "settings", section: btn.section }); - await openSettingsPopup(); - } - if (campaign.requireAcknowledge) acknowledged = true; - await closePopup(); - }, - })); - - openPopup({ - header, - content, - animateSelector: ".whatsnewImgContainer, .whatsnewTextContainer *", - actions, - afterClose: () => { - void markCampaignSeen(campaign.id, campaign.requireAcknowledge ? acknowledged : undefined); - onDismissed?.(); - }, - }); -} diff --git a/src/seqta/utils/openers/whatsNewChangelog.ts b/src/seqta/utils/openers/whatsNewChangelog.ts index 2af0bf83..ee9fa770 100644 --- a/src/seqta/utils/openers/whatsNewChangelog.ts +++ b/src/seqta/utils/openers/whatsNewChangelog.ts @@ -17,7 +17,6 @@ export const WHATS_NEW_CHANGELOG: WhatsNewRelease[] = [ "Improved releiability of opening the connection for Timetable Sharing.", "Added a new submitter badge for community theme submitters.", "Added ability for Admin's to view unreleased community themes for QA.", - "Added ability for BetterSEQTA+ features to be dynamically configured remotly to negate compatability issues.", "Added ability to set BetterSEQTA Cloud Profile Picture from Extension Settings.", ], }, diff --git a/src/seqta/utils/patchThemeImagesPageContext.ts b/src/seqta/utils/patchThemeImagesPageContext.ts index 38bf754d..38938927 100644 --- a/src/seqta/utils/patchThemeImagesPageContext.ts +++ b/src/seqta/utils/patchThemeImagesPageContext.ts @@ -14,11 +14,8 @@ export type ThemePageSyncInput = { images?: Array<{ variableName: string; blob: Blob }>; customCss?: string; previewCss?: string; - overlayCss?: string; - overlayImages?: Array<{ variableName: string; blob: Blob }>; clear?: boolean; clearPreview?: boolean; - clearOverlay?: boolean; }; export function installThemeImagePagePatch(): void { @@ -62,22 +59,7 @@ function preserveCustomSidebarActive(css: string): string { return css.replace(/\.active(?![\w-])/g, ":is(.active, .bsplus-active)"); } -async function encodeImages(images?: Array<{ variableName: string; blob: Blob }>) { - if (images === undefined) return undefined; - return Promise.all( - images.map(async (image) => ({ - variableName: image.variableName, - data: await blobToBase64Data(image.blob), - mime: image.blob.type || "image/png", - })), - ); -} - export async function syncThemeToPage(input: ThemePageSyncInput): Promise { - if (input.clearOverlay) { - sendPayload({ clearOverlay: true }); - return; - } if (input.clear) { sendPayload({ clear: true }); return; @@ -91,15 +73,16 @@ export async function syncThemeToPage(input: ThemePageSyncInput): Promise if (input.previewCss !== undefined) { payload.previewCss = preserveCustomSidebarActive(input.previewCss); } - if (input.overlayCss !== undefined) { - payload.overlayCss = preserveCustomSidebarActive(input.overlayCss); + if (input.images !== undefined) { + payload.images = await Promise.all( + input.images.map(async (image) => ({ + variableName: image.variableName, + data: await blobToBase64Data(image.blob), + mime: image.blob.type || "image/png", + })), + ); } - const images = await encodeImages(input.images); - if (images !== undefined) payload.images = images; - const overlayImages = await encodeImages(input.overlayImages); - if (overlayImages !== undefined) payload.overlayImages = overlayImages; - if (Object.keys(payload).length === 0) return; sendPayload(payload); } diff --git a/src/seqta/utils/remoteConfig/apply.test.ts b/src/seqta/utils/remoteConfig/apply.test.ts deleted file mode 100644 index 2c2d4b3a..00000000 --- a/src/seqta/utils/remoteConfig/apply.test.ts +++ /dev/null @@ -1,148 +0,0 @@ -import { computeEffectiveEnabled, isRemoteFeatureAllowed, resolveFeatureMode } from "./apply"; -import { DEFAULT_REMOTE_CONFIG } from "./normalize"; -import type { RemoteConfigSnapshot } from "./types"; - -function snapshot(partial: Partial): 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("@/lib/browser", () => ({ - 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 }, - })); - jest.doMock("./routeGate", () => ({ - syncRouteEnhancementChrome: jest.fn(async () => {}), - })); - jest.doMock("./remoteTheme", () => ({ - scheduleReconcileRemoteTheme: jest.fn(), - dismissOptionalRemoteTheme: jest.fn(), - resolveEffectiveRemoteTheme: jest.fn(), - })); - const { hydrateRemoteConfigFromStorage, notifyRemoteConfigPageContext } = - await import("./runtime"); - await hydrateRemoteConfigFromStorage(); - notifyRemoteConfigPageContext("learn.example.edu.au"); - const browser = jest.requireMock("@/lib/browser"); - const types = browser.runtime.sendMessage.mock.calls.map( - (c: [{ type?: string }]) => c[0]?.type, - ); - expect(types).toContain("getRemoteConfigSnapshot"); - expect(types).toContain("setRemoteConfigPageContext"); - expect(types).toContain("refreshRemoteConfig"); - expect(types.indexOf("getRemoteConfigSnapshot")).toBeLessThan( - types.indexOf("refreshRemoteConfig"), - ); - }); -}); diff --git a/src/seqta/utils/remoteConfig/apply.ts b/src/seqta/utils/remoteConfig/apply.ts deleted file mode 100644 index 3773f40b..00000000 --- a/src/seqta/utils/remoteConfig/apply.ts +++ /dev/null @@ -1,112 +0,0 @@ -import type { FeatureMode, RemoteConfigSnapshot, RemoteFeatureGate } from "./types"; -import { DEFAULT_REMOTE_CONFIG } from "./normalize"; -import semver from "semver"; -import browser from "@/lib/browser"; - -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 = {}, -): 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 = {}, -): boolean { - const mode = resolveFeatureMode(key, snapshot, hiddenUntilVersion); - return mode === "allow" || mode === "banner"; -} - -export function shouldHideFeature( - key: string, - snapshot: RemoteConfigSnapshot, - hiddenUntilVersion: Record = {}, -): boolean { - return resolveFeatureMode(key, snapshot, hiddenUntilVersion) === "hide"; -} - -export function getFeatureMessage( - key: string, - snapshot: RemoteConfigSnapshot, -): RemoteFeatureGate["message"] | undefined { - return snapshot.features[key]?.message; -} diff --git a/src/seqta/utils/remoteConfig/normalize.test.ts b/src/seqta/utils/remoteConfig/normalize.test.ts deleted file mode 100644 index 21d86284..00000000 --- a/src/seqta/utils/remoteConfig/normalize.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -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"); - }); - - it("normalizes remoteTheme directive", () => { - const snap = normalizeRemoteConfigSnapshot({ - configVersion: "10", - remoteTheme: { - packageId: "pkg", - packageVersion: "1", - mode: "optional", - }, - }); - expect(snap.remoteTheme?.packageId).toBe("pkg"); - expect(snap.remoteTheme?.mode).toBe("optional"); - }); - - it("drops invalid remoteTheme", () => { - const snap = normalizeRemoteConfigSnapshot({ - remoteTheme: { mode: "forced" }, - }); - expect(snap.remoteTheme).toBeNull(); - }); - - it("normalizes applicationMode overlay", () => { - const snap = normalizeRemoteConfigSnapshot({ - remoteTheme: { - packageId: "p", - packageVersion: "1", - mode: "optional", - applicationMode: "overlay", - }, - }); - expect(snap.remoteTheme?.applicationMode).toBe("overlay"); - }); -}); - -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"); - }); -}); diff --git a/src/seqta/utils/remoteConfig/normalize.ts b/src/seqta/utils/remoteConfig/normalize.ts deleted file mode 100644 index fc880839..00000000 --- a/src/seqta/utils/remoteConfig/normalize.ts +++ /dev/null @@ -1,162 +0,0 @@ -import type { - RemoteConfigSnapshot, - RemoteFeatureGate, - RemoteGlobalConfig, - RemoteThemeDirective, -} from "./types"; - -export const DEFAULT_REMOTE_CONFIG: RemoteConfigSnapshot = { - configVersion: "0", - source: "default", - global: { mode: "on", allowLocalOverride: true }, - features: {}, - campaigns: [], - remoteTheme: null, -}; - -function normalizeGlobal(raw: unknown): RemoteGlobalConfig { - if (!raw || typeof raw !== "object") return DEFAULT_REMOTE_CONFIG.global; - const g = raw as Record; - 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 { - if (!raw || typeof raw !== "object") return {}; - const out: Record = {}; - for (const [key, value] of Object.entries(raw as Record)) { - if (!value || typeof value !== "object") continue; - const v = value as Record; - 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; -} - -function normalizeRemoteTheme(raw: unknown): RemoteThemeDirective | null { - if (!raw || typeof raw !== "object") return null; - const r = raw as Record; - const mode = r.mode; - if (mode !== "off" && mode !== "optional" && mode !== "forced") return null; - const packageId = typeof r.packageId === "string" ? r.packageId.trim() : ""; - const packageVersion = typeof r.packageVersion === "string" ? r.packageVersion.trim() : ""; - if (!packageId || !packageVersion) return null; - if (mode === "off") return null; - const msg = r.message; - return { - packageId, - packageVersion, - mode, - applicationMode: r.applicationMode === "overlay" ? "overlay" : "replace", - activeFrom: typeof r.activeFrom === "string" ? r.activeFrom : undefined, - activeTo: typeof r.activeTo === "string" ? r.activeTo : undefined, - allowUserOptOut: r.allowUserOptOut !== false, - message: - msg && typeof msg === "object" - ? { - title: - typeof (msg as { title?: string }).title === "string" - ? (msg as { title: string }).title - : undefined, - body: - typeof (msg as { body?: string }).body === "string" - ? (msg as { body: string }).body - : undefined, - } - : undefined, - }; -} - -export function normalizeRemoteConfigSnapshot(raw: unknown): RemoteConfigSnapshot { - if (!raw || typeof raw !== "object") return { ...DEFAULT_REMOTE_CONFIG }; - const r = raw as Record; - const data = r.data && typeof r.data === "object" ? (r.data as Record) : 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"]) - : [], - remoteTheme: normalizeRemoteTheme(data.remoteTheme), - }; -} - -/** Merge GitHub manifest + partial files into one snapshot. */ -export function mergeGithubConfigFiles( - manifest: Record, - files: Record, -): RemoteConfigSnapshot { - return normalizeRemoteConfigSnapshot({ - configVersion: manifest.configVersion ?? manifest.updatedAt ?? "0", - source: "github", - global: files.global ?? {}, - features: files.features ?? {}, - campaigns: files.campaigns ?? [], - remoteTheme: files.remoteTheme ?? null, - }); -} diff --git a/src/seqta/utils/remoteConfig/remoteTheme.ts b/src/seqta/utils/remoteConfig/remoteTheme.ts deleted file mode 100644 index 9c3ffdfe..00000000 --- a/src/seqta/utils/remoteConfig/remoteTheme.ts +++ /dev/null @@ -1,271 +0,0 @@ -import browser from "@/lib/browser"; -import localforage from "localforage"; -import type { CustomTheme } from "@/types/CustomThemes"; -import { - applyLocalSettingsRecord, - captureSyncableSettingsSnapshot, -} from "@/seqta/utils/cloudSettingsSync"; -import { settingsState, initializeSettingsState } from "@/seqta/utils/listeners/SettingsState"; -import { syncThemeToPage } from "@/seqta/utils/patchThemeImagesPageContext"; -import type { RemoteConfigSnapshot, RemoteThemeDirective } from "./types"; -import { - BSPLUS_REMOTE_THEME_BEFORE_V1_KEY, - BSPLUS_REMOTE_THEME_STATE_V1_KEY, - BSPLUS_REMOTE_THEME_USER_OFF_KEY, -} from "./storageKeys"; - -type BeforeSnapshot = { - capturedAt: string; - directiveKey: string; - storage: Record; - selectedTheme: string; -}; - -type ActiveThemeState = { - directiveKey: string; - layerIds: string[]; - mode: "optional" | "forced"; - applicationMode: "replace" | "overlay"; -}; - -type RemotePackage = { - theme?: Record; - overlayLayers?: Record[]; - downloadUrl?: string; -}; - -let reconcileChain: Promise = Promise.resolve(); - -function directiveKey(snapshot: RemoteConfigSnapshot, d: RemoteThemeDirective): string { - return `${snapshot.configVersion}|${d.packageId}|${d.packageVersion}|${d.mode}|${d.applicationMode ?? "replace"}`; -} - -function isWithinWindow(d: RemoteThemeDirective, now = Date.now()): boolean { - if (d.activeFrom && !Number.isNaN(Date.parse(d.activeFrom)) && now < Date.parse(d.activeFrom)) { - return false; - } - if (d.activeTo && !Number.isNaN(Date.parse(d.activeTo)) && now > Date.parse(d.activeTo)) { - return false; - } - return true; -} - -export function resolveEffectiveRemoteTheme( - snapshot: RemoteConfigSnapshot, -): RemoteThemeDirective | null { - const d = snapshot.remoteTheme; - if (!d || d.mode === "off" || !isWithinWindow(d)) return null; - return d; -} - -async function readJson(key: string): Promise { - const stored = await browser.storage.local.get(key); - const raw = stored[key]; - return raw && typeof raw === "object" ? (raw as T) : null; -} - -async function loadBeforeSnapshot(): Promise { - const b = await readJson(BSPLUS_REMOTE_THEME_BEFORE_V1_KEY); - if (!b?.directiveKey || !b.storage) return null; - return b; -} - -async function loadActiveState(): Promise { - return readJson(BSPLUS_REMOTE_THEME_STATE_V1_KEY); -} - -async function loadUserOffKey(): Promise { - const raw = await readJson<{ directiveKey?: string }>(BSPLUS_REMOTE_THEME_USER_OFF_KEY); - return typeof raw?.directiveKey === "string" ? raw.directiveKey : null; -} - -async function clearRemoteThemeLocalState(): Promise { - await browser.storage.local.remove([ - BSPLUS_REMOTE_THEME_BEFORE_V1_KEY, - BSPLUS_REMOTE_THEME_STATE_V1_KEY, - BSPLUS_REMOTE_THEME_USER_OFF_KEY, - ]); -} - -async function clearRemoteThemeOverlay(state?: ActiveThemeState | null): Promise { - const active = state ?? (await loadActiveState()); - await syncThemeToPage({ clearOverlay: true }); - if (!active?.layerIds?.length) return; - const { ThemeManager } = await import("@/plugins/built-in/themes/theme-manager"); - const tm = ThemeManager.getInstance(); - for (const id of active.layerIds) { - await tm.deleteTheme(id).catch(() => {}); - } -} - -export async function dismissOptionalRemoteTheme(snapshot: RemoteConfigSnapshot): Promise { - const d = resolveEffectiveRemoteTheme(snapshot); - if (!d || d.mode !== "optional") return; - await browser.storage.local.set({ - [BSPLUS_REMOTE_THEME_USER_OFF_KEY]: { directiveKey: directiveKey(snapshot, d) }, - }); - await restoreRemoteThemeSnapshot(); -} - -async function restoreRemoteThemeSnapshot(): Promise { - const state = await loadActiveState(); - if (state?.applicationMode === "overlay") { - await clearRemoteThemeOverlay(state); - await clearRemoteThemeLocalState(); - return; - } - const before = await loadBeforeSnapshot(); - if (before) { - await applyLocalSettingsRecord(before.storage); - await initializeSettingsState(); - const { ThemeManager } = await import("@/plugins/built-in/themes/theme-manager"); - const tm = ThemeManager.getInstance(); - if (before.selectedTheme) await tm.setTheme(before.selectedTheme, false); - else await tm.disableTheme(); - } - await clearRemoteThemeLocalState(); -} - -async function fetchPackage(packageId: string): Promise { - try { - const res = (await browser.runtime.sendMessage({ - type: "fetchRemoteThemePackage", - packageId, - })) as { package?: RemotePackage; error?: string }; - return res?.package && !res.error ? res.package : null; - } catch { - return null; - } -} - -async function fetchDownload(url: string): Promise | null> { - try { - const res = (await browser.runtime.sendMessage({ - type: "fetchRemoteThemePackageUrl", - url, - })) as { theme?: Record }; - return res?.theme && typeof res.theme === "object" ? res.theme : null; - } catch { - return null; - } -} - -async function resolveLayers(pkg: RemotePackage): Promise[]> { - if (Array.isArray(pkg.overlayLayers) && pkg.overlayLayers.length) { - return pkg.overlayLayers.filter((l) => l && typeof l === "object") as Record[]; - } - if (pkg.theme && typeof pkg.theme === "object") return [pkg.theme]; - if (!pkg.downloadUrl) return []; - const dl = await fetchDownload(pkg.downloadUrl); - if (!dl) return []; - if (Array.isArray((dl as { overlayLayers?: unknown }).overlayLayers)) { - return (dl as { overlayLayers: Record[] }).overlayLayers; - } - return [dl]; -} - -async function saveActiveState(state: ActiveThemeState): Promise { - await browser.storage.local.set({ [BSPLUS_REMOTE_THEME_STATE_V1_KEY]: state }); - await browser.storage.local.remove(BSPLUS_REMOTE_THEME_USER_OFF_KEY); -} - -async function applyRemoteTheme( - snapshot: RemoteConfigSnapshot, - directive: RemoteThemeDirective, -): Promise { - if (directive.mode === "off") return; - const key = directiveKey(snapshot, directive); - const prior = await loadActiveState(); - if (prior?.directiveKey === key) return; - - const overlay = (directive.applicationMode ?? "replace") === "overlay"; - if (prior?.applicationMode === "overlay") await clearRemoteThemeOverlay(prior); - - const pkg = await fetchPackage(directive.packageId); - if (!pkg) return; - - const layers = await resolveLayers(pkg); - const { ThemeManager } = await import("@/plugins/built-in/themes/theme-manager"); - const tm = ThemeManager.getInstance(); - - if (overlay) { - if (!layers.length) return; - for (const layer of layers) { - if (typeof layer.id !== "string" || !layer.name) continue; - await tm.installTheme(layer as Parameters[0], { fromStore: false }); - } - if (settingsState.selectedTheme) await tm.setTheme(settingsState.selectedTheme, false); - - const css: string[] = []; - const images = new Map(); - const layerIds: string[] = []; - for (const layer of layers) { - if (typeof layer.id === "string") layerIds.push(layer.id); - if (typeof layer.CustomCSS === "string") css.push(layer.CustomCSS); - const stored = - typeof layer.id === "string" - ? ((await localforage.getItem(layer.id)) as CustomTheme | null) - : null; - for (const img of stored?.CustomImages ?? []) { - if (img.variableName && img.blob) images.set(img.variableName, img); - } - } - await syncThemeToPage({ - overlayCss: css.join("\n"), - overlayImages: [...images.values()], - }); - await saveActiveState({ - directiveKey: key, - layerIds, - mode: directive.mode, - applicationMode: "overlay", - }); - return; - } - - const theme = layers[0]; - if (!theme || typeof theme.id !== "string") return; - - await captureBeforeSnapshot(key); - await tm.installTheme(theme as Parameters[0], { - fromStore: false, - forceTheme: directive.mode === "forced", - }); - await tm.setTheme(String(theme.id), false); - await saveActiveState({ - directiveKey: key, - layerIds: [String(theme.id)], - mode: directive.mode, - applicationMode: "replace", - }); -} - -async function captureBeforeSnapshot(directiveKey: string): Promise { - const existing = await loadBeforeSnapshot(); - if (existing?.directiveKey === directiveKey) return; - await browser.storage.local.set({ - [BSPLUS_REMOTE_THEME_BEFORE_V1_KEY]: { - capturedAt: new Date().toISOString(), - directiveKey, - storage: await captureSyncableSettingsSnapshot(), - selectedTheme: settingsState.selectedTheme ?? "", - }, - }); -} - -async function reconcileRemoteThemeInner(snapshot: RemoteConfigSnapshot): Promise { - const d = resolveEffectiveRemoteTheme(snapshot); - if (!d) { - if (await loadActiveState()) await restoreRemoteThemeSnapshot(); - return; - } - const key = directiveKey(snapshot, d); - if (d.mode === "optional" && (await loadUserOffKey()) === key) return; - await applyRemoteTheme(snapshot, d); -} - -export function scheduleReconcileRemoteTheme(snapshot: RemoteConfigSnapshot): void { - reconcileChain = reconcileChain - .then(() => reconcileRemoteThemeInner(snapshot)) - .catch((e) => console.warn("[BetterSEQTA+] remote theme reconcile failed:", e)); -} diff --git a/src/seqta/utils/remoteConfig/routeGate.ts b/src/seqta/utils/remoteConfig/routeGate.ts deleted file mode 100644 index cd82b133..00000000 --- a/src/seqta/utils/remoteConfig/routeGate.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { checkRemoteFeature } from "./runtime"; - -export const ROUTE_STRIP_KEEP_PLUGINS = new Set(["themes", "animated-background"]); - -export function parseSeqtaPageKeyFromHash(hash = location.hash): string | null { - const match = hash.match(/[#?]page=\/([^/?&#]+)/i) ?? hash.match(/page=\/([^/?&#]+)/i); - if (!match?.[1]) return null; - return match[1].trim().toLowerCase(); -} - -export function isRemoteRouteEnhancementsStripped(pageKey?: string | null): boolean { - const key = pageKey ?? parseSeqtaPageKeyFromHash(); - if (!key) return false; - return checkRemoteFeature(`page.${key}`).mode === "block"; -} - -export function remoteChromeGateAllowed( - key: "ui.sidebar.styled" | "ui.titlebar.custom" | "ui.titlebar.founderBadge", -): boolean { - const mode = checkRemoteFeature(key).mode; - return mode !== "hide" && mode !== "block"; -} - -export async function syncRouteEnhancementChrome(): Promise { - if (isRemoteRouteEnhancementsStripped()) { - const { clearNativeSidebar } = await import("@/seqta/ui/sidebar/applyNativeSidebar"); - clearNativeSidebar(); - const { unmountCustomTitleBar } = await import("@/seqta/ui/titlebar/mountCustomTitleBar"); - unmountCustomTitleBar(); - const { pluginManager } = await import("@/plugins/index"); - await pluginManager.stopPluginsExcept(ROUTE_STRIP_KEEP_PLUGINS); - return; - } - - if (remoteChromeGateAllowed("ui.sidebar.styled")) { - const { applyNativeSidebar } = await import("@/seqta/ui/sidebar/applyNativeSidebar"); - await applyNativeSidebar(); - } - if (remoteChromeGateAllowed("ui.titlebar.custom")) { - const { mountCustomTitleBar } = await import("@/seqta/ui/titlebar/mountCustomTitleBar"); - void mountCustomTitleBar(); - } - const { pluginManager } = await import("@/plugins/index"); - await pluginManager.startAllPlugins(); -} diff --git a/src/seqta/utils/remoteConfig/runtime.ts b/src/seqta/utils/remoteConfig/runtime.ts deleted file mode 100644 index d2c08f50..00000000 --- a/src/seqta/utils/remoteConfig/runtime.ts +++ /dev/null @@ -1,290 +0,0 @@ -import browser from "@/lib/browser"; -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"; -import { scheduleReconcileRemoteTheme } from "./remoteTheme"; - -export { dismissOptionalRemoteTheme, resolveEffectiveRemoteTheme } from "./remoteTheme"; - -let snapshot: RemoteConfigSnapshot = normalizeRemoteConfigSnapshot(null); -let localOverride = false; -let hiddenUntilVersion: Record = {}; -let campaignSeen: CampaignSeenRecord = {}; - -const SNAPSHOT_FETCH_TIMEOUT_MS = 200; - -function kickRemoteSideEffects(): void { - scheduleReconcileRemoteTheme(snapshot); - void import("./routeGate").then((m) => m.syncRouteEnhancementChrome()); -} - -export function getRemoteConfigSnapshot(): RemoteConfigSnapshot { - return snapshot; -} - -export function getHiddenUntilVersion(): Record { - 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 { - localOverride = enabled; - await browser.storage.local.set({ [BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY]: enabled }); -} - -function applyRemoteRuntime( - next: RemoteConfigSnapshot, - override: boolean, - hidden: Record, - 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 { - 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((resolve) => setTimeout(() => resolve(null), SNAPSHOT_FETCH_TIMEOUT_MS)), - ])) as { snapshot?: unknown } | null; - if (res?.snapshot) raw = res.snapshot; - } catch { - // SW unavailable - } - } - - applyRemoteRuntime( - normalizeRemoteConfigSnapshot(raw), - stored[BSPLUS_LOCAL_OVERRIDE_ONOFF_KEY] === true, - (stored[BSPLUS_FEATURES_HIDDEN_UNTIL_VERSION_KEY] as Record) ?? {}, - (stored[BSPLUS_CAMPAIGN_SEEN_KEY] as CampaignSeenRecord) ?? {}, - ); - kickRemoteSideEffects(); - return snapshot; -} - -export function syncRemoteConfigFromBackend(): void { - void browser.runtime.sendMessage({ type: "refreshRemoteConfig" }).catch(() => {}); -} - -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(() => {}); - syncRemoteConfigFromBackend(); -} - -export async function markCampaignSeen(campaignId: string, ack?: boolean): Promise { - campaignSeen = { - ...campaignSeen, - [campaignId]: { - seenAt: new Date().toISOString(), - ...(ack === true ? { ack: true } : ack === false ? { ack: false } : {}), - }, - }; - 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(() => { - kickRemoteSideEffects(); - 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 */ `

${title}

${body}

`, - ).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 */ ` -
- ${gate.message.title ? `

${gate.message.title}

` : ""} -

${gate.message.body}

-
- `).firstChild!, - container.firstChild, - ); -} - -/** Remote kill path: settings popup + toolbar cog without monofile. */ -export async function ensureKilledModeSettingsAccess(): Promise { - addExtensionSettings(); - if (document.getElementById("AddedSettings")) { - setupSettingsButton(); - return; - } - - const fallback = - document.getElementById("content") ?? document.getElementById("container") ?? document.body; - - const mountParent = async (): Promise => { - 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 */ ` - - `).firstChild!, - ); - setupSettingsButton(); - }); -} diff --git a/src/seqta/utils/remoteConfig/storageKeys.ts b/src/seqta/utils/remoteConfig/storageKeys.ts deleted file mode 100644 index c82cc6ae..00000000 --- a/src/seqta/utils/remoteConfig/storageKeys.ts +++ /dev/null @@ -1,20 +0,0 @@ -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 BSPLUS_REMOTE_THEME_BEFORE_V1_KEY = "bsplus_remote_theme_before_v1"; -export const BSPLUS_REMOTE_THEME_STATE_V1_KEY = "bsplus_remote_theme_state_v1"; -export const BSPLUS_REMOTE_THEME_USER_OFF_KEY = "bsplus_remote_theme_user_off"; - -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"; diff --git a/src/seqta/utils/remoteConfig/types.ts b/src/seqta/utils/remoteConfig/types.ts deleted file mode 100644 index b30a5e7b..00000000 --- a/src/seqta/utils/remoteConfig/types.ts +++ /dev/null @@ -1,70 +0,0 @@ -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 RemoteThemeMode = "off" | "optional" | "forced"; -export type RemoteThemeApplicationMode = "replace" | "overlay"; - -export type RemoteThemeDirective = { - packageId: string; - packageVersion: string; - mode: RemoteThemeMode; - applicationMode?: RemoteThemeApplicationMode; - activeFrom?: string; - activeTo?: string; - message?: { title?: string; body?: string }; - allowUserOptOut?: boolean; -}; - -export type RemoteConfigSnapshot = { - configVersion: string; - etag?: string; - source?: "api" | "github" | "default" | "cache"; - global: RemoteGlobalConfig; - features: Record; - campaigns: RemoteCampaign[]; - remoteTheme?: RemoteThemeDirective | null; -}; - -export type CampaignSeenRecord = Record; diff --git a/src/seqta/utils/remoteStatus.test.ts b/src/seqta/utils/remoteStatus.test.ts new file mode 100644 index 00000000..02f8a28f --- /dev/null +++ b/src/seqta/utils/remoteStatus.test.ts @@ -0,0 +1,21 @@ +import { normalizeRemoteStatus } from "./remoteStatus"; + +describe("normalizeRemoteStatus", () => { + it("falls back to working defaults for missing or malformed data", () => { + const defaults = { off: false, message: null, disabledFeatures: [] }; + expect(normalizeRemoteStatus(null)).toEqual(defaults); + expect( + normalizeRemoteStatus({ off: "yes", message: 4, disabledFeatures: "page.news" }), + ).toEqual(defaults); + }); + + it("keeps valid fields and drops non-string feature keys", () => { + expect( + normalizeRemoteStatus({ + off: true, + message: "Back soon", + disabledFeatures: ["page.news", 1], + }), + ).toEqual({ off: true, message: "Back soon", disabledFeatures: ["page.news"] }); + }); +}); diff --git a/src/seqta/utils/remoteStatus.ts b/src/seqta/utils/remoteStatus.ts new file mode 100644 index 00000000..79dfb8ef --- /dev/null +++ b/src/seqta/utils/remoteStatus.ts @@ -0,0 +1,45 @@ +import browser from "@/lib/browser"; + +export type RemoteStatus = { + off: boolean; + message: string | null; + disabledFeatures: string[]; +}; + +const STATUS_URL = + "https://raw.githubusercontent.com/BetterSEQTA/BS-Status/main/config/status.json"; +export const REMOTE_STATUS_KEY = "bsplus_remote_status"; + +export function normalizeRemoteStatus(raw: unknown): RemoteStatus { + const r = (raw && typeof raw === "object" ? raw : {}) as Record; + return { + off: r.off === true, + message: typeof r.message === "string" && r.message.trim() ? r.message : null, + disabledFeatures: Array.isArray(r.disabledFeatures) + ? r.disabledFeatures.filter((key): key is string => typeof key === "string") + : [], + }; +} + +export async function readRemoteStatus(): Promise { + const stored = await browser.storage.local.get(REMOTE_STATUS_KEY); + return normalizeRemoteStatus(stored[REMOTE_STATUS_KEY]); +} + +let status = normalizeRemoteStatus(null); + +export const getRemoteStatus = (): RemoteStatus => status; + +export const isFeatureDisabled = (key: string): boolean => status.disabledFeatures.includes(key); + +export async function loadRemoteStatus(): Promise { + status = await readRemoteStatus(); +} + +export async function refreshRemoteStatus(): Promise { + const res = await browser.runtime + .sendMessage({ type: "fetchFromUrl", url: STATUS_URL }) + .catch(() => null); + if (!res?.data && res?.httpStatus !== 404) return; + await browser.storage.local.set({ [REMOTE_STATUS_KEY]: normalizeRemoteStatus(res.data) }); +} diff --git a/src/seqta/utils/themeImagePagePatch.js b/src/seqta/utils/themeImagePagePatch.js index 613a9768..ba1caaf0 100644 --- a/src/seqta/utils/themeImagePagePatch.js +++ b/src/seqta/utils/themeImagePagePatch.js @@ -6,10 +6,7 @@ const PAYLOAD_ID = "bsplus-theme-image-payload"; const IMAGES_STYLE_ID = "bsplus-theme-images"; const THEME_STYLE_ID = "custom-theme"; const PREVIEW_STYLE_ID = "custom-theme-preview"; -const OVERLAY_STYLE_ID = "bsplus-remote-theme-overlay"; -const OVERLAY_IMAGES_STYLE_ID = "bsplus-remote-theme-overlay-images"; const urlCache = new Set(); -const overlayUrlCache = new Set(); let headObserver = null; function log(event, detail) { @@ -32,13 +29,6 @@ function styleEl(id) { return el; } -function keepOverlayStylesLast() { - for (const id of [OVERLAY_IMAGES_STYLE_ID, OVERLAY_STYLE_ID]) { - const el = document.getElementById(id); - if (el && document.head.contains(el)) document.head.appendChild(el); - } -} - function keepThemeStyleLast() { const themeStyle = document.getElementById(THEME_STYLE_ID); if ( @@ -48,7 +38,6 @@ function keepThemeStyleLast() { ) { document.head.appendChild(themeStyle); } - keepOverlayStylesLast(); } function watchHead() { @@ -69,10 +58,10 @@ function setStyleText(id, text, watchThemeOrder) { } } -function applyRootImages(images, styleId, cache, afterApply) { - releaseCache(cache); +function applyThemeImages(images) { + releaseCache(urlCache); if (!images?.length) { - document.getElementById(styleId)?.remove(); + setStyleText(IMAGES_STYLE_ID, ""); return; } const lines = [":root {"]; @@ -80,23 +69,15 @@ function applyRootImages(images, styleId, cache, afterApply) { if (!img?.variableName || !img.data) continue; try { const url = URL.createObjectURL(base64ToBlob(img.data, img.mime || "image/png")); - cache.add(url); + urlCache.add(url); lines.push(` --${img.variableName}: url("${url}");`); } catch (e) { console.warn(LOG, "skip image", img.variableName, e); } } lines.push("}"); - styleEl(styleId).textContent = lines.join("\n"); - afterApply?.(); - log("images applied", { styleId, count: images.length }); -} - -function clearOverlayOnly() { - releaseCache(overlayUrlCache); - document.getElementById(OVERLAY_STYLE_ID)?.remove(); - document.getElementById(OVERLAY_IMAGES_STYLE_ID)?.remove(); - log("overlay cleared"); + styleEl(IMAGES_STYLE_ID).textContent = lines.join("\n"); + log("images applied", { count: images.length }); } function clearAll() { @@ -122,31 +103,12 @@ function processPayload() { clearAll(); return; } - if (payload.clearOverlay) { - clearOverlayOnly(); - return; - } - if (payload.images !== undefined) { - applyRootImages(payload.images, IMAGES_STYLE_ID, urlCache); - } + if (payload.images !== undefined) applyThemeImages(payload.images); if (payload.customCss !== undefined) { setStyleText(THEME_STYLE_ID, payload.customCss || "", true); log("custom css applied"); } - if (payload.overlayImages !== undefined) { - applyRootImages( - payload.overlayImages, - OVERLAY_IMAGES_STYLE_ID, - overlayUrlCache, - keepOverlayStylesLast, - ); - } - if (payload.overlayCss !== undefined) { - setStyleText(OVERLAY_STYLE_ID, payload.overlayCss || "", false); - keepOverlayStylesLast(); - log("overlay css applied"); - } if (payload.previewCss !== undefined) { setStyleText(PREVIEW_STYLE_ID, payload.previewCss || ""); const previewStyle = document.getElementById(PREVIEW_STYLE_ID);