Remove API base override and inline onclick allowance

The API base is a fixed constant; fetchFromUrl only attaches the bearer token to betterseqta.org and accounts.betterseqta.org.
This commit is contained in:
SethBurkart123 committed 2026-11-03 17:40:52 +11:00
1 parent dc5c16ff1a
commit 175df9fb47
22 files changed
+40 -257

No files matched your search

+11 -44
View File
@@ -19,29 +19,13 @@ import {
registerOutlookCalendarMessageHandlers,
type CalendarMessageHandlerMap,
} from "./background/calendarBackground";
import { API_BASE } from "./config/apiBase";
import { createCustomThemesHandlers } from "./background/customThemesHandlers";
import { DEFAULT_BACKGROUND_PENDING_KEY } from "@/seqta/ui/defaultBackgroundKey";
import { handleSearchThemeStockPhotos } from "./background/searchThemeStockPhotos";
import { initTimetableClassmatesBackgroundSync } from "./background/timetableClassmatesSync";
import { runStorageMigrations } from "./background/storageMigrations";
/**
* Session-only dev-mode override of the content API base.
*
* Stored in a module-level variable (not `chrome.storage`) so it is wiped
* automatically when the browser/service-worker process restarts. Content
* scripts re-sync this on every page load via `setDevApiBase` so the value
* survives transient service-worker terminations within the same browser
* session.
*/
const DEFAULT_API_BASE = "https://betterseqta.org";
let DEV_API_BASE: string | null = null;
function apiBase(): string {
// Extension dev builds always hit production (see DevApiBase.ts).
if (import.meta.env.DEV) return DEFAULT_API_BASE;
return DEV_API_BASE ?? DEFAULT_API_BASE;
}
function reloadSeqtaPages() {
const result = browser.tabs.query({});
function open(tabs: chrome.tabs.Tab[]) {
@@ -106,7 +90,7 @@ function normalizeFetchThemesResponse(json: unknown): {
function handleFetchThemes(_request: unknown, sendResponse: MessageSender): boolean {
void (async () => {
const token = await getAccessTokenFromStorage();
const apiUrl = `${apiBase()}/api/themes?type=betterseqta&limit=100&nocache=${Date.now()}`;
const apiUrl = `${API_BASE}/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}`;
@@ -155,7 +139,7 @@ function handleFetchThemeDetails(request: BackgroundRequest, sendResponse: Messa
const token = await getAccessTokenFromStorage();
const headers: Record<string, string> = {};
if (token) headers["Authorization"] = `Bearer ${token}`;
fetch(`${apiBase()}/api/themes/${themeId}`, { cache: "no-store", headers })
fetch(`${API_BASE}/api/themes/${themeId}`, { cache: "no-store", headers })
.then((r) => r.json())
.then(sendResponse)
.catch((err) => {
@@ -182,6 +166,8 @@ function isTrustedSender(sender?: chrome.runtime.MessageSender): boolean {
return false;
}
const AUTH_FETCH_ORIGINS = [API_BASE, "https://accounts.betterseqta.org"];
function handleFetchFromUrl(
request: BackgroundRequest,
sendResponse: MessageSender,
@@ -200,6 +186,10 @@ function handleFetchFromUrl(
sendResponse({ error: "URL not allowed" });
return false;
}
if (request.auth === true && !AUTH_FETCH_ORIGINS.includes(new URL(url).origin)) {
sendResponse({ error: "URL not allowed" });
return false;
}
void (async () => {
try {
const headers: Record<string, string> = { Accept: "application/json" };
@@ -491,7 +481,7 @@ function handleCloudFavorite(request: BackgroundRequest, sendResponse: MessageSe
return;
}
const isFavorite = action === "favorite";
fetch(`${apiBase()}/api/themes/${themeId}/favorite`, {
fetch(`${API_BASE}/api/themes/${themeId}/favorite`, {
method: isFavorite ? "POST" : "DELETE",
headers: { Authorization: `Bearer ${token}` },
})
@@ -523,35 +513,12 @@ function isSeqtaOrigin(origin: string): boolean {
}
}
function handleSetDevApiBase(
request: BackgroundRequest,
_sendResponse: MessageSender,
sender?: chrome.runtime.MessageSender,
): boolean {
if (!isTrustedSender(sender)) return false;
if (import.meta.env.DEV) {
DEV_API_BASE = null;
return false;
}
const url = typeof request?.url === "string" ? request.url.trim() : null;
if (url && /^https?:\/\//.test(url)) {
DEV_API_BASE = url.replace(/\/$/, "");
} else {
DEV_API_BASE = null;
}
return false;
}
const customThemesHandlers = createCustomThemesHandlers({
apiBase,
getAccessTokenFromStorage,
});
const customThemesHandlers = createCustomThemesHandlers({ getAccessTokenFromStorage });
const MESSAGE_HANDLERS: Record<string, MessageHandler> = {
...customThemesHandlers,
searchThemeStockPhotos: handleSearchThemeStockPhotos,
reloadTabs: () => reloadSeqtaPages(),
setDevApiBase: handleSetDevApiBase,
extensionPages: (req) => {
browser.tabs.query({}).then((tabs) => {
for (const tab of tabs) {
+3 -3
View File
@@ -1,3 +1,4 @@
import { API_BASE } from "@/config/apiBase";
import { normalizeCustomThemeApiResponse } from "@/seqta/utils/customThemes/parseApiEnvelope";
import { base64ToBlob } from "@/seqta/utils/base64";
@@ -32,7 +33,6 @@ function buildFormDataFromPayload(payload: UploadPayload): FormData {
}
export function createCustomThemesHandlers(deps: {
apiBase: () => string;
getAccessTokenFromStorage: () => Promise<string | null>;
}): Record<string, (request: Record<string, unknown>, sendResponse: MessageSender) => boolean> {
async function readCustomThemesResponse(r: Response): Promise<Record<string, unknown>> {
@@ -66,7 +66,7 @@ export function createCustomThemesHandlers(deps: {
}
headers.Authorization = `Bearer ${token}`;
}
const url = `${deps.apiBase()}${path}`;
const url = `${API_BASE}${path}`;
const r = await fetch(url, {
...init,
headers,
@@ -84,7 +84,7 @@ export function createCustomThemesHandlers(deps: {
return { success: false, error: "Not authenticated", httpStatus: 401 };
}
const form = buildFormDataFromPayload(payload);
const url = `${deps.apiBase()}${path}`;
const url = `${API_BASE}${path}`;
const r = await fetch(url, {
method: "POST",
headers: { Authorization: `Bearer ${token}` },
+1
View File
@@ -0,0 +1 @@
export const API_BASE = "https://betterseqta.org";
-2
View File
@@ -34,8 +34,6 @@ if (!mountPoint) {
await initializeSettingsState();
await loadRemoteStatus();
initVerboseLogging();
const { syncApiBaseToBackground } = await import("@/seqta/utils/DevApiBase");
syncApiBaseToBackground();
renderSvelte(Settings, mountPoint, { standalone: true });
})();
}
@@ -7,37 +7,11 @@
import { showThemeOfTheMonthPopupNow } from "@/seqta/utils/openers/OpenThemeOfTheMonthPopup";
import { closeExtensionPopup } from "@/seqta/utils/closers/closeExtensionPopup";
import { getSnapshotForUpload } from "@/seqta/utils/cloudSettingsSync";
import { getStoredOverride, PRODUCTION_API_BASE, setApiBase } from "@/seqta/utils/DevApiBase";
const isExtensionDevBuild = import.meta.env.DEV;
import { matchesSearch, type SettingsSectionSharedProps } from "../shared";
let { searchQuery = "" }: SettingsSectionSharedProps = $props();
let devApiBaseInput = $state<string>(getStoredOverride() ?? "");
let devApiBaseActive = $state<string | null>(getStoredOverride());
function applyDevApiBase() {
const trimmed = devApiBaseInput.trim();
if (trimmed === "") {
setApiBase(null);
devApiBaseActive = null;
return;
}
if (!/^https?:\/\//.test(trimmed)) {
alert("Please enter a full URL starting with http:// or https://");
return;
}
setApiBase(trimmed);
devApiBaseActive = trimmed.replace(/\/$/, "");
}
function clearDevApiBase() {
devApiBaseInput = "";
setApiBase(null);
devApiBaseActive = null;
}
async function exportCloudSettingsJsonToFile() {
const payload = await getSnapshotForUpload();
const blob = new Blob([JSON.stringify(payload, null, 2)], {
@@ -189,43 +163,6 @@
<Button onClick={exportCloudSettingsJsonToFile} text="Export to file" />
</div>
</div>
<div class="flex flex-col gap-2 px-4 py-3">
<div class="flex justify-between items-start gap-3">
<div class="pr-4">
<h2 class="text-sm font-bold">API Base URL (session only)</h2>
{#if isExtensionDevBuild}
<p class="text-xs text-zinc-600 dark:text-zinc-300">
Extension dev builds always use production ({PRODUCTION_API_BASE}) for the theme store,
community submit, and related APIs. Build a release package to test a staging host override.
</p>
{:else}
<p class="text-xs text-zinc-600 dark:text-zinc-300">
Override the content API host for this browser session. Cleared on restart. Affects
themes, theme of the month, and other server-driven content.
</p>
{#if devApiBaseActive}
<p class="text-xs mt-1 text-amber-600 dark:text-amber-400">
Override active: <span class="font-mono">{devApiBaseActive}</span>
</p>
{/if}
{/if}
</div>
</div>
{#if !isExtensionDevBuild}
<div class="flex gap-2 items-center">
<input
type="text"
placeholder="https://betterseqta.org"
bind:value={devApiBaseInput}
class="flex-1 px-2 py-1 text-xs rounded-sm border bg-white dark:bg-zinc-800 border-zinc-300 dark:border-zinc-700 text-zinc-900 dark:text-zinc-100"
/>
<Button onClick={applyDevApiBase} text="Apply" />
{#if devApiBaseActive}
<Button onClick={clearDevApiBase} text="Clear" />
{/if}
</div>
{/if}
</div>
<div class="flex flex-col gap-2 px-4 py-3">
<div>
<h2 class="text-sm font-bold">GitHub latest version override</h2>
@@ -17,9 +17,6 @@ jest.mock("@/seqta/utils/listeners/SettingsState", () => ({
jest.mock("@/seqta/utils/performanceMode", () => ({
fullMotionEffectsEnabled: () => false,
}));
jest.mock("@/seqta/utils/DevApiBase", () => ({
getApiBase: () => "https://betterseqta.org",
}));
jest.mock("@/seqta/ui/colors/Manager", () => ({ updateAllColors: jest.fn() }));
jest.mock("@/seqta/ui/colors/customThemeAdaptiveBindings", () => ({}));
jest.mock("@/seqta/utils/patchThemeImagesPageContext", () => ({}));
+2 -5
View File
@@ -11,7 +11,7 @@ import { settingsState } from "@/seqta/utils/listeners/SettingsState";
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 { API_BASE } from "@/config/apiBase";
import { isAllowedFetchUrl } from "@/seqta/utils/allowedFetchUrl";
import { updateAllColors } from "@/seqta/ui/colors/Manager";
import {
@@ -544,10 +544,7 @@ export class ThemeManager {
}
}
/** Use a getter so dev-mode session-only base URL overrides take effect immediately. */
private get THEME_API_BASE(): string {
return `${getApiBase()}/api`;
}
private readonly THEME_API_BASE = `${API_BASE}/api`;
private readonly GITHUB_THEMES_BASE =
"https://raw.githubusercontent.com/BetterSEQTA/BetterSEQTA-Themes/main/store/themes";
-15
View File
@@ -1,15 +0,0 @@
import { PRODUCTION_API_BASE, resolveApiBase } from "./apiBasePolicy";
describe("resolveApiBase", () => {
it("uses production during extension dev builds", () => {
expect(resolveApiBase("development", "http://localhost:3000")).toBe(PRODUCTION_API_BASE);
expect(resolveApiBase("development", null)).toBe(PRODUCTION_API_BASE);
});
it("honors session override in production builds", () => {
expect(resolveApiBase("production", "https://staging.example.test")).toBe(
"https://staging.example.test",
);
expect(resolveApiBase("production", null)).toBe(PRODUCTION_API_BASE);
});
});
-76
View File
@@ -1,76 +0,0 @@
import browser from "@/lib/browser";
import { resolveApiBase } from "@/seqta/utils/apiBasePolicy";
export { PRODUCTION_API_BASE } from "@/seqta/utils/apiBasePolicy";
const KEY = "bsplus_dev_api_base";
function readSessionOverride(): string | null {
try {
if (typeof sessionStorage === "undefined") return null;
const v = sessionStorage.getItem(KEY);
if (v && /^https?:\/\//.test(v)) return v.replace(/\/$/, "");
} catch {
// sessionStorage may throw in some restricted contexts; fall back silently.
}
return null;
}
function currentBuildMode(): "development" | "production" {
return import.meta.env.DEV ? "development" : "production";
}
/**
* Returns the current content-API base URL.
*
* In production builds, Advanced settings may set a session-only override for server testing.
* In extension dev builds, overrides are ignored and production is always used.
*/
export function getApiBase(): string {
return resolveApiBase(currentBuildMode(), readSessionOverride());
}
/**
* Persist a session-scoped override and broadcast it to the background script
* so its `fetch` calls hit the same host.
*
* Pass `null` to clear the override. No-op in extension dev builds.
*/
export function setApiBase(url: string | null): void {
if (import.meta.env.DEV) {
try {
sessionStorage.removeItem(KEY);
} catch {
// ignore
}
void browser.runtime.sendMessage({ type: "setDevApiBase", url: null }).catch(() => {});
return;
}
try {
if (!url) {
sessionStorage.removeItem(KEY);
} else {
sessionStorage.setItem(KEY, url.replace(/\/$/, ""));
}
} catch {
// ignore
}
void browser.runtime.sendMessage({ type: "setDevApiBase", url: url || null }).catch(() => {});
}
/** Returns the override URL if one is currently active (production builds only). */
export function getStoredOverride(): string | null {
if (import.meta.env.DEV) return null;
return readSessionOverride();
}
/**
* Send the current session override to the background script.
* Call this early in page load so the background context stays in sync after
* service-worker restarts.
*/
export function syncApiBaseToBackground(): void {
const override = import.meta.env.DEV ? null : readSessionOverride();
void browser.runtime.sendMessage({ type: "setDevApiBase", url: override }).catch(() => {});
}
-14
View File
@@ -1,14 +0,0 @@
export const PRODUCTION_API_BASE = "https://betterseqta.org";
/**
* Resolves the content API host. Extension dev builds always use production
* so community theme submit and the theme store work against the live API.
*/
export function resolveApiBase(
buildMode: "development" | "production",
sessionOverride: string | null,
): string {
if (buildMode === "development") return PRODUCTION_API_BASE;
if (sessionOverride) return sessionOverride;
return PRODUCTION_API_BASE;
}
-1
View File
@@ -88,7 +88,6 @@ const OMIT_FROM_UPLOAD_EXACT = new Set<string>([
"devMode",
"devGhReleaseVersionOverride",
"devDelayLoadingScreen",
"bsplus_dev_api_base",
"bsplus_dev_accounts_base",
"bsplus_dev_oauth_client_id",
"bsplus_dev_oauth_client_secret",
-4
View File
@@ -1,7 +1,3 @@
jest.mock("@/seqta/utils/DevApiBase", () => ({
getApiBase: () => "https://example.test",
}));
import browser from "@/lib/browser";
import {
addPendingFeedbackId,
+2 -2
View File
@@ -1,5 +1,5 @@
import browser from "@/lib/browser";
import { getApiBase } from "@/seqta/utils/DevApiBase";
import { API_BASE } from "@/config/apiBase";
import { isExtensionSettingsOpen } from "@/seqta/utils/settingsPopupAnimation";
import { isSeqtaEngageExperience } from "@/seqta/utils/isSeqtaEngage";
import { settingsState } from "@/seqta/utils/listeners/SettingsState";
@@ -115,7 +115,7 @@ function channel(): FeedbackChannel {
async function apiFetch(path: string, init?: RequestInit): Promise<Response> {
try {
return await fetch(`${getApiBase()}${path}`, {
return await fetch(`${API_BASE}${path}`, {
...init,
headers: { Accept: "application/json", ...init?.headers },
});
+8 -3
View File
@@ -480,8 +480,8 @@ function makeLessonDiv(lesson: HomeTimetableLesson, num: number) {
if (type == "class") {
if (programmeID !== 0) {
lessonString += `
<div class="day-button clickable" style="right: 5px;" onclick="location.href='${buildAssessmentURL(programmeID, metaID)}'">${assessmentsicon}</div>
<div class="day-button clickable" style="right: 35px;" onclick="location.href='../#?page=/courses/${programmeID}:${metaID}'">${coursesicon}</div>
<div class="day-button clickable" style="right: 5px;" data-href="${buildAssessmentURL(programmeID, metaID)}">${assessmentsicon}</div>
<div class="day-button clickable" style="right: 35px;" data-href="../#?page=/courses/${programmeID}:${metaID}">${coursesicon}</div>
`;
}
@@ -489,7 +489,7 @@ function makeLessonDiv(lesson: HomeTimetableLesson, num: number) {
const assessmentString = assessments
.map(
(element: HomeLessonAssessmentLink) =>
`<p onclick="location.href = '${buildAssessmentURL(programmeID, metaID, element.id)}';">${element.title}</p>`,
`<p data-href="${buildAssessmentURL(programmeID, metaID, element.id)}">${element.title}</p>`,
)
.join("");
@@ -506,6 +506,11 @@ function makeLessonDiv(lesson: HomeTimetableLesson, num: number) {
lessonString += "</div>";
const element = stringToHTML(lessonString);
element.querySelectorAll<HTMLElement>("[data-href]").forEach((el) => {
el.addEventListener("click", () => {
location.href = el.dataset.href!;
});
});
setupFixedTooltips(element);
return element;
}
@@ -1,10 +1,6 @@
/**
* @jest-environment jsdom
*/
jest.mock("../DevApiBase", () => ({
getApiBase: () => "https://betterseqta.org",
}));
import {
getFallbackTermsOfService,
markTermsOfServiceAccepted,
@@ -1,6 +1,6 @@
import stringToHTML from "../stringToHTML";
import { settingsState } from "../listeners/SettingsState";
import { getApiBase } from "../DevApiBase";
import { API_BASE } from "@/config/apiBase";
import { closePopup, openPopup } from "./PopupManager";
import fallbackTerms from "@/exampletermsresponse.json";
import type { SettingsState } from "@/types/storage";
@@ -33,7 +33,7 @@ export function getFallbackTermsOfService(): LegalDocumentPayload {
/** Loads Terms of Service body from `GET /api/terms`. */
export async function fetchTermsOfService(): Promise<LegalDocumentPayload> {
try {
const res = await fetch(`${getApiBase()}/api/terms`, {
const res = await fetch(`${API_BASE}/api/terms`, {
cache: "no-store",
signal: AbortSignal.timeout(TERMS_FETCH_TIMEOUT_MS),
});
@@ -2,9 +2,6 @@
import { OpenThemeOfTheMonthPopup } from "./OpenThemeOfTheMonthPopup";
import { settingsState } from "../listeners/SettingsState";
jest.mock("../DevApiBase", () => ({
getApiBase: () => "https://example.test",
}));
jest.mock("./PopupManager", () => ({ closePopup: jest.fn() }));
jest.mock("../listeners/SettingsState", () => ({
settingsState: { animations: false },
@@ -2,7 +2,7 @@ import browser from "@/lib/browser";
import stringToHTML from "../stringToHTML";
import { settingsState } from "../listeners/SettingsState";
import { closePopup } from "./PopupManager";
import { getApiBase } from "../DevApiBase";
import { API_BASE } from "@/config/apiBase";
import { openThemeStoreWithHighlight } from "../openThemeStoreWithHighlight";
import type { Theme } from "@/interface/types/Theme";
import { buildModalHeroSlides, normalizeStoreTheme } from "@/interface/utils/themeStoreFlavours";
@@ -58,7 +58,7 @@ async function writeCachedThemeOfTheMonth(entry: ThemeOfTheMonthEntry): Promise<
*/
export async function fetchThemeOfTheMonth(): Promise<ThemeOfTheMonthEntry | null> {
try {
const res = await fetch(`${getApiBase()}/api/theme-of-the-month/current`, {
const res = await fetch(`${API_BASE}/api/theme-of-the-month/current`, {
cache: "no-store",
signal: AbortSignal.timeout(TOTM_FETCH_TIMEOUT_MS),
});
@@ -10,7 +10,6 @@ import {
OpenCoursesAssessmentsFixPopup,
shouldShowCoursesAssessmentsFixPopup,
} from "./OpenCoursesAssessmentsFixPopup";
import { syncApiBaseToBackground } from "../DevApiBase";
import { cloudAuth } from "../CloudAuth";
import {
fetchTermsOfService,
@@ -21,8 +20,6 @@ import {
type QueueStep = (goNext: () => void) => void;
export async function runStartupPopupQueue() {
syncApiBaseToBackground();
const steps: QueueStep[] = [];
if (settingsState.justupdated) {
@@ -1,10 +1,6 @@
import browser from "@/lib/browser";
import { fetchThemeOfTheMonth } from "./OpenThemeOfTheMonthPopup";
jest.mock("../DevApiBase", () => ({
getApiBase: () => "https://example.test",
}));
const CACHE_KEY = "bsplus_theme_of_the_month_cache";
const sampleEntry = {
+9 -3
View File
@@ -5,13 +5,19 @@
import stringToHTML from "./stringToHTML";
describe("stringToHTML", () => {
it("preserves inline onclick handlers used by lesson action buttons", () => {
it("strips inline onclick handlers and keeps data-href", () => {
const body = stringToHTML(
`<div class="day-button clickable" onclick="location.href='../#?page=/courses/123:456'">Go</div>`,
`<div class="day-button clickable" data-href="../#?page=/courses/123:456" onclick="location.href='x'">Go</div>`,
);
const el = body.firstElementChild as HTMLElement | null;
expect(el).not.toBeNull();
expect(el?.getAttribute("onclick")).toContain("location.href");
expect(el?.hasAttribute("onclick")).toBe(false);
expect(el?.dataset.href).toBe("../#?page=/courses/123:456");
});
it("strips javascript: URLs", () => {
const body = stringToHTML(`<a href="javascript:alert(1)">x</a>`);
expect(body.querySelector("a")?.getAttribute("href")).toBeNull();
});
});
-1
View File
@@ -4,7 +4,6 @@ export default function stringToHTML(str: string, styles = false) {
const parser = new DOMParser();
str = DOMPurify.sanitize(str, {
ADD_ATTR: ["onclick"],
ALLOWED_URI_REGEXP:
/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|chrome-extension):|\/|#|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i,
});