Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -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*",
Expand Down
24 changes: 2 additions & 22 deletions src/background.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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: [
{
Expand All @@ -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(() => {
Expand Down
166 changes: 73 additions & 93 deletions src/lib/alarms/access_token.test.ts
Original file line number Diff line number Diff line change
@@ -1,136 +1,116 @@
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<string, unknown>();
const {storage, getCookie, isFirefox} = vi.hoisted(() => {
const getCookie = vi.fn();
vi.stubGlobal('chrome', {storage: {local: {}}, cookies: {get: getCookie}});
return {storage: new Map<string, unknown>(), getCookie, isFirefox: vi.fn()};
});
vi.mock('../utils/detect', () => ({isFirefox}));
vi.mock('../storage/store', () => ({
gStore: {
getWithStorage: async (_: unknown, key: string) => storage.get(key),
setWithStorage: async (_: unknown, key: string, value: unknown) => void storage.set(key, value),
},
}));

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', () => {
Expand Down
Loading