steam-session

repository·master·Indexed 41 days ago

https://github.com/doctormckay/node-steam-session

A Node.js module for negotiating Steam tokens by authenticating with the Steam login server. Version 1.9.4 enables handling Steam Guard, QR logins, and obtaining access and refresh tokens for use with other Steam services. It supports multiple platform types via EAuthTokenPlatformType (SteamClient, WebBrowser, MobileApp) and provides classes like LoginSession for authentication flows and LoginApprover for managing QR login approvals.

Tokens
6.8K
Snippets
21
Records
27
Agent score
51%

What's inside steam-session

  1. Handle LoginSession events

    master

    The LoginSession emits several events during the authentication lifecycle. It is critical to handle the error event, as failing to do so will cause Node.js to crash.

    Key Events:

    • polling: Emitted when the session starts periodically checking Steam to see if the login succeeded. Polling begins after credentials are provided (and guards are satisfied) or after a Steam Guard code is submitted.
    • timeout: Emitted if the loginTimeout period elapses before authentication succeeds. This triggers an internal call to cancelLoginAttempt.
    • remoteInteraction: Emitted when Steam reports a "remote interaction" (e.g., when a user views the approval prompt in the Steam mobile app for a DeviceConfirmation guard, or after a QR code is scanned but before it is approved/denied).
    • steamGuardMachineToken: Emitted when logging into an account with email-based Steam Guard using EAuthTokenPlatformType.SteamClient. The new token is available in the steamGuardMachineToken property.
    • authenticated: Emitted upon successful authentication. At this point, accountName and refreshToken are populated. If using an appropriate EAuthTokenPlatformType, you can now call getWebCookies.
    • error: Emitted if an error occurs during polling. The first argument is an Error object. The login attempt has failed and must be retried with a new LoginSession.
  2. How Steam authentication works

    master

    Logging into Steam via steam-session is a two-step process:

    1. Initiate Session: Start a login session using either account credentials (username and password) or a QR code.
      • Use startWithCredentials(details) for username/password.
      • Use startWithQR() for QR code login.
    2. Satisfy Guards: If credentials are correct, Steam returns a list of login guards (see EAuthSessionGuardType).
      • If Steam Guard is disabled or a valid code was provided upfront, there may be 0 guards required.
      • Only one guard must be satisfied to complete the login (e.g., providing a TOTP code or confirming via the Steam mobile app).

    Once satisfied, Steam returns an access token and a refresh token, which can be used to log on with node-steam-user, obtain web session cookies, or authenticate with mobile app WebAPIs.

    // Conceptual flow summary:
    // 1. session = new LoginSession(platformType)
    // 2. session.startWithCredentials({ accountName, password })
    // 3. Handle guards (e.g., session.submitSteamGuardCode(code))
    // 4. 'authenticated' event fires -> use session.accessToken and session.refreshToken
  3. Custom Transports for steam-session

    master

    The module uses different transports to interact with the Steam login server based on the EAuthTokenPlatformType provided:

    • SteamClient uses WebSocketCMTransport (WebSocket communication with a CM server).
    • Other platform types use WebApiTransport (interacting with api.steampowered.com).

    If you need to implement a custom transport, you can use the following TypeScript interfaces:

    • ITransport
    • ApiRequest
    • ApiResponse
    import { ITransport, ApiRequest, ApiResponse } from 'steam-session';
  4. Importing steam-session

    master

    The module supports both CommonJS and ES6 module syntax. Note that for ES6 modules, there is no default export; you must use named imports.

    CommonJS:

    const { LoginSession, EAuthTokenPlatformType } = require('steam-session');

    ES6 Modules:

    import { LoginSession, EAuthTokenPlatformType } from 'steam-session';
    const { LoginSession } = require('steam-session');
  5. Handle login responses and required actions

    master

    When starting a session, the StartSessionResponse object tells you if the login was successful or if further interaction is required.

    Handling actionRequired If actionRequired is true, you must perform one of the validActions provided in the validActions array to continue the login attempt.

    Valid Actions Each action in validActions contains:

    • type: An EAuthSessionGuardType indicating the type of guard (e.g., EmailCode).
    • detail: (Optional) A string containing extra details, such as the domain of the email address used for an EmailCode guard.

    QR Code Login If you are using startWithQR, the response will contain a qrChallengeUrl. This string is the URL that must be encoded into a QR code for a user to scan with their Steam mobile app.

    // Conceptual handling of a response
    if (response.actionRequired) {
      for (const action of response.validActions) {
        console.log(`Action required: ${action.type}, Detail: ${action.detail}`);
      }
    }
  6. Initialize a LoginSession

    master

    Create a new LoginSession instance by providing a platform type from EAuthTokenPlatformType. You can also provide an optional options object to configure the session.

    Available Options:

    • userAgent: Override the default user-agent (only effective for EAuthTokenPlatformType.WebBrowser).
    • transport: An ITransport instance for custom transport logic. Defaults to WebSocketCMTransport for SteamClient and WebApiTransport for others.
    • localAddress: A string containing the local IP address.
    • httpProxy: A URI for an HTTP proxy (e.g., http://user:pass@1.2.3.4:80).
    • socksProxy: A URI for a SOCKS proxy (e.g., socks5://user:pass@1.2.3.4:1080).
    • agent: An https.Agent instance.
    • machineId: (Only for SteamClient) A Buffer containing a valid Steam machine ID, or true to auto-generate one.
    • machineFriendlyName: (Only for SteamClient) A string for the machine name reported to Steam.

    Constraint: You can only use one of localAddress, httpProxy, socksProxy, or agent at a time. Using more than one will throw an Error.

    import {LoginSession, EAuthTokenPlatformType} from 'steam-session';
    
    let session = new LoginSession(EAuthTokenPlatformType.WebBrowser);
  7. Start a login with credentials using startWithCredentials()

    master

    Initiates a login attempt using an account name and password. Returns a Promise that resolves to an object describing the login state.

    Arguments (details object):

    • accountName: String login name.
    • password: String password.
    • persistence: Optional ESessionPersistence value (defaults to Persistent).
    • steamGuardMachineToken: Optional. For EAuthTokenPlatformType.SteamClient, pass a Buffer containing the SHA-1 hash of your sentry file to bypass email verification.
    • steamGuardCode: Optional. A valid Steam Guard code (email or TOTP).

    Success Response:

    • actionRequired: Boolean. If true, you must handle a guard (e.g., EmailCode, DeviceCode, DeviceConfirmation, or EmailConfirmation) using submitSteamGuardCode() or similar.
    • validActions: Array of objects describing required actions.

    Failure: The Promise rejects with an Error where the message is the string representation of an EResult and the .eresult property is the numeric code.

    import {createHash} from 'crypto';
    import {readFileSync} from 'fs';
    import {LoginSession, EAuthTokenPlatformType} from 'steam-session';
    
    let hash = createHash('sha1');
    hash.update(readFileSync('ssfn1234567890'));
    let buffer = hash.digest(); // buffer contains a Buffer
    
    let session = new LoginSession(EAuthTokenPlatformType.SteamClient);
    session.startWithCredentials({
    	accountName: 'johndoe',
    	password: 'h3ll0wor1d',
    	steamGuardMachineToken: buffer
    });
  8. Use LoginApprover to approve QR logins

    master

    The LoginApprover class is used to approve or deny login attempts that were initiated via a QR code.

    Constructor Parameters

    • accessToken (string): A valid access token for the account. Note: This must be an access token (not a refresh token) and must have been generated using EAuthTokenPlatformType.MobileApp.
    • sharedSecret (string | Buffer): The account's TOTP shared secret. If a string, it must be hex- or base64-encoded.
    • options (object, optional):
      • transport: An ITransport instance (defaults to WebApiTransport).
      • localAddress: Local IP address string.
      • httpProxy: URI for an HTTP proxy.
      • socksProxy: URI for a SOCKS proxy.
      • agent: An https.Agent instance.
      • Note: You can only use one of localAddress, httpProxy, socksProxy, or agent at a time.

    Methods

    • getAuthSessionInfo(qrChallengeUrl): Returns a Promise resolving to an object containing session details like ip, location (city, state, geoloc), platformType, deviceFriendlyName, loginHistory, and requestedPersistence.
    • approveAuthSession(details): Approves or denies the session.
      • details.approve: true to approve, false to deny.
      • details.qrChallengeUrl: The URL from the startWithQR call.
      • details.persistence: An ESessionPersistence value.
      • If denied (false), the LoginSession will emit an error event with EResult.FileNotFound (9).
    import {LoginApprover} from 'steam-session';
    
    // Initialize with an access token and shared secret
    let approver = new LoginApprover('eyAid...', 'oTVMfZJ9uHXo3m9MwTD9IOEWQaw=');
    
    // Example: Approving a session
    await approver.approveAuthSession({
      qrChallengeUrl: 'https://example.com/qr-url',
      approve: true,
      persistence: ESessionPersistence.Session
    });
  9. Start a QR login with startWithQR()

    master

    Initiates a QR code-based login attempt. Returns a Promise that resolves to an object containing the QR challenge URL.

    Success Response:

    • actionRequired: Always true.
    • validActions: Array of required actions (typically DeviceConfirmation).
    • qrChallengeUrl: The URL to be encoded into a QR code for scanning with the Steam mobile app.

    Note: steamID is not populated immediately; it will be populated after successful authentication. The session will automatically start polling for the authentication result.

    // Usage pattern for startWithQR
    let session = new LoginSession(EAuthTokenPlatformType.WebBrowser);
    let result = await session.startWithQR();
    console.log(result.qrChallengeUrl);
  10. Retrieve web cookies with getWebCookies()

    master

    Once authenticated, retrieves an array of cookie strings (e.g., steamLoginSecure=...) for use on Steam websites.

    Usage with Refresh Tokens: You can manually set the refreshToken property on the LoginSession and then call getWebCookies() to bypass a full login flow.

    Platform Support Note: As of 2025-04-30, this works for EAuthTokenPlatformType.WebBrowser and MobileApp. For SteamClient, you must use node-steam-user's webLogOn() method instead.

    import {LoginSession, EAuthTokenPlatformType} from 'steam-session';
    
    let session = new LoginSession(EAuthTokenPlatformType.WebBrowser);
    session.refreshToken = 'eyAidHlwIjogIkpXVCIsICJhbGciOiAiRWREU0EiIH0.eyJpc3MiOiJ...';
    let cookies = await session.getWebCookies();
  11. LoginSession Properties

    master

    The LoginSession class provides the following properties to track the state of an authentication attempt:

    • steamID (Read-only): A SteamID instance for the authenticated account. Populated after startWithCredentials resolves or after tokens are set.
    • loginTimeout: A number (milliseconds) specifying when a login attempt will timeout. Must be set before polling is emitted.
    • accountName (Read-only): A string containing the account name. Populated just before the authenticated event.
    • accessToken: A string containing the access token. Note: This is populated after calling refreshAccessToken(), renewRefreshToken(), or getWebCookies() (for SteamClient or MobileApp).
    • refreshToken: A string containing the refresh token. Populated just before the authenticated event.
    • steamGuardMachineToken (Read-only): A string containing the Steam Guard machine token. Populated when passed to startWithCredentials or just before the steamGuardMachineToken event.
  12. Manage LoginSession polling and cancellation

    master

    During an active login attempt, you can control the polling behavior:

    • forcePoll(): Forces an immediate polling attempt. Throws an error if called before the polling event is emitted, after authenticated is emitted, or after cancelLoginAttempt() is called.
    • cancelLoginAttempt(): Stops polling for the current login attempt. After calling this, the LoginSession instance should be considered dead; create a new one for any subsequent attempts.