Skip to content

armgit / soju

Public Imported from GitHub
0

Play Windows games on Apple Silicon Macs. Free, open-source app that installs the official Battle.net, Steam, Epic and GOG launchers and lists your games in one library.

7.0 KB
Raw Blame
// Runs only inside the user's official Steam page. Sessions never leave WebKit.
if (location.protocol !== "https:" || !["steamcommunity.com", "store.steampowered.com"].includes(location.hostname)) {
    return { state: "wrong-page" };
}
const config = document.getElementById("application_config");
const attribute = name => {
    try { return JSON.parse(config?.getAttribute(name) || "{}"); } catch { return {}; }
};
const user = attribute("data-userinfo");
// Steam's React pages, the current All Games page among them, have no
// application_config, g_steamID or account menu. Their viewer is UserConfig.
const reactUser = window.UserConfig && typeof window.UserConfig === "object" ? window.UserConfig : null;
const validID = value => /^765[0-9]{14}$/.test(String(value || ""));
const viewers = [window.g_steamID, user.steamid, reactUser?.steamid].filter(validID).map(String);
if (new Set(viewers).size > 1) return { state: "unavailable" };
let steamid = viewers[0] || "";
const loggedIn = user.logged_in === true || reactUser?.logged_in === true;
function reactToken() {
    if (reactUser?.logged_in !== true || !Array.isArray(window.SSR?.loaderData)) return "";
    for (const item of window.SSR.loaderData) {
        try {
            const value = typeof item === "string" ? JSON.parse(item) : item;
            if (typeof value?.strWebAPIToken === "string" && value.strWebAPIToken) return value.strWebAPIToken;
        } catch {}
    }
    return "";
}

function snapshot(rows, count) {
    if (!Array.isArray(rows) || !Number.isInteger(count) || count < 0 ||
        count > 20000 || rows.length !== count) return { state: "unavailable", why: "count" };
    const games = [];
    const seen = new Set();
    for (const row of rows) {
        if (!row || !/^[1-9][0-9]{0,9}$/.test(String(row.appid))) return { state: "unavailable", why: "appid" };
        const appid = String(row.appid);
        // Steam lists some apps without a name (delisted games, test servers, tools).
        // Skip those rows instead of refusing the whole library; repeated rows count once.
        if (typeof row.name !== "string" || !row.name.trim() || row.name.length > 1000 || seen.has(appid)) continue;
        seen.add(appid);
        games.push({ appid, name: row.name.trim().slice(0, 300) });
    }
    // Rows that all lack a name must not replace a library with an empty one.
    if (count > 0 && games.length === 0) return { state: "unavailable", why: "names" };
    return { state: "ready", steamid, game_count: games.length, games };
}

// Legacy All Games pages do not consistently include application_config or a
// webapi_token. Read their complete list only when its owner matches this session.
const profile = String(window.g_rgProfileData?.steamid || "");
const ownAllGames = () => validID(steamid) && location.hostname === "steamcommunity.com" &&
    /\/games\/?$/.test(location.pathname) &&
    new URLSearchParams(location.search).get("tab") === "all" && profile === steamid &&
    Array.isArray(window.rgGames);
if (ownAllGames()) return snapshot(window.rgGames, window.rgGames.length);
// Steam's current All Games page carries the owner's complete list in its own
// server-rendered data (the "OwnedGames" query). Read it when the page says it is the
// viewer's own profile: Steam's session token is refused (401) by the owned-games API.
function pageOwnedGames() {
    if (reactUser?.logged_in !== true || !validID(steamid) || location.hostname !== "steamcommunity.com") return null;
    const parse = value => { try { return typeof value === "string" ? JSON.parse(value) : value; } catch { return null; } };
    const loaders = Array.isArray(window.SSR?.loaderData) ? window.SSR.loaderData.map(parse) : [];
    if (!loaders.some(item => item && item.bOwnProfile === true && String(item.steamid) === steamid)) return null;
    const queries = parse(parse(window.SSR?.renderContext)?.queryData)?.queries;
    if (!Array.isArray(queries)) return null;
    for (const query of queries) {
        const key = query?.queryKey;
        if (Array.isArray(key) && key[0] === "OwnedGames" && String(key[1]) === steamid &&
            query.state?.status === "success" && Array.isArray(query.state.data)) return query.state.data;
    }
    return null;
}
const pageGames = pageOwnedGames();
if (pageGames && pageGames.length) {
    const value = snapshot(pageGames, pageGames.length);
    if (value.state === "ready") return value;
}
if (!reactUser && validID(steamid) && validID(profile) && !ownAllGames() && !user.webapi_token) {
    return { state: "open-library" };
}
const signedInPage = !!document.querySelector?.("#account_pulldown");

const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 20000);
async function readJSON(url, credentials, limit) {
    const response = await fetch(url, {
        signal: controller.signal, redirect: "error", credentials, cache: "no-store"
    });
    if (!response.ok) throw Error("http" + response.status);
    const raw = await response.text();
    if (raw.length > limit) throw Error("response too large");
    return JSON.parse(raw);
}
try {
    let token = user.logged_in === true && typeof user.webapi_token === "string" ? user.webapi_token : reactToken();
    // Steam's legacy community pages can omit both identity and the token.
    // Ask Steam's own session endpoint on the same origin; do not scrape cookies.
    const loginPage = /^\/(login|openid)(\/|$)/.test(location.pathname);
    if (!token && location.hostname === "steamcommunity.com" && !loginPage &&
        (validID(steamid) || loggedIn || signedInPage)) {
        const session = await readJSON("https://steamcommunity.com/chat/clientjstoken", "same-origin", 64 * 1024);
        if (session.logged_in !== true || !validID(session.steamid)) {
            return { state: validID(steamid) ? "open-library" : "sign-in" };
        }
        if (validID(steamid) && steamid !== String(session.steamid)) return { state: "unavailable" };
        steamid = String(session.steamid);
        if (ownAllGames()) return snapshot(window.rgGames, window.rgGames.length);
        token = typeof session.token === "string" ? session.token : "";
    }
    if (!validID(steamid)) return { state: "sign-in" };
    if (!token) return { state: "open-library" };
    const params = new URLSearchParams({
        access_token: token,
        input_json: JSON.stringify({ steamid, include_appinfo: true, include_played_free_games: true })
    });
    const payload = await readJSON("https://api.steampowered.com/IPlayerService/GetOwnedGames/v1/?" + params,
                                   "omit", 8 * 1024 * 1024);
    const value = payload.response;
    if (!value || !Object.prototype.hasOwnProperty.call(value, "game_count")) return { state: "unavailable", why: "private" };
    return snapshot(value.games || [], value.game_count);
} catch (error) {
    // Only Steam's status code leaves this page, never a URL, token or message.
    return { state: "unavailable", why: /^http[0-9]{3}$/.test(error?.message) ? error.message : "request" };
} finally {
    clearTimeout(timer);
}