diff --git a/src/background.ts b/src/background.ts index 199e3253..bfcf8e38 100644 --- a/src/background.ts +++ b/src/background.ts @@ -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 = {}; if (token) headers["Authorization"] = `Bearer ${token}`; @@ -155,7 +139,7 @@ function handleFetchThemeDetails(request: BackgroundRequest, sendResponse: Messa const token = await getAccessTokenFromStorage(); const headers: Record = {}; 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 = { 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 = { ...customThemesHandlers, searchThemeStockPhotos: handleSearchThemeStockPhotos, reloadTabs: () => reloadSeqtaPages(), - setDevApiBase: handleSetDevApiBase, extensionPages: (req) => { browser.tabs.query({}).then((tabs) => { for (const tab of tabs) { diff --git a/src/background/customThemesHandlers.ts b/src/background/customThemesHandlers.ts index da1c3d19..c51ef346 100644 --- a/src/background/customThemesHandlers.ts +++ b/src/background/customThemesHandlers.ts @@ -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; }): Record, sendResponse: MessageSender) => boolean> { async function readCustomThemesResponse(r: Response): Promise> { @@ -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}` }, diff --git a/src/config/apiBase.ts b/src/config/apiBase.ts new file mode 100644 index 00000000..c36f999d --- /dev/null +++ b/src/config/apiBase.ts @@ -0,0 +1 @@ +export const API_BASE = "https://betterseqta.org"; diff --git a/src/interface/index.ts b/src/interface/index.ts index d2faaba4..fc27c41d 100644 --- a/src/interface/index.ts +++ b/src/interface/index.ts @@ -34,8 +34,6 @@ if (!mountPoint) { await initializeSettingsState(); await loadRemoteStatus(); initVerboseLogging(); - const { syncApiBaseToBackground } = await import("@/seqta/utils/DevApiBase"); - syncApiBaseToBackground(); renderSvelte(Settings, mountPoint, { standalone: true }); })(); } diff --git a/src/interface/pages/settings/sections/advanced.svelte b/src/interface/pages/settings/sections/advanced.svelte index f316e63d..2de0e370 100644 --- a/src/interface/pages/settings/sections/advanced.svelte +++ b/src/interface/pages/settings/sections/advanced.svelte @@ -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(getStoredOverride() ?? ""); - let devApiBaseActive = $state(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 @@