### Basic HTTP Server Steam Sign-In Integration Source: https://context7.com/doctormckay/node-steam-signin/llms.txt A complete example demonstrating how to integrate Steam Sign-In with a basic Node.js HTTP server. It handles both the initial redirect to the Steam login page and the callback route for verifying the authentication response. ```javascript const HTTP = require('http'); const SteamSignIn = require('steam-signin'); const signIn = new SteamSignIn('http://localhost'); let serverPort; const server = HTTP.createServer(async (req, res) => { // Callback route - verify Steam login if (req.url.startsWith('/callback')) { res.setHeader('Content-Type', 'text/plain'); try { const steamId = await signIn.verifyLogin(req.url); res.end(`Authenticated! SteamID: ${steamId.getSteamID64()}`); console.log(`User logged in: ${steamId.steam3()}`); } catch (error) { res.statusCode = 401; res.end(`Authentication failed: ${error.message}`); } return; } // Main route - redirect to Steam const returnUrl = `http://localhost:${serverPort}/callback`; res.statusCode = 302; res.setHeader('Location', signIn.getUrl(returnUrl)); res.end(); }); server.listen(() => { serverPort = server.address().port; console.log(`Server: http://localhost:${serverPort}`); }); ``` -------------------------------- ### Verify User Login (JavaScript) Source: https://github.com/doctormckay/node-steam-signin/blob/master/README.md Provides an example of verifying a user's login after they return to your site. The verifyLogin method takes the return URL (including querystring parameters) and returns a promise that resolves with the user's SteamID object upon successful authentication. It will reject if the login data is invalid or reused. ```javascript let returnUrl = getReturnUrlSomehow(); // returnUrl must contain the URL the user landed at your site on, including all querystring parameters. How exactly you // fetch this value will depend on the web framework you're using. let steamId = await signIn.verifyLogin(returnUrl); // If we make it here, the user has successfully authenticated. If their login data was bogus or reused, the verifyLogin() // promise would reject, which you could catch with try/catch. // steamId is a SteamID object (see https://www.npmjs.com/package/steamid) console.log(`User successfully authenticated as ${steamId.getSteamID64()}`); ``` -------------------------------- ### Get Authentication URL (JavaScript) Source: https://github.com/doctormckay/node-steam-signin/blob/master/README.md Illustrates how to obtain the authentication URL by calling the getUrl method on a SteamSignIn instance. This URL is used to redirect users to Steam for authentication. The return URL must match the realm provided during instantiation. ```javascript let authUrl = signIn.getUrl('https://example.com/auth/return'); ``` -------------------------------- ### Constructor: new SteamSignIn(realm) Source: https://context7.com/doctormckay/node-steam-signin/llms.txt Initializes a new SteamSignIn instance. The 'realm' parameter should be the protocol and domain of your website (e.g., 'https://example.com'). Ports and paths are not allowed. ```APIDOC ## Constructor: new SteamSignIn(realm) ### Description Creates a new SteamSignIn instance with the specified realm (protocol and domain). ### Parameters #### Path Parameters - **realm** (string) - Required - The protocol and domain of your website (e.g., 'https://example.com'). ### Request Example ```javascript const SteamSignIn = require('steam-signin'); // For production HTTPS site const signIn = new SteamSignIn('https://example.com'); // For local development const signIn = new SteamSignIn('http://localhost'); ``` ### Response N/A (This is a constructor) ### Error Handling - Throws an error if the realm includes a port or path. ``` -------------------------------- ### Instantiate SteamSignIn with Realm (JavaScript) Source: https://github.com/doctormckay/node-steam-signin/blob/master/README.md Shows how to create a new instance of the SteamSignIn class. The 'realm' parameter, which is your domain and protocol (http or https), is required. ```javascript let signIn = new SteamSignIn('https://example.com'); ``` -------------------------------- ### Method: getUrl(returnUrl) Source: https://context7.com/doctormckay/node-steam-signin/llms.txt Generates the Steam OpenID authentication URL. Users should be redirected to this URL to initiate the Steam sign-in process. The 'returnUrl' must match the realm provided during initialization. ```APIDOC ## Method: getUrl(returnUrl) ### Description Generates the Steam OpenID authentication URL where users should be redirected to sign in. ### Method GET ### Endpoint N/A (This is a method of the SteamSignIn instance) ### Parameters #### Query Parameters - **returnUrl** (string) - Required - The URL Steam will redirect to after authentication. Must be on the same domain and protocol as the realm. ### Request Example ```javascript const SteamSignIn = require('steam-signin'); const signIn = new SteamSignIn('https://example.com'); // Get authentication URL const authUrl = signIn.getUrl('https://example.com/auth/callback'); console.log(authUrl); // Output: https://steamcommunity.com/openid/login?openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.identity=... // In Express.js route handler app.get('/auth/steam', (req, res) => { const returnUrl = `https://example.com/auth/callback`; const steamLoginUrl = signIn.getUrl(returnUrl); res.redirect(steamLoginUrl); }); ``` ### Response #### Success Response (200) - **authUrl** (string) - The generated Steam OpenID login URL. #### Response Example ```json { "authUrl": "https://steamcommunity.com/openid/login?openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.identity=..." } ``` ### Error Handling - Returns an error if the `returnUrl` protocol or domain does not match the `realm`. ``` -------------------------------- ### Initialize SteamSignIn Instance Source: https://context7.com/doctormckay/node-steam-signin/llms.txt Creates a new instance of SteamSignIn, which is used to manage the Steam OpenID authentication flow. The 'realm' parameter is crucial for security and must strictly follow the protocol and domain, excluding ports or paths. Invalid realms will result in errors. ```javascript const SteamSignIn = require('steam-signin'); // For production HTTPS site const signIn = new SteamSignIn('https://example.com'); // For local development const signIn = new SteamSignIn('http://localhost'); // Realm must be protocol + domain only, no paths or ports // These will throw errors: // new SteamSignIn('https://example.com:3000'); // ❌ includes port // new SteamSignIn('https://example.com/auth'); // ❌ includes path ``` -------------------------------- ### Import SteamSignIn Class (JavaScript) Source: https://github.com/doctormckay/node-steam-signin/blob/master/README.md Demonstrates how to import the SteamSignIn class using both CommonJS and ES6 module syntax. This is the first step in using the module. ```javascript // CommonJS const SteamSignIn = require('steam-signin'); // ES6 Modules import SteamSignIn from 'steam-signin'; ``` -------------------------------- ### Method: verifyLogin(url) Source: https://context7.com/doctormckay/node-steam-signin/llms.txt Verifies the authentication response from Steam after the user has logged in. It returns the authenticated user's SteamID if the login is valid and secure. This method can accept either the full callback URL or just the path. ```APIDOC ## Method: verifyLogin(url) ### Description Verifies the authentication response from Steam and returns the authenticated user's SteamID. ### Method GET ### Endpoint N/A (This is a method of the SteamSignIn instance) ### Parameters #### Query Parameters - **url** (string) - Required - The full callback URL or just the path received from Steam after user authentication. ### Request Example ```javascript const SteamSignIn = require('steam-signin'); const signIn = new SteamSignIn('https://example.com'); // In Express.js callback route app.get('/auth/callback', async (req, res) => { try { // Pass the full callback URL or just the path const steamId = await signIn.verifyLogin(req.url); // steamId is a SteamID object from the 'steamid' package console.log(`SteamID64: ${steamId.getSteamID64()}`); console.log(`Steam3 format: ${steamId.steam3()}`); console.log(`Profile URL: ${steamId.getProfileURL()}`); // Store in session req.session.steamId = steamId.getSteamID64(); res.redirect('/dashboard'); } catch (error) { // Verification failed - forged, reused, or invalid token console.error('Login verification failed:', error.message); res.status(401).send('Authentication failed'); } }); // Works with full URL or path only // ✅ await signIn.verifyLogin('/auth/callback?openid.mode=id_res&...') // ✅ await signIn.verifyLogin('https://example.com/auth/callback?openid.mode=...') ``` ### Response #### Success Response (200) - **steamId** (object) - A SteamID object containing user information (e.g., getSteamID64(), steam3(), getProfileURL()). #### Response Example ```json { "steamId": { "steamId64": "76198370000000001", "steam3": "[U:1:123456789]", "profileUrl": "https://steamcommunity.com/profiles/76198370000000001" } } ``` ### Error Handling - Throws an error if the login verification fails due to a forged, reused, or invalid token. ``` -------------------------------- ### Express.js Integration with Steam Authentication and Profile Fetching Source: https://context7.com/doctormckay/node-steam-signin/llms.txt This snippet demonstrates a full Express.js application implementing Steam authentication using express-session. It includes routes for signing in, handling the Steam callback, displaying user profile information fetched from the Steam Web API, and logging out. It requires the 'express', 'express-session', and 'steam-signin' packages. ```javascript const express = require('express'); const session = require('express-session'); const SteamSignIn = require('steam-signin'); const app = express(); const signIn = new SteamSignIn('https://example.com'); const STEAM_API_KEY = 'YOUR_API_KEY'; // Get from https://steamcommunity.com/dev/apikey // Session middleware app.use(session({ secret: 'your-secret-key', resave: false, saveUninitialized: true, cookie: { secure: true, maxAge: 3600000 } })); // Authentication middleware app.use((req, res, next) => { const publicPaths = ['/', '/auth/steam', '/auth/callback']; if (publicPaths.includes(req.path) || req.session.steamId) { next(); } else { res.redirect('/'); } }); // Home page app.get('/', (req, res) => { if (req.session.steamId) { res.send( `
Logged in as: ${req.session.steamId}
\n View Profile |\n Logout` ); } else { res.send('Sign in with Steam'); } }); // Redirect to Steam app.get('/auth/steam', (req, res) => { const returnUrl = 'https://example.com/auth/callback'; res.redirect(signIn.getUrl(returnUrl)); }); // Steam callback app.get('/auth/callback', async (req, res) => { try { const steamId = await signIn.verifyLogin(req.url); req.session.steamId = steamId.getSteamID64(); res.redirect('/profile'); } catch (error) { res.status(401).send(`Login failed: ${error.message}`); } }); // Fetch and display profile using Steam Web API app.get('/profile', async (req, res) => { const steamId = req.session.steamId; const apiUrl = `https://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=${STEAM_API_KEY}&steamids=${steamId}`; try { const response = await fetch(apiUrl); const data = await response.json(); const player = data.response.players[0]; res.send( `SteamID: ${player.steamid}
\nProfile: ${player.profileurl}
\nStatus: ${player.personastate === 1 ? 'Online' : 'Offline'}
\nAccount created: ${new Date(player.timecreated * 1000).toLocaleDateString()}
` ); } catch (error) { res.status(500).send('Failed to fetch profile'); } }); // Logout app.get('/auth/logout', (req, res) => { req.session.destroy(); res.redirect('/'); }); app.listen(3000); ``` -------------------------------- ### Generate Steam Authentication URL Source: https://context7.com/doctormckay/node-steam-signin/llms.txt Generates the unique Steam OpenID authentication URL. Users must be redirected to this URL to initiate the sign-in process. The 'returnUrl' provided must be a valid path on the configured realm to ensure proper verification upon callback. ```javascript const SteamSignIn = require('steam-signin'); const signIn = new SteamSignIn('https://example.com'); // Get authentication URL const authUrl = signIn.getUrl('https://example.com/auth/callback'); console.log(authUrl); // Output: https://steamcommunity.com/openid/login?openid.claimed_id=http%3A%2F%2Fspecs.openid.net%2Fauth%2F2.0%2Fidentifier_select&openid.identity=... // In Express.js route handler app.get('/auth/steam', (req, res) => { const returnUrl = `https://example.com/auth/callback`; const steamLoginUrl = signIn.getUrl(returnUrl); res.redirect(steamLoginUrl); }); // Return URL must match the realm // ✅ Valid: https://example.com/any/path // ❌ Invalid: https://different-domain.com/path (realm mismatch) // ❌ Invalid: http://example.com/path (protocol mismatch) ``` -------------------------------- ### TypeScript Usage for Steam Authentication Source: https://context7.com/doctormckay/node-steam-signin/llms.txt This snippet illustrates how to use the steam-signin library in a TypeScript environment. It shows how to import the library, instantiate the SteamSignIn class, and obtain the Steam authentication URL. It also includes an asynchronous function to verify the login callback and handle potential errors. Requires '@types/steamid' for SteamID type definitions. ```typescript import SteamSignIn from 'steam-signin'; import type SteamID from 'steamid'; const signIn: SteamSignIn = new SteamSignIn('https://example.com'); // Get authentication URL const authUrl: string = signIn.getUrl('https://example.com/callback'); // Verify login async function handleCallback(returnUrl: string): Promise