diff --git a/src/background.ts b/src/background.ts index fab49f4a..00adf091 100644 --- a/src/background.ts +++ b/src/background.ts @@ -27,6 +27,7 @@ import { } from "./background/remoteConfig"; import { BSPLUS_INSTALL_REGISTERED_AT_KEY } from "@/seqta/utils/remoteConfig/storageKeys"; import { handleSearchThemeStockPhotos } from "./background/searchThemeStockPhotos"; +import { bsplusApiQueryParams, withBsplusApiQuery } from "@/seqta/utils/bsplusClientContext"; import { initTimetableClassmatesBackgroundSync } from "./background/timetableClassmatesSync"; /** @@ -105,7 +106,11 @@ function normalizeFetchThemesResponse(json: unknown): { function handleFetchThemes(request: any, sendResponse: MessageSender): boolean { void (async () => { const token = await getAccessTokenFromStorage(); - const apiUrl = `${apiBase()}/api/themes?type=betterseqta&limit=100&nocache=${Date.now()}`; + 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 githubUrl = `https://raw.githubusercontent.com/BetterSEQTA/BetterSEQTA-Themes/main/store/themes.json?nocache=${Date.now()}`; const headers: Record = {}; if (token) headers["Authorization"] = `Bearer ${token}`; @@ -151,7 +156,10 @@ function handleFetchThemeDetails(request: any, sendResponse: MessageSender): boo const token = await getAccessTokenFromStorage(); const headers: Record = {}; if (token) headers["Authorization"] = `Bearer ${token}`; - fetch(`${apiBase()}/api/themes/${themeId}`, { cache: "no-store", headers }) + const detailUrl = await withBsplusApiQuery( + `${apiBase()}/api/themes/${encodeURIComponent(themeId)}`, + ); + fetch(detailUrl, { cache: "no-store", headers }) .then((r) => r.json()) .then(sendResponse) .catch((err) => { diff --git a/src/background/customThemesHandlers.ts b/src/background/customThemesHandlers.ts index 057bd2ea..d441ebea 100644 --- a/src/background/customThemesHandlers.ts +++ b/src/background/customThemesHandlers.ts @@ -1,4 +1,5 @@ import { normalizeCustomThemeApiResponse } from "@/seqta/utils/customThemes/parseApiEnvelope"; +import { bsplusApiQueryParams } from "@/seqta/utils/bsplusClientContext"; type MessageSender = { (response?: unknown): void }; @@ -115,6 +116,7 @@ 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 search = request.search?.trim(); const path = search @@ -139,6 +141,7 @@ 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), diff --git a/src/background/remoteConfig.ts b/src/background/remoteConfig.ts index 728a19d1..59801663 100644 --- a/src/background/remoteConfig.ts +++ b/src/background/remoteConfig.ts @@ -1,4 +1,9 @@ import browser from "webextension-polyfill"; +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 { @@ -21,19 +26,28 @@ import type { RemoteConfigSnapshot } from "@/seqta/utils/remoteConfig/types"; type MessageSender = { (response?: unknown): void }; -function extensionChannel(): string { - if (typeof __UPDATE_CHANNEL__ !== "undefined") { - if (__UPDATE_CHANNEL__ === "nightly") return "nightly"; - if (__UPDATE_CHANNEL__ === "stable") return "stable"; - } - return "unknown"; -} +const ACCOUNTS_BASE = "https://accounts.betterseqta.org"; -function extensionVersion(): string { +async function linkCloudInstall(token: string, installId: string): Promise { try { - return browser.runtime.getManifest().version; - } catch { - return "0"; + 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, + extension: bsplusExtensionPayload(), + 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); } } @@ -94,6 +108,8 @@ async function registerInstall( "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) @@ -103,11 +119,7 @@ async function registerInstall( const body = { installId, - extension: { - version: extensionVersion(), - channel: extensionChannel(), - browser: "chrome", - }, + extension: bsplusExtensionPayload(), userId, lastSeenAt: new Date().toISOString(), ...(hostname ? { hostname } : {}), @@ -118,9 +130,7 @@ async function registerInstall( Accept: "application/json", "Content-Type": "application/json", }; - if (typeof bsplus_token === "string" && bsplus_token.length > 0) { - headers.Authorization = `Bearer ${bsplus_token}`; - } + if (token) headers.Authorization = `Bearer ${token}`; const r = await fetch(`${apiBase}/api/bsplus/installs/register`, { method: "POST", headers, @@ -135,6 +145,7 @@ async function registerInstall( } catch (e) { console.warn("[BetterSEQTA+] install register failed:", e); } + if (token) void linkCloudInstall(token, installId); } export async function refreshRemoteConfig(apiBase: () => string): Promise<{ @@ -143,13 +154,8 @@ export async function refreshRemoteConfig(apiBase: () => string): Promise<{ primaryOk: boolean; }> { const base = apiBase(); - const installId = await getOrCreateInstallId(); const hostname = await readLastHostname(); - const params = new URLSearchParams({ - installId, - extensionVersion: extensionVersion(), - channel: extensionChannel(), - }); + const params = await bsplusApiQueryParams(); if (hostname) params.set("hostname", hostname); const stored = await browser.storage.local.get([ @@ -237,6 +243,12 @@ export function initRemoteConfigBackground(apiBase: () => string): void { } 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()); + } + } } })(); } @@ -295,11 +307,7 @@ export function createRemoteConfigHandlers(apiBase: () => string): Record< void (async () => { try { const hostname = await readLastHostname(); - const params = new URLSearchParams({ - installId: await getOrCreateInstallId(), - extensionVersion: extensionVersion(), - channel: extensionChannel(), - }); + const params = await bsplusApiQueryParams(); if (hostname) params.set("hostname", hostname); const base = apiBase(); const url = `${base}/api/bsplus/remote-theme-packages/${encodeURIComponent(packageId)}?${params}`; diff --git a/src/plugins/built-in/themes/theme-manager.cloud.test.ts b/src/plugins/built-in/themes/theme-manager.cloud.test.ts index 59bebdf4..0c6fa7e8 100644 --- a/src/plugins/built-in/themes/theme-manager.cloud.test.ts +++ b/src/plugins/built-in/themes/theme-manager.cloud.test.ts @@ -52,7 +52,9 @@ describe("cloud theme restoration", () => { (browser.runtime.sendMessage as jest.Mock).mockImplementation( async ({ url }) => { if ( - url === `https://betterseqta.org/api/${catalog}/catalog-id/download` + typeof url === "string" && + url.includes(`/api/${catalog}/catalog-id/download`) && + url.includes("extensionVersion=") ) { return { data: { success: true, data: { theme_json_url: jsonUrl } }, diff --git a/src/plugins/built-in/themes/theme-manager.ts b/src/plugins/built-in/themes/theme-manager.ts index a47d2b7d..971eaf28 100644 --- a/src/plugins/built-in/themes/theme-manager.ts +++ b/src/plugins/built-in/themes/theme-manager.ts @@ -12,6 +12,7 @@ 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 { @@ -679,8 +680,16 @@ 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( - `${this.THEME_API_BASE}/custom-themes/${themeContent.id}/download`, + await withBsplusApiQuery( + `${this.THEME_API_BASE}/custom-themes/${encodeURIComponent(themeContent.id)}/download`, + ), + auth, )) 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"); @@ -730,8 +739,16 @@ 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( - `${this.THEME_API_BASE}/themes/${themeContent.id}/download`, + await withBsplusApiQuery( + `${this.THEME_API_BASE}/themes/${encodeURIComponent(themeContent.id)}/download`, + ), + auth, )) 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"); diff --git a/src/resources/timetable-classmates.webm b/src/resources/timetable-classmates.webm index 3a78cb25..eab6ccb4 100644 Binary files a/src/resources/timetable-classmates.webm and b/src/resources/timetable-classmates.webm differ diff --git a/src/seqta/utils/Openers/OpenThemeOfTheMonthPopup.ts b/src/seqta/utils/Openers/OpenThemeOfTheMonthPopup.ts index 7cdd3b93..982b2c52 100644 --- a/src/seqta/utils/Openers/OpenThemeOfTheMonthPopup.ts +++ b/src/seqta/utils/Openers/OpenThemeOfTheMonthPopup.ts @@ -3,6 +3,7 @@ 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 { @@ -62,7 +63,8 @@ async function writeCachedThemeOfTheMonth( */ export async function fetchThemeOfTheMonth(): Promise { try { - const res = await fetch(`${getApiBase()}/api/theme-of-the-month/current`, { + const url = await withBsplusApiQuery(`${getApiBase()}/api/theme-of-the-month/current`); + const res = await fetch(url, { cache: "no-store", signal: AbortSignal.timeout(TOTM_FETCH_TIMEOUT_MS), }); diff --git a/src/seqta/utils/bsplusClientContext.ts b/src/seqta/utils/bsplusClientContext.ts new file mode 100644 index 00000000..6a84f267 --- /dev/null +++ b/src/seqta/utils/bsplusClientContext.ts @@ -0,0 +1,46 @@ +import browser from "webextension-polyfill"; +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 { + 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 { + const qs = (await bsplusApiQueryParams()).toString(); + return qs ? (url.includes("?") ? `${url}&${qs}` : `${url}?${qs}`) : url; +}