Replace remote config with a static off switch

The extension now reads one public status file with no identifiers.
Campaigns, forced remote themes, install registration, hostname capture
and install ID/user ID query params on theme requests are gone.
This commit is contained in:
SethBurkart123 committed 2026-11-03 16:01:43 +11:00
1 parent deafdd27a0
commit bfe8e3645b
45 files changed
+255 -2112

No files matched your search

+2 -24
View File
@@ -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<string, string> = {};
if (token) headers["Authorization"] = `Bearer ${token}`;
@@ -166,10 +155,7 @@ function handleFetchThemeDetails(request: BackgroundRequest, sendResponse: Messa
const token = await getAccessTokenFromStorage();
const headers: Record<string, string> = {};
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<string, MessageHandler> = {
...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();
+11 -7
View File
@@ -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<boolean> {
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<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 };
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<void> {
}
async function runCloudSettingsPollInner(): Promise<void> {
if (await isRemoteCloudSyncDisabled()) return;
if (await isCloudSyncDisabled()) return;
const all = (await browser.storage.local.get()) as Record<string, unknown>;
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<string, unknown>;
if (!isAutoCloudSyncEnabled(all)) return;
if (suppressAutoUploadDuringRestore) return;
@@ -432,7 +436,7 @@ export function requestCloudSettingsDebouncedUpload(): void {
}
async function runDebouncedUploadJob(): Promise<void> {
if (await isRemoteCloudSyncDisabled()) return;
if (await isCloudSyncDisabled()) return;
const all = (await browser.storage.local.get()) as Record<string, unknown>;
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<string, unknown>;
if (!isAutoCloudSyncEnabled(all)) return;
if (suppressAutoUploadDuringRestore) return;
-3
View File
@@ -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) {
-369
View File
@@ -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<void> {
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<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 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<string, string> = {
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<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);
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<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: 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<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;
}
+22 -1
View File
@@ -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<void> {
if (crossedUpgrade(previousVersion, "3.6.5")) {
try {
@@ -47,4 +47,25 @@ export async function runStorageMigrations(previousVersion: string): Promise<voi
console.warn("[BetterSEQTA+] Theme of the Month 3.7.0 dismissal migration failed:", e);
}
}
if (crossedUpgrade(previousVersion, "3.7.7")) {
try {
await browser.storage.local.remove([
"bsplus_remote_config_snapshot",
"bsplus_remote_config_etag",
"bsplus_remote_config_fetched_at",
"bsplus_remote_config_last_hostname",
"bsplus_remote_last_primary_ok",
"bsplus_campaign_seen",
"bsplus_local_override_onoff",
"bsplus_features_hidden_until_version",
"bsplus_install_registered_at",
"bsplus_remote_theme_before_v1",
"bsplus_remote_theme_state_v1",
"bsplus_remote_theme_user_off",
]);
} catch (e) {
console.warn("[BetterSEQTA+] 3.7.7 storage cleanup migration failed:", e);
}
}
}
-17
View File
@@ -4077,23 +4077,6 @@ div.day-empty {
pointer-events: auto;
}
.bsplus-remote-page-banner {
width: 90%;
margin: 0 auto 0.75rem;
padding: 0.65rem 0.85rem;
border-radius: 12px;
border: 1px solid color-mix(in srgb, var(--text-primary) 14%, transparent);
background: color-mix(in srgb, var(--text-primary) 5%, var(--background-primary));
font-size: 0.95rem;
line-height: 1.5;
color: var(--text-primary);
}
.bsplus-remote-page-banner__title {
font-weight: 600;
margin: 0 0 0.35rem;
}
.whatsnewTextContainer.bsplus-founder-badge-body p {
margin: 0 0 1rem;
font-size: 1.2rem;
@@ -1,99 +0,0 @@
<script lang="ts">
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" });
}
</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">
{activeTheme?.mode === "optional" && activeTheme.message?.body
? activeTheme.message.body
: statusMessage ??
"BetterSEQTA+ is temporarily limited. You can review settings for details."}
</p>
<div class="mt-2 flex flex-wrap items-center gap-2">
{#if activeTheme?.mode === "optional" && snapshot.remoteTheme?.allowUserOptOut !== false}
<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-hidden focus:ring-2 focus:ring-amber-500 focus:ring-offset-2 dark:focus:ring-offset-zinc-900"
onclick={() => void turnOffOptionalTheme()}
>
Turn off school theme
</button>
{/if}
{#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-hidden 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-hidden 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}
@@ -0,0 +1,15 @@
<script lang="ts">
import { getRemoteStatus } from "@/seqta/utils/remoteStatus";
const status = getRemoteStatus();
const message = status.message ?? (status.off ? "BetterSEQTA+ is temporarily disabled." : null);
</script>
{#if message}
<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">{message}</p>
</div>
{/if}
@@ -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) {
@@ -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<ThemeList | null>(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}
<p class="mb-3 rounded-lg border border-amber-500/40 bg-amber-500/10 px-3 py-2 text-sm text-amber-900 dark:text-amber-100">
Your school has applied a theme. Theme selection is locked until it is removed.
</p>
{/if}
<div class="{useTwoColumnLayout ? 'grid grid-cols-2 gap-3' : 'flex flex-col gap-2 px-2'} {remoteThemeForced ? 'pointer-events-none opacity-50' : ''}">
<div class="{useTwoColumnLayout ? 'grid grid-cols-2 gap-3' : 'flex flex-col gap-2 px-2'}">
{#if themes}
{#each themes.themes as theme (theme.id)}
<button
+2
View File
@@ -3,6 +3,7 @@ import IconFamily from "@/resources/fonts/IconFamily.woff";
import { resolveExtensionAssetUrl } from "@/lib/extensionAssetUrl";
import renderSvelte from "./main";
import { initializeSettingsState } from "@/seqta/utils/listeners/SettingsState";
import { loadRemoteStatus } from "@/seqta/utils/remoteStatus";
import { initVerboseLogging, verboseInfo } from "@/utils/verboseLog";
function InjectCustomIcons() {
@@ -31,6 +32,7 @@ if (!mountPoint) {
void (async () => {
await initializeSettingsState();
await loadRemoteStatus();
initVerboseLogging();
const { syncApiBaseToBackground } = await import("@/seqta/utils/DevApiBase");
syncApiBaseToBackground();
+9 -6
View File
@@ -21,8 +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 RemoteStatusStrip from "../components/RemoteStatusStrip.svelte";
import { isFeatureDisabled } from "@/seqta/utils/remoteStatus";
import {
consumeSettingsDestination,
SETTINGS_NAVIGATION_EVENT,
@@ -88,11 +88,14 @@
const ghReleaseChannelLabel = getInstalledGhReleaseChannelLabel();
let ghReleaseUpdate = $state<GhReleaseUpdateInfo | null>(null);
const isSectionVisible = (id: string) =>
!isFeatureDisabled(id === "account" ? "settings.nav.cloud" : `settings.section.${id}`);
const userNav: NavItem[] = [
{ id: "account", label: "My Account" },
{ id: "general", label: "General" },
{ id: "appearance", label: "Appearance" },
].filter((item) => isRemoteSettingsSectionVisible(item.id));
].filter((item) => isSectionVisible(item.id));
$effect(() => {
if (!$settingsState.devMode && activeSection === "advanced") activeSection = "general";
@@ -104,7 +107,7 @@
{ id: "features", label: "Features" },
...($settingsState.devMode ? [{ id: "advanced", label: "Advanced" }] : []),
{ id: "shortcuts", label: "Shortcuts" },
].filter((item) => isRemoteSettingsSectionVisible(item.id)));
].filter((item) => isSectionVisible(item.id)));
const settingsNavGroups = $derived([
{ label: "User Settings", items: userNav },
@@ -553,7 +556,7 @@
onToggleSize={standalone ? undefined : toggleExpanded}
/>
<RemoteConfigStatusStrip />
<RemoteStatusStrip />
<!-- Body: left nav + content -->
<div class="flex flex-1 min-h-0 overflow-hidden">
@@ -734,7 +737,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 />
<RemoteStatusStrip />
<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'}"
>
@@ -13,14 +13,12 @@
import browser from "@/lib/browser";
import { matchesSearch, type SettingsSectionSharedProps } from "../shared";
import type { SettingsList } from "@/interface/types/SettingsProps";
import { checkRemoteFeature } from "@/seqta/utils/remoteConfig/runtime";
import { isFeatureDisabled } from "@/seqta/utils/remoteStatus";
let { searchQuery = "" }: SettingsSectionSharedProps = $props();
const isEngage = isSeqtaEngageExperience();
const onoffGate = $derived(checkRemoteFeature("settings.control.onoff"));
const onoffGreyedOut = $derived(onoffGate.mode === "greyout");
const sidebarEditHidden = $derived(checkRemoteFeature("ui.sidebar.edit").hide);
const sidebarEditHidden = isFeatureDisabled("ui.sidebar.edit");
const generalOptions = $derived([
{
@@ -149,19 +147,7 @@
{#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)}
{#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}
<SettingRow {...option} {searchQuery} />
{#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,7 +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 { isFeatureDisabled } from "@/seqta/utils/remoteStatus";
import { applyMenuItemVisibility } from "@/seqta/utils/menuItemVisibility";
import { getNativeMenuList } from "@/seqta/ui/sidebar/parseNativeMenu";
import { rafThrottle } from "@/seqta/utils/rafThrottle";
@@ -30,7 +30,7 @@ export async function injectAnalyticsMenuItem(): Promise<() => void> {
if (isSeqtaEngageExperience()) {
return () => {};
}
if (checkRemoteFeature("page.analytics").hide) {
if (isFeatureDisabled("page.analytics")) {
return () => {};
}
@@ -48,11 +48,7 @@ describe("cloud theme restoration", () => {
it.each(["themes", "custom-themes"])("installs a missing %s catalog theme", async (catalog) => {
const jsonUrl = "https://betterseqta.org/storage/theme.json";
(browser.runtime.sendMessage as jest.Mock).mockImplementation(async ({ url }) => {
if (
typeof url === "string" &&
url.includes(`/api/${catalog}/catalog-id/download`) &&
url.includes("extensionVersion=")
) {
if (url === `https://betterseqta.org/api/${catalog}/catalog-id/download`) {
return {
data: { success: true, data: { theme_json_url: jsonUrl } },
};
+2 -19
View File
@@ -12,7 +12,6 @@ import { fullMotionEffectsEnabled } from "@/seqta/utils/performanceMode";
import debounce from "@/seqta/utils/debounce";
import { themeUpdates } from "@/interface/hooks/ThemeUpdates";
import { getApiBase } from "@/seqta/utils/DevApiBase";
import { withBsplusApiQuery } from "@/seqta/utils/bsplusClientContext";
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
import { updateAllColors } from "@/seqta/ui/colors/Manager";
import {
@@ -642,16 +641,8 @@ export class ThemeManager {
let themeJsonUrl = themeContent.theme_json_url;
if (!themeJsonUrl) {
const { bsplus_token } = await browser.storage.local.get("bsplus_token");
const auth =
typeof bsplus_token === "string" && bsplus_token.length > 0
? { auth: true as const }
: undefined;
const downloadData = (await this.fetchFromUrl(
await withBsplusApiQuery(
`${this.THEME_API_BASE}/custom-themes/${encodeURIComponent(themeContent.id)}/download`,
),
auth,
`${this.THEME_API_BASE}/custom-themes/${encodeURIComponent(themeContent.id)}/download`,
)) as { success?: boolean; data?: { theme_json_url: string } };
if (!downloadData?.success || !downloadData?.data?.theme_json_url) {
throw new Error("Failed to get community theme download URL");
@@ -701,16 +692,8 @@ export class ThemeManager {
let themeData: ThemeContent;
try {
const { bsplus_token } = await browser.storage.local.get("bsplus_token");
const auth =
typeof bsplus_token === "string" && bsplus_token.length > 0
? { auth: true as const }
: undefined;
const downloadData = (await this.fetchFromUrl(
await withBsplusApiQuery(
`${this.THEME_API_BASE}/themes/${encodeURIComponent(themeContent.id)}/download`,
),
auth,
`${this.THEME_API_BASE}/themes/${encodeURIComponent(themeContent.id)}/download`,
)) as { success?: boolean; data?: { theme_json_url: string } };
if (!downloadData?.success || !downloadData?.data?.theme_json_url) {
throw new Error("Failed to get theme download URL");
+2 -16
View File
@@ -14,11 +14,7 @@ import { createPluginAPI } from "./createAPI";
import browser from "@/lib/browser";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
import { verboseInfo } from "@/utils/verboseLog";
import { isRemotePluginStartAllowed } from "@/seqta/utils/remoteConfig/runtime";
import {
isRemoteRouteEnhancementsStripped,
ROUTE_STRIP_KEEP_PLUGINS,
} from "@/seqta/utils/remoteConfig/routeGate";
import { isFeatureDisabled } from "@/seqta/utils/remoteStatus";
import { isPluginAllowedInPerformanceMode } from "@/seqta/utils/performanceMode";
interface PluginSettingsStorage {
@@ -194,10 +190,7 @@ export class PluginManager {
if (settingsState.onoff === false || !isPluginAllowedInPerformanceMode(plugin.id)) {
return false;
}
if (!isRemotePluginStartAllowed(plugin.id)) {
return false;
}
if (isRemoteRouteEnhancementsStripped() && !ROUTE_STRIP_KEEP_PLUGINS.has(plugin.id)) {
if (isFeatureDisabled(`plugin.${plugin.id}`)) {
return false;
}
if (!plugin.disableToggle) return true;
@@ -277,13 +270,6 @@ export class PluginManager {
Array.from(this.plugins.keys()).forEach((id) => this.stopPlugin(id));
}
public async stopPluginsExcept(keepIds: ReadonlySet<string>): Promise<void> {
const stops = Array.from(this.plugins.keys())
.filter((id) => !keepIds.has(id))
.map((id) => this.stopPlugin(id));
await Promise.allSettled(stops);
}
public getPlugin(pluginId: string): Plugin | undefined {
return this.plugins.get(pluginId);
}
+19 -19
View File
@@ -30,6 +30,7 @@ import {
updateEngageHomeMenuActive,
} from "@/seqta/utils/loaders/LoadEngageHomePage";
import { loadHomePage } from "@/seqta/utils/loaders/LoadHomePage";
import { isFeatureDisabled } from "@/seqta/utils/remoteStatus";
import { runStartupPopupQueue } from "@/seqta/utils/openers/StartupPopupQueue";
import { OpenCoursesAssessmentsFixPopup } from "@/seqta/utils/openers/OpenCoursesAssessmentsFixPopup";
@@ -197,8 +198,16 @@ function SortMessagePageItems() {
async function LoadPageElements(): Promise<void> {
await AddBetterSEQTAElements();
const { syncRouteEnhancementChrome } = await import("@/seqta/utils/remoteConfig/routeGate");
await syncRouteEnhancementChrome();
if (!isFeatureDisabled("ui.sidebar.styled")) {
void import("@/seqta/ui/sidebar/applyNativeSidebar").then((mod) => {
void mod.applyNativeSidebar();
});
}
if (!isFeatureDisabled("ui.titlebar.custom")) {
void import("@/seqta/ui/titlebar/mountCustomTitleBar").then((mod) => {
void mod.mountCustomTitleBar();
});
}
const sublink: string | undefined = getEngageRoutePage();
if (isSeqtaEngageExperience() && !engageHashListenerAttached) {
@@ -716,17 +725,16 @@ export function init() {
// Learn only: apply sidebar CSS vars early; Engage keeps its native React menu.
if (!onLogin && !isSeqtaEngageExperience()) {
document.documentElement.classList.add("bsplus-custom-title-pending");
void import("@/seqta/utils/remoteConfig/routeGate").then(async (gate) => {
if (gate.isRemoteRouteEnhancementsStripped()) return;
if (gate.remoteChromeGateAllowed("ui.sidebar.styled")) {
const mod = await import("@/seqta/ui/sidebar/applyNativeSidebar");
if (!isFeatureDisabled("ui.sidebar.styled")) {
void import("@/seqta/ui/sidebar/applyNativeSidebar").then((mod) => {
mod.prepareNativeSidebarEarly();
}
if (gate.remoteChromeGateAllowed("ui.titlebar.custom")) {
const mod = await import("@/seqta/ui/titlebar/mountCustomTitleBar");
});
}
if (!isFeatureDisabled("ui.titlebar.custom")) {
void import("@/seqta/ui/titlebar/mountCustomTitleBar").then((mod) => {
mod.prepareCustomTitleBarEarly();
}
});
});
}
} else {
document.documentElement.classList.remove("bsplus-custom-title-pending");
}
@@ -751,15 +759,7 @@ export function init() {
});
let hashColorTimer: ReturnType<typeof setTimeout> | null = null;
let routeChromeTimer: ReturnType<typeof setTimeout> | null = null;
window.addEventListener("hashchange", () => {
if (routeChromeTimer) clearTimeout(routeChromeTimer);
routeChromeTimer = setTimeout(() => {
routeChromeTimer = null;
void import("@/seqta/utils/remoteConfig/routeGate").then((m) =>
m.syncRouteEnhancementChrome(),
);
}, 120);
if (!settingsState.adaptiveThemeColour) return;
if (hashColorTimer) clearTimeout(hashColorTimer);
hashColorTimer = setTimeout(
+6 -18
View File
@@ -9,14 +9,8 @@ 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";
import { getRemoteStatus, loadRemoteStatus, refreshRemoteStatus } from "@/seqta/utils/remoteStatus";
import { ensureSettingsAccess } from "@/seqta/utils/ensureSettingsAccess";
import { recoverFromStaleDevModuleGraph } from "@/seqta/devModuleGraphRecovery";
function registerFetchSeqtaAppLinkListener() {
@@ -101,15 +95,10 @@ async function init() {
await delay(5);
}
await hydrateRemoteConfigFromStorage();
notifyRemoteConfigPageContext(location.hostname);
installRemoteConfigStorageListener(() => {
location.reload();
});
await loadRemoteStatus();
void refreshRemoteStatus();
const bsplusEnabled = isEffectiveBsplusEnabled();
if (bsplusEnabled) {
if (settingsState.onoff !== false && !getRemoteStatus().off) {
await main();
const { init: Monofile } = await import("@/plugins/monofile");
@@ -120,8 +109,7 @@ async function init() {
await initializePlugins();
}
} else {
await ensureKilledModeSettingsAccess();
void runStartupPopupQueue();
await ensureSettingsAccess();
}
if (settingsState.devMode) {
+4 -5
View File
@@ -26,8 +26,7 @@ import {
refreshTitlebarFounderBadge,
} from "@/seqta/ui/founderBadge/mountTitlebarFounderBadge";
import { isPerformanceMode } from "@/seqta/utils/performanceMode";
import { checkRemoteFeature } from "@/seqta/utils/remoteConfig/runtime";
import { remoteChromeGateAllowed } from "@/seqta/utils/remoteConfig/routeGate";
import { isFeatureDisabled } from "@/seqta/utils/remoteStatus";
import { rafThrottle } from "@/seqta/utils/rafThrottle";
import {
installSidebarDrillReturn,
@@ -65,10 +64,10 @@ export async function AddBetterSEQTAElements() {
const menu = document.getElementById("menu")!;
const menuList = menu.firstChild as HTMLElement;
if (!checkRemoteFeature("page.home").hide) {
if (!isFeatureDisabled("page.home")) {
createHomeButton(fragment);
}
if (!checkRemoteFeature("page.news").hide) {
if (!isFeatureDisabled("page.news")) {
createNewsButton(fragment, menu);
}
@@ -88,7 +87,7 @@ export async function AddBetterSEQTAElements() {
setupEventListeners();
await addDarkLightToggle();
customizeMenuToggle();
if (remoteChromeGateAllowed("ui.sidebar.styled")) {
if (!isFeatureDisabled("ui.sidebar.styled")) {
maybeSetupSidebarAccessibility();
}
}
@@ -9,7 +9,7 @@ import {
type BadgeItem,
} from "@/seqta/utils/founderBadges";
import { openFounderBadgeModal } from "@/seqta/ui/founderBadge/openFounderBadgeModal";
import { remoteChromeGateAllowed } from "@/seqta/utils/remoteConfig/routeGate";
import { isFeatureDisabled } from "@/seqta/utils/remoteStatus";
let subscribed = false;
let refreshPending = false;
@@ -82,7 +82,7 @@ async function syncTitlebarFounderBadge(): Promise<void> {
if (
settingsState.showTitlebarFounderBadge === false ||
!cloudAuth.state.isLoggedIn ||
!remoteChromeGateAllowed("ui.titlebar.founderBadge")
isFeatureDisabled("ui.titlebar.founderBadge")
) {
return;
}
+2 -6
View File
@@ -8,13 +8,10 @@ import { resolveExtensionAssetUrl } from "@/lib/extensionAssetUrl";
import { animate, stagger } from "motion";
import { verboseInfo } from "@/utils/verboseLog";
import { toNewsArticles, type NewsPayload } from "@/seqta/utils/newsFeed";
import {
applyPageFeatureGateEarly,
injectPageFeatureBanner,
} from "@/seqta/utils/remoteConfig/runtime";
import { isFeatureDisabled } from "@/seqta/utils/remoteStatus";
export async function SendNewsPage() {
if (applyPageFeatureGateEarly("news")) return;
if (isFeatureDisabled("page.news")) return;
verboseInfo("[BetterSEQTA+] Started Loading News Page");
document.title = "News ― SEQTA Learn";
@@ -57,7 +54,6 @@ export async function SendNewsPage() {
</div>`);
main.append(html.firstChild!);
injectPageFeatureBanner("news", "#news-container");
void import("@/seqta/ui/titlebar/mountCustomTitleBar").then((mod) => {
mod.setCustomTitleBarText("News");
-46
View File
@@ -1,46 +0,0 @@
import browser from "@/lib/browser";
import { getOrCreateInstallId } from "@/seqta/utils/feedback/installId";
function manifestVersion(): string {
try {
return browser.runtime.getManifest().version;
} catch {
return "0";
}
}
function updateChannel(): string {
if (typeof __UPDATE_CHANNEL__ !== "undefined") {
if (__UPDATE_CHANNEL__ === "nightly") return "nightly";
if (__UPDATE_CHANNEL__ === "stable") return "stable";
}
return "unknown";
}
export function bsplusExtensionPayload(): {
version: string;
channel: string;
browser: "chrome";
} {
return { version: manifestVersion(), channel: updateChannel(), browser: "chrome" };
}
/** Shared query params for betterseqta.org theme + remote-config requests. */
export async function bsplusApiQueryParams(): Promise<URLSearchParams> {
const params = new URLSearchParams({
extensionVersion: manifestVersion(),
channel: updateChannel(),
installId: await getOrCreateInstallId(),
});
const { bsplus_user } = await browser.storage.local.get("bsplus_user");
if (bsplus_user && typeof bsplus_user === "object" && "id" in bsplus_user) {
const id = (bsplus_user as { id: unknown }).id;
if (typeof id === "string" && id) params.set("userId", id);
}
return params;
}
export async function withBsplusApiQuery(url: string): Promise<string> {
const qs = (await bsplusApiQueryParams()).toString();
return qs ? (url.includes("?") ? `${url}&${qs}` : `${url}?${qs}`) : url;
}
+1 -29
View File
@@ -1,20 +1,6 @@
import browser from "@/lib/browser";
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_FETCHED_AT_KEY,
BSPLUS_REMOTE_CONFIG_LAST_HOSTNAME_KEY,
BSPLUS_REMOTE_CONFIG_SNAPSHOT_KEY,
BSPLUS_REMOTE_LAST_PRIMARY_OK_KEY,
BSPLUS_REMOTE_THEME_BEFORE_V1_KEY,
BSPLUS_REMOTE_THEME_STATE_V1_KEY,
BSPLUS_REMOTE_THEME_USER_OFF_KEY,
} from "@/seqta/utils/remoteConfig/storageKeys";
/** Matches the contract in docs/CLOUD_SETTINGS_SYNC_SERVER.md */
export const CLOUD_SETTINGS_SYNC_SCHEMA_VERSION = 1;
@@ -58,18 +44,7 @@ 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_REMOTE_THEME_BEFORE_V1_KEY,
BSPLUS_REMOTE_THEME_STATE_V1_KEY,
BSPLUS_REMOTE_THEME_USER_OFF_KEY,
"bsplus_remote_status",
BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY,
] as const;
@@ -94,9 +69,6 @@ const CLIENT_ONLY_CLOUD_KEYS_EXACT = [
"bsplus_lastCloudPoll",
BSPLUS_PENDING_THEME_ENSURE_AFTER_CLOUD_KEY,
BSPLUS_CALENDAR_SYNC_IN_PROGRESS_KEY,
"bsplus_remote_theme_before_v1",
"bsplus_remote_theme_state_v1",
"bsplus_remote_theme_user_off",
] as const;
/** After restoring from cloud, keep local session so the user stays signed in. */
+58
View File
@@ -0,0 +1,58 @@
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";
export async function ensureSettingsAccess(): 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" 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>
</button>
`).firstChild!,
);
setupSettingsButton();
});
}
+2 -2
View File
@@ -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,
+1 -6
View File
@@ -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 {
+2 -7
View File
@@ -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() {
</div>`);
homeContainer.appendChild(skeletonStructure.firstChild!);
injectPageFeatureBanner("home", "#home-container");
injectPageFeatureBanner("home", "#home-container");
if (settingsState.animations) {
animate(
@@ -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<ThemeOfTheMonthEntry | null> {
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),
});
+1 -28
View File
@@ -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));
@@ -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 */ `<div class="whatsnewHeader"><h1>${title}</h1>${subtitle ? `<p>${subtitle}</p>` : ""}</div>`,
).firstChild as HTMLElement;
const buttons = campaign.buttons?.length
? campaign.buttons
: [{ id: "dismiss", label: "Dismiss", action: "dismiss" as const }];
const actionsHtml = buttons
.map(
(btn, i) =>
`<button type="button" id="bsplus-campaign-${campaign.id}-${btn.id}" class="bsplus-cal-btn ${i === 0 ? "bsplus-cal-btn--primary" : "bsplus-cal-btn--ghost"}">${btn.label}</button>`,
)
.join("");
const text = stringToHTML(/* html */ `
<div class="whatsnewTextContainer bsplus-founder-badge-body" style="overflow-y: auto;">
<div class="bsplus-campaign-body"></div>
<div class="bsplus-founder-badge-actions">${actionsHtml}</div>
</div>
`).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 */ `<div class="whatsnewImgContainer"></div>`)
.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?.();
},
});
}
@@ -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.",
],
},
+8 -25
View File
@@ -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<void> {
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<void>
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);
}
-148
View File
@@ -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>): 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"),
);
});
});
-112
View File
@@ -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<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;
}
@@ -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");
});
});
-162
View File
@@ -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<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;
}
function normalizeRemoteTheme(raw: unknown): RemoteThemeDirective | null {
if (!raw || typeof raw !== "object") return null;
const r = raw as Record<string, unknown>;
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<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"])
: [],
remoteTheme: normalizeRemoteTheme(data.remoteTheme),
};
}
/** 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 ?? [],
remoteTheme: files.remoteTheme ?? null,
});
}
-271
View File
@@ -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<string, unknown>;
selectedTheme: string;
};
type ActiveThemeState = {
directiveKey: string;
layerIds: string[];
mode: "optional" | "forced";
applicationMode: "replace" | "overlay";
};
type RemotePackage = {
theme?: Record<string, unknown>;
overlayLayers?: Record<string, unknown>[];
downloadUrl?: string;
};
let reconcileChain: Promise<void> = 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<T>(key: string): Promise<T | null> {
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<BeforeSnapshot | null> {
const b = await readJson<BeforeSnapshot>(BSPLUS_REMOTE_THEME_BEFORE_V1_KEY);
if (!b?.directiveKey || !b.storage) return null;
return b;
}
async function loadActiveState(): Promise<ActiveThemeState | null> {
return readJson<ActiveThemeState>(BSPLUS_REMOTE_THEME_STATE_V1_KEY);
}
async function loadUserOffKey(): Promise<string | null> {
const raw = await readJson<{ directiveKey?: string }>(BSPLUS_REMOTE_THEME_USER_OFF_KEY);
return typeof raw?.directiveKey === "string" ? raw.directiveKey : null;
}
async function clearRemoteThemeLocalState(): Promise<void> {
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<void> {
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<void> {
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<void> {
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<RemotePackage | null> {
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<Record<string, unknown> | null> {
try {
const res = (await browser.runtime.sendMessage({
type: "fetchRemoteThemePackageUrl",
url,
})) as { theme?: Record<string, unknown> };
return res?.theme && typeof res.theme === "object" ? res.theme : null;
} catch {
return null;
}
}
async function resolveLayers(pkg: RemotePackage): Promise<Record<string, unknown>[]> {
if (Array.isArray(pkg.overlayLayers) && pkg.overlayLayers.length) {
return pkg.overlayLayers.filter((l) => l && typeof l === "object") as Record<string, unknown>[];
}
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<string, unknown>[] }).overlayLayers;
}
return [dl];
}
async function saveActiveState(state: ActiveThemeState): Promise<void> {
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<void> {
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<typeof tm.installTheme>[0], { fromStore: false });
}
if (settingsState.selectedTheme) await tm.setTheme(settingsState.selectedTheme, false);
const css: string[] = [];
const images = new Map<string, { variableName: string; blob: Blob }>();
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<typeof tm.installTheme>[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<void> {
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<void> {
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));
}
-45
View File
@@ -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<void> {
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();
}
-290
View File
@@ -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<string, string> = {};
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<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
}
}
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) ?? {},
);
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<void> {
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 */ `<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" 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>
</button>
`).firstChild!,
);
setupSettingsButton();
});
}
@@ -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";
-70
View File
@@ -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<string, RemoteFeatureGate>;
campaigns: RemoteCampaign[];
remoteTheme?: RemoteThemeDirective | null;
};
export type CampaignSeenRecord = Record<string, { seenAt: string; ack?: boolean }>;
+21
View File
@@ -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"] });
});
});
+45
View File
@@ -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<string, unknown>;
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<RemoteStatus> {
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<void> {
status = await readRemoteStatus();
}
export async function refreshRemoteStatus(): Promise<void> {
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) });
}
+7 -45
View File
@@ -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);