diff --git a/manifest.json b/manifest.json index 2ee179a8..4c1a0257 100644 --- a/manifest.json +++ b/manifest.json @@ -49,7 +49,7 @@ "type": "module" }, "minimum_chrome_version": "109", - "permissions": ["storage", "scripting", "alarms", "declarativeNetRequestWithHostAccess", "offscreen"], + "permissions": ["storage", "scripting", "alarms", "declarativeNetRequestWithHostAccess", "offscreen", "cookies"], "host_permissions": [ "*://*.steamcommunity.com/market/listings/730/*", "*://*.steamcommunity.com/id/*/inventory*", diff --git a/src/background.ts b/src/background.ts index 32741f41..8668c3a6 100644 --- a/src/background.ts +++ b/src/background.ts @@ -69,10 +69,11 @@ async function checkTradeStatus() { checkTradeStatus(); if (isFirefox()) { - // Need to manually update the rules to allow the extension to send trade offers and renew the store session + // Need to manually update the rule to allow the extension to send trade offers // Since Firefox IDs are random and we still want to scope it to only this extension browser.declarativeNetRequest .updateDynamicRules({ + // 1795650406 and 1795650407 were the 5.19.3 store session renewal rules, dynamic rules survive updates removeRuleIds: [1738196326, 1795650406, 1795650407], addRules: [ { @@ -94,27 +95,6 @@ if (isFirefox()) { initiatorDomains: [new URL(browser.runtime.getURL('')).hostname], }, }, - ...( - [ - [1795650406, 'https://login.steampowered.com/jwt/ajaxrefresh'], - [1795650407, 'https://store.steampowered.com/login/settoken'], - ] as const - ).map(([id, urlFilter]) => ({ - id, - priority: 2, - action: { - type: 'modifyHeaders' as const, - requestHeaders: [ - {header: 'origin', operation: 'set' as const, value: 'https://store.steampowered.com'}, - {header: 'referer', operation: 'set' as const, value: 'https://store.steampowered.com/'}, - ], - }, - condition: { - urlFilter, - resourceTypes: ['xmlhttprequest' as const], - initiatorDomains: [new URL(browser.runtime.getURL('')).hostname], - }, - })), ], }) .then(() => { diff --git a/src/lib/alarms/access_token.test.ts b/src/lib/alarms/access_token.test.ts index beddb05b..92dcb26c 100644 --- a/src/lib/alarms/access_token.test.ts +++ b/src/lib/alarms/access_token.test.ts @@ -1,10 +1,12 @@ import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest'; import {extractSteamID, getAccessToken} from './access_token'; -const storage = vi.hoisted(() => { - vi.stubGlobal('chrome', {storage: {local: {}}}); - return new Map(); +const {storage, getCookie, isFirefox} = vi.hoisted(() => { + const getCookie = vi.fn(); + vi.stubGlobal('chrome', {storage: {local: {}}, cookies: {get: getCookie}}); + return {storage: new Map(), getCookie, isFirefox: vi.fn()}; }); +vi.mock('../utils/detect', () => ({isFirefox})); vi.mock('../storage/store', () => ({ gStore: { getWithStorage: async (_: unknown, key: string) => storage.get(key), @@ -12,125 +14,103 @@ vi.mock('../storage/store', () => ({ }, })); -const payload = btoa(JSON.stringify({sub: '76561198000000001', aud: ['web:store']})).replace(/=+$/, ''); -const token = `eyJhbGciOiJFZERTQSJ9.${payload}.c2ln`; +const EXP = Date.UTC(2026, 10, 27) / 1000; -const REFRESH = { - success: true, - login_url: 'https://store.steampowered.com/login/settoken', - steamID: '76561198000000001', - nonce: 'nonce', - redir: '/', - auth: 'auth', -}; - -/** Routes Steam requests to canned JSON bodies, the store config is logged in once settoken succeeds */ -function stubSteam( - opts: { - loggedIn?: boolean; - refresh?: unknown; - refreshFails?: boolean; - refreshStatus?: number; - settokenResult?: number; - } = {} -) { - let loggedIn = !!opts.loggedIn; - const fetchMock = vi.fn(async (url: string, _?: RequestInit) => { - let body: unknown = {}; - let status = 200; - if (url.endsWith('/ajaxgetasyncconfig')) { - body = {success: 1, data: loggedIn ? {webapi_token: token} : []}; - } else if (url.endsWith('/jwt/ajaxrefresh')) { - if (opts.refreshFails) { - throw new TypeError('Failed to fetch'); - } - body = opts.refresh ?? REFRESH; - status = opts.refreshStatus ?? 200; - } else if (url.endsWith('/login/settoken')) { - body = {result: opts.settokenResult ?? 1}; - loggedIn = opts.settokenResult === undefined; - } - return {ok: status < 400, status, json: () => Promise.resolve(body)}; +function makeToken(claims: object) { + const payload = btoa(JSON.stringify({sub: '76561198000000001', aud: ['web:community'], ...claims})); + return `eyJhbGciOiJFZERTQSJ9.${payload.replace(/=+$/, '')}.c2ln`; +} +const token = makeToken({exp: EXP}); +const cookieFor = (t: string) => `76561198000000001%7C%7C${t}`; + +/** Records the page load and cookie read in order, the cookie is only refreshed by the page load */ +function stubSteam(cookieValue?: string, steamDate = new Date((EXP - 3600) * 1000)) { + const calls: string[] = []; + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string) => { + calls.push(url); + return {headers: new Headers({date: steamDate.toUTCString()})}; + }) + ); + getCookie.mockImplementation(async ({name}: {name: string}) => { + calls.push(`cookie:${name}`); + return cookieValue === undefined ? null : {name, value: cookieValue}; }); - vi.stubGlobal('fetch', fetchMock); - return (path: string) => fetchMock.mock.calls.filter(([url]) => url.endsWith(path)); + return calls; } describe('getAccessToken', () => { - beforeEach(() => storage.clear()); + beforeEach(() => { + storage.clear(); + isFirefox.mockReturnValue(false); + }); afterEach(() => vi.useRealTimers()); - it('reads the web API token and Steam ID from the store config', async () => { - const calls = stubSteam({loggedIn: true}); + it('reads the token from the steamLoginSecure cookie after loading steamcommunity.com', async () => { + const calls = stubSteam(cookieFor(token)); await expect(getAccessToken('76561198000000001')).resolves.toMatchObject({ token, steam_id: '76561198000000001', }); - expect(calls('/jwt/ajaxrefresh')).toHaveLength(0); + expect(calls).toEqual(['https://steamcommunity.com', 'cookie:steamLoginSecure']); }); it('rejects a token for a different Steam account', async () => { - stubSteam({loggedIn: true}); + stubSteam(cookieFor(token)); await expect(getAccessToken('76561198000000002')).rejects.toThrow('expected steam account'); }); - it('renews an expired store session without following redirects', async () => { - const calls = stubSteam(); - await expect(getAccessToken()).resolves.toMatchObject({token}); - const [, init] = calls('/login/settoken')[0]; - expect((init!.body as FormData).get('auth')).toBe('auth'); - expect(init!.redirect).toBe('error'); + it('fails without a usable cookie', async () => { + for (const value of [undefined, '', '76561198000000001']) { + stubSteam(value); + await expect(getAccessToken()).rejects.toThrow('failed to parse web api token'); + } }); - it('shares one renewal between overlapping callers', async () => { - const calls = stubSteam(); - const results = await Promise.all([getAccessToken(), getAccessToken('76561198000000001')]); - expect(results.map((r) => r.token)).toEqual([token, token]); - expect(calls('/jwt/ajaxrefresh')).toHaveLength(1); + it("rejects tokens that are expired by Steam's clock, or have no expiry", async () => { + for (const t of [makeToken({exp: EXP}), makeToken({}), 'not-a-jwt']) { + stubSteam(cookieFor(t), new Date((EXP + 1) * 1000)); + await expect(getAccessToken()).rejects.toThrow('steam web api token is expired'); + } }); - it('waits an hour after Steam rejects a renewal', async () => { + it("trusts Steam's clock over a drifted local one", async () => { vi.useFakeTimers({toFake: ['Date']}); - const rejected = stubSteam({settokenResult: 8}); - await expect(getAccessToken()).rejects.toThrow('failed to parse web api token'); - // A rejected settoken doesn't refetch the config - expect(rejected('/ajaxgetasyncconfig')).toHaveLength(1); - - const throttled = stubSteam(); - await expect(getAccessToken()).rejects.toThrow('failed to parse web api token'); - expect(throttled('/jwt/ajaxrefresh')).toHaveLength(0); - - vi.setSystemTime(Date.now() + 61 * 60 * 1000); + vi.setSystemTime((EXP + 24 * 3600) * 1000); + stubSteam(cookieFor(token)); await expect(getAccessToken()).resolves.toMatchObject({token}); }); - it('retries right away after a network error, but not after a Steam error', async () => { - stubSteam({refreshFails: true}); - await expect(getAccessToken()).rejects.toThrow('failed to parse web api token'); - - stubSteam({refreshStatus: 500}); - await expect(getAccessToken()).rejects.toThrow('failed to parse web api token'); + it('only reuses a cached token while it has more than 5 minutes left', async () => { + vi.useFakeTimers({toFake: ['Date']}); + // Local clock is a day ahead of Steam's, the token has 10 minutes left + vi.setSystemTime((EXP - 600 + 24 * 3600) * 1000); + const calls = stubSteam(cookieFor(token), new Date((EXP - 600) * 1000)); + await getAccessToken(); - const throttled = stubSteam(); - await expect(getAccessToken()).rejects.toThrow('failed to parse web api token'); - expect(throttled('/jwt/ajaxrefresh')).toHaveLength(0); - }); + vi.setSystemTime(Date.now() + 60 * 1000); + await expect(getAccessToken()).resolves.toMatchObject({token}); + expect(calls).toHaveLength(2); - it('never posts incomplete or misdirected auth to settoken', async () => { - for (const refresh of [ - {...REFRESH, login_url: 'https://example.com/login/settoken'}, - {...REFRESH, auth: undefined}, - ]) { - storage.clear(); - const calls = stubSteam({refresh}); - await expect(getAccessToken()).rejects.toThrow('failed to parse web api token'); - expect(calls('/login/settoken')).toHaveLength(0); - } + vi.setSystemTime(Date.now() + 5 * 60 * 1000); + await getAccessToken(); + expect(calls).toHaveLength(4); }); - it('explains non-JSON store responses', async () => { - vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ok: true, json: () => Promise.reject(new SyntaxError())})); - await expect(getAccessToken()).rejects.toThrow('failed to parse steam store config'); + it('retries with firstPartyDomain when Firefox first-party isolation rejects the lookup', async () => { + isFirefox.mockReturnValue(true); + stubSteam(cookieFor(token)); + const isolated = getCookie.getMockImplementation()!; + getCookie.mockImplementation(async (details: {firstPartyDomain?: string}) => { + if (details.firstPartyDomain !== 'steamcommunity.com') { + throw new Error( + "First-Party Isolation is enabled, but the required 'firstPartyDomain' attribute was not set." + ); + } + return isolated(details); + }); + await expect(getAccessToken()).resolves.toMatchObject({token}); }); it('returns null for malformed tokens', () => { diff --git a/src/lib/alarms/access_token.ts b/src/lib/alarms/access_token.ts index ad28cab9..7f5264d9 100644 --- a/src/lib/alarms/access_token.ts +++ b/src/lib/alarms/access_token.ts @@ -1,24 +1,31 @@ import {gStore} from '../storage/store'; import {StorageKey} from '../storage/keys'; +import {isFirefox} from '../utils/detect'; export interface AccessToken { token: string; steam_id?: string | null; updated_at: number; + // JWT expiry on the local clock + expires_at?: number; } export async function getAccessToken(expectedSteamID?: string): Promise { // Do we have a fresh local copy? const tokenData = await gStore.getWithStorage(chrome.storage.local, StorageKey.ACCESS_TOKEN); - if (tokenData?.token && tokenData.updated_at > Date.now() - 30 * 60 * 1000) { - // Token refreshed within the last 30 min, we can re-use + if ( + tokenData?.token && + tokenData.updated_at > Date.now() - 30 * 60 * 1000 && + (tokenData.expires_at ?? 0) > Date.now() + 5 * 60 * 1000 + ) { + // Token refreshed within the last 30 min and isn't about to expire, we can re-use if (!expectedSteamID || expectedSteamID === tokenData?.steam_id) { return tokenData; } } // Need to fetch a new one - await fetch(`https://store.steampowered.com`, { + const resp = await fetch(`https://steamcommunity.com`, { credentials: 'include', headers: { // Required for Steam to refresh the JWT when it expires @@ -26,137 +33,70 @@ export async function getAccessToken(expectedSteamID?: string): Promise { + if (!isFirefox()) { + throw e; + } + // Firefox requires `firstPartyDomain` when first-party isolation is enabled + return chrome.cookies.get({ + ...cookieDetails, + firstPartyDomain: 'steamcommunity.com', + } as chrome.cookies.CookieDetails); + }); + // Structured as `||` + const token = decodeURIComponent(cookie?.value ?? '').split('||')[1]; if (!token) { throw new Error('failed to parse web api token'); } + // Steam leaves the expired JWT in the cookie when it can't refresh the session. + // Compared against Steam's clock since the user's can drift. + const steamNow = Date.parse(resp.headers.get('date') ?? '') || Date.now(); + const {exp} = decodeJWTPayload(token) ?? {}; + if (typeof exp !== 'number' || exp * 1000 <= steamNow) { + throw new Error('steam web api token is expired'); + } + const steamID = extractSteamID(token); if (steamID && expectedSteamID && steamID !== expectedSteamID) { throw new Error('user is not logged into the expected steam account'); } + const data: AccessToken = { + token, + steam_id: steamID, + updated_at: Date.now(), + expires_at: Date.now() + exp * 1000 - steamNow, + }; + try { - await saveAccessToken(token, steamID); + await saveAccessToken(data); } catch (e) { console.error('failed ot save access token to storage', e); } - return {token, steam_id: steamID, updated_at: Date.now()}; + return data; } -async function fetchStoreWebAPIToken(): Promise { - const resp = await fetch(`https://store.steampowered.com/pointssummary/ajaxgetasyncconfig`, { - credentials: 'include', - }); - if (!resp.ok) { - throw new Error(`failed to fetch steam store config (status ${resp.status})`); - } - - const body = await resp.json().catch(() => { - throw new Error('failed to parse steam store config'); - }); - - return body?.data?.webapi_token; -} - -let storeTokenRenewal: Promise | null = null; - -/** - * Overlapping callers share one renewal, so they don't race the hourly throttle or send Steam competing nonces - */ -function renewStoreWebAPIToken(): Promise { - storeTokenRenewal ??= (async () => { - try { - return (await renewStoreSession()) ? await fetchStoreWebAPIToken() : undefined; - } finally { - storeTokenRenewal = null; - } - })(); - return storeTokenRenewal; -} - -const STORE_SETTOKEN_URL = 'https://store.steampowered.com/login/settoken'; -const SETTOKEN_FIELDS = ['steamID', 'nonce', 'redir', 'auth']; - -/** - * The store login cookie can expire while the Steam login session is still valid (ie. steamcommunity.com still - * works), so renew it the same way the store page does. Returns whether it renewed. - */ -async function renewStoreSession(): Promise { - const lastAttempt = await gStore.getWithStorage( - chrome.storage.local, - StorageKey.LAST_STORE_SESSION_RENEWAL_ATTEMPT - ); - if (lastAttempt && lastAttempt > Date.now() - 60 * 60 * 1000) { - // Steam already said no within the last hour, they're likely logged out of Steam entirely - return false; - } - - // Only Steam answering counts towards the hourly throttle, network errors are retried on the next call - const steamAnswered = () => - gStore.setWithStorage(chrome.storage.local, StorageKey.LAST_STORE_SESSION_RENEWAL_ATTEMPT, Date.now()); - - try { - const refreshForm = new FormData(); - refreshForm.append('redir', 'https://store.steampowered.com/'); - const refreshResp = await fetch(`https://login.steampowered.com/jwt/ajaxrefresh`, { - method: 'POST', - credentials: 'include', - body: refreshForm, - }); - - const refresh = refreshResp.ok ? await refreshResp.json().catch(() => null) : null; - if ( - !refresh?.success || - // Only ever send the auth to the store - refresh.login_url !== STORE_SETTOKEN_URL || - !SETTOKEN_FIELDS.every((key) => typeof refresh[key] === 'string' && refresh[key]) - ) { - await steamAnswered(); - return false; - } - - const tokenForm = new FormData(); - for (const key of SETTOKEN_FIELDS) { - tokenForm.append(key, refresh[key]); - } - const tokenResp = await fetch(STORE_SETTOKEN_URL, { - method: 'POST', - credentials: 'include', - body: tokenForm, - // A redirect would resend the auth wherever it points - redirect: 'error', - }); - - await steamAnswered(); - // Rejections are still HTTP 200, ie. `{"result": 8}` - const result = tokenResp.ok ? await tokenResp.json().catch(() => null) : null; - return result?.result === 1; - } catch (e) { - console.error('failed to renew steam store session', e); - return false; - } -} - -export function extractSteamID(token: string): string | null { +function decodeJWTPayload(token: string): {sub?: unknown; exp?: unknown} | null { try { const payload = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/'); - const {sub} = JSON.parse(atob(payload)); - return /^\d+$/.test(sub) ? sub : null; + return JSON.parse(atob(payload)); } catch { return null; } } -export function saveAccessToken(token: string, steamID: string | null): Promise { +export function extractSteamID(token: string): string | null { + const sub = decodeJWTPayload(token)?.sub; + return typeof sub === 'string' && /^\d+$/.test(sub) ? sub : null; +} + +export function saveAccessToken(data: AccessToken): Promise { // Explicitly use local storage to prevent issues with sync storage quota or connectivity issues - return gStore.setWithStorage(chrome.storage.local, StorageKey.ACCESS_TOKEN, { - token, - steam_id: steamID, - updated_at: Date.now(), - } as AccessToken); + return gStore.setWithStorage(chrome.storage.local, StorageKey.ACCESS_TOKEN, data); } export function clearAccessTokenFromStorage(): Promise { diff --git a/src/lib/storage/keys.ts b/src/lib/storage/keys.ts index 306d872f..1566e980 100644 --- a/src/lib/storage/keys.ts +++ b/src/lib/storage/keys.ts @@ -13,7 +13,6 @@ export enum StorageKey { ACCESS_TOKEN = 'access_token', LAST_TRADE_PING_ATTEMPT = 'last_trade_ping_attempt', LAST_TRADE_BLOCKED_PING_ATTEMPT = 'last_trade_blocked_ping_attempt', - LAST_STORE_SESSION_RENEWAL_ATTEMPT = 'last_store_session_renewal_attempt', LAST_NOTARY_BG_PROOF_FAILURE = 'last_notary_bg_proof_failure', NOTARY_ACCEPTED_PROOF_ATTEMPTS = 'notary_accepted_proof_attempts', // csfloat trade id -> last attempt ms PRICE_CACHE = 'price_cache', // Stores market hash name -> price mapping (~0.86MB) diff --git a/src/steamcommunity_ruleset.json b/src/steamcommunity_ruleset.json index f025edb0..1ee0dfcf 100644 --- a/src/steamcommunity_ruleset.json +++ b/src/steamcommunity_ruleset.json @@ -17,53 +17,5 @@ "resourceTypes": ["xmlhttprequest"], "initiatorDomains": ["jjicbefpemnphinccgikpdaagjebbnhg", "gdlioplmcfbdloeoojolmlijihfplcmk"] } - }, - { - "id": 2, - "priority": 1, - "action": { - "type": "modifyHeaders", - "requestHeaders": [ - { - "header": "origin", - "operation": "set", - "value": "https://store.steampowered.com" - }, - { - "header": "referer", - "operation": "set", - "value": "https://store.steampowered.com/" - } - ] - }, - "condition": { - "urlFilter": "https://login.steampowered.com/jwt/ajaxrefresh", - "resourceTypes": ["xmlhttprequest"], - "initiatorDomains": ["jjicbefpemnphinccgikpdaagjebbnhg", "gdlioplmcfbdloeoojolmlijihfplcmk"] - } - }, - { - "id": 3, - "priority": 1, - "action": { - "type": "modifyHeaders", - "requestHeaders": [ - { - "header": "origin", - "operation": "set", - "value": "https://store.steampowered.com" - }, - { - "header": "referer", - "operation": "set", - "value": "https://store.steampowered.com/" - } - ] - }, - "condition": { - "urlFilter": "https://store.steampowered.com/login/settoken", - "resourceTypes": ["xmlhttprequest"], - "initiatorDomains": ["jjicbefpemnphinccgikpdaagjebbnhg", "gdlioplmcfbdloeoojolmlijihfplcmk"] - } } ]