### Install and Initialize Prismarine Auth Source: https://context7.com/prismarinejs/prismarine-auth/llms.txt Demonstrates how to install the prismarine-auth library via npm and perform basic initialization using the default device code authentication flow. This setup automatically caches tokens for subsequent use. ```javascript const { Authflow, Titles } = require('prismarine-auth') // Install via npm // npm install prismarine-auth // Basic initialization with device code auth (default) const userIdentifier = 'unique-user-id' const cacheDir = './.auth-cache' const flow = new Authflow(userIdentifier, cacheDir) // The library will prompt for device code authentication on first use // Subsequent calls will use cached tokens automatically ``` -------------------------------- ### Prismarine Auth: Implementing an In-Memory Cache Source: https://github.com/prismarinejs/prismarine-auth/blob/master/docs/API.md Provides an example of creating a custom in-memory cache for Prismarine Auth. This implementation includes methods for getting, setting, and partially setting cached data, adhering to the required interface. ```typescript // Return the stored value, this can be called multiple times getCached(): Promise // Replace the stored value setCached(value: any): Promise // Replace an part of the stored value. Implement this using the spread operator setCachedPartial(value: any): Promise ``` ```javascript class InMemoryCache { private cache = {} async reset () { // (should clear the data in the cache like a first run) } async getCached () { return this.cache } async setCached (value) { this.cache = value } async setCachedPartial (value) { this.cache = { ...this.cache, ...value } } } function cacheFactory ({ username, cacheName }) { return new InMemoryCache() } // Passed like `new Authflow('bob', cacheFactory, ...)` ``` -------------------------------- ### Install prismarine-auth Source: https://github.com/prismarinejs/prismarine-auth/blob/master/README.md Installs the prismarine-auth library using npm. This is the initial step to begin using the authentication functionalities provided by the library. ```shell npm install prismarine-auth ``` -------------------------------- ### Get Minecraft Java Edition Token with prismarine-auth Source: https://github.com/prismarinejs/prismarine-auth/blob/master/README.md Retrieves a Minecraft Java Edition authentication token. This example initializes Authflow and then calls getMinecraftJavaToken(), optionally fetching profile information. The response includes the token, entitlements, and player profile details. ```javascript const { Authflow, Titles } = require('prismarine-auth') const userIdentifier = 'any unique identifier' const cacheDir = './' // You can leave this as undefined unless you want to specify a caching directory const flow = new Authflow(userIdentifier, cacheDir) // Get a Minecraft Java Edition auth token, then log it flow.getMinecraftJavaToken({ fetchProfile: true }).then(console.log) ``` -------------------------------- ### Custom Token Cache Implementation with Prismarine-Auth (JavaScript) Source: https://context7.com/prismarinejs/prismarine-auth/llms.txt Demonstrates how to implement custom token cache storage backends for Prismarine-Auth. Includes a `DatabaseCache` example using a hypothetical `database` object and an in-memory `MemoryCache`. These custom caches can be integrated with `Authflow` via a factory function. ```javascript const { Authflow } = require('prismarine-auth') // Custom cache class implementing required interface class DatabaseCache { constructor(username, cacheName) { this.key = `auth:${username}:${cacheName}` } async reset() { // Clear cache data (called on forceRefresh) await database.delete(this.key) } async getCached() { // Retrieve cached tokens const data = await database.get(this.key) return data ? JSON.parse(data) : {} } async setCached(value) { // Store complete token cache await database.set(this.key, JSON.stringify(value)) } async setCachedPartial(value) { // Merge partial update with existing cache const existing = await this.getCached() await this.setCached({ ...existing, ...value }) } } // Cache factory function function cacheFactory({ username, cacheName }) { console.log(`Creating cache for ${username} (${cacheName})`) return new DatabaseCache(username, cacheName) } // Use custom cache with Authflow const flow = new Authflow('user123', cacheFactory, { flow: 'live', authTitle: Titles.MinecraftNintendoSwitch, deviceType: 'Nintendo' }) flow.getMinecraftJavaToken({ fetchProfile: true }) .then(result => { console.log('Token cached in custom storage') console.log('Player:', result.profile.name) }) // In-memory cache example (no persistence) class MemoryCache { constructor() { this.data = {} } async reset() { this.data = {} } async getCached() { return this.data } async setCached(value) { this.data = value } async setCachedPartial(value) { this.data = { ...this.data, ...value } } } const memoryCacheFactory = () => new MemoryCache() const memoryFlow = new Authflow('user123', memoryCacheFactory) ``` -------------------------------- ### Get Microsoft Account (MSA) Token with prismarine-auth Source: https://github.com/prismarinejs/prismarine-auth/blob/master/README.md Obtains a Microsoft Account (MSA) token using the Authflow class. This example demonstrates initializing Authflow with a user identifier and cache directory, then calling getMsaToken() to retrieve the token. It's suitable for general Microsoft authentication and can be configured for specific flows like 'msal' with an authTitle for non-Minecraft applications. ```javascript const { Authflow, Titles } = require('prismarine-auth') const userIdentifier = 'unique identifier for caching' const cacheDir = './' // You can leave this as undefined unless you want to specify a caching directory const flow = new Authflow(userIdentifier, cacheDir) // Get a auth token, then log it flow.getMsaToken().then(console.log) // Example for MSAL flow: // const flow = new Authflow(userIdentifier, cacheDir, { flow: 'msal', authTitle: '000-000-000-000' }) // flow.getMsaToken().then(console.log) ``` -------------------------------- ### Access Available Title Constants in JavaScript Source: https://context7.com/prismarinejs/prismarine-auth/llms.txt Shows how to access and utilize built-in client IDs (Titles) provided by prismarine-auth for various Microsoft services, including Minecraft and Xbox platforms. This example demonstrates logging these constants and using them to configure authentication flows with appropriate device types. ```javascript const { Titles } = require('prismarine-auth'); // Minecraft platform titles console.log('Nintendo Switch:', Titles.MinecraftNintendoSwitch); // '00000000441cc96b' console.log('PlayStation:', Titles.MinecraftPlaystation); // '000000004827c78e' console.log('Android:', Titles.MinecraftAndroid); // '0000000048183522' console.log('Java Edition:', Titles.MinecraftJava); // '00000000402b5328' console.log('iOS:', Titles.MinecraftIOS); // '000000004c17c01a' // Xbox platform titles console.log('Xbox App iOS:', Titles.XboxAppIOS); // '000000004c12ae6f' console.log('Xbox Gamepass iOS:', Titles.XboxGamepassIOS); // '000000004c20a908' // Usage with appropriate device types const configs = [ { title: Titles.MinecraftNintendoSwitch, device: 'Nintendo' }, { title: Titles.MinecraftPlaystation, device: 'PlayStation' }, { title: Titles.MinecraftAndroid, device: 'Android' }, { title: Titles.MinecraftJava, device: 'Win32' }, { title: Titles.MinecraftIOS, device: 'iOS' }, { title: Titles.XboxAppIOS, device: 'iOS' } ]; configs.forEach(config => { console.log(`Title ${config.title} uses device type: ${config.device}`); }) ``` -------------------------------- ### Get Microsoft Account (MSA) Token via Device Code Auth Source: https://context7.com/prismarinejs/prismarine-auth/llms.txt This snippet shows how to obtain a Microsoft Account OAuth access token using the 'live' flow. It covers standard device code authentication and includes an example of a custom callback for displaying the device code to the user. Tokens are cached and refreshed automatically. ```javascript const { Authflow, Titles } = require('prismarine-auth') const flow = new Authflow('user123', './.cache', { flow: 'live', authTitle: Titles.MinecraftNintendoSwitch, deviceType: 'Nintendo' }) // Get MSA token with device code authentication flow.getMsaToken() .then(token => { console.log('Microsoft Access Token:', token) // Token is a JWT string: eyJhbGciOiJSUzI1NiIsImtpZCI6... // Valid for 1 hour, automatically cached and refreshed }) .catch(error => { console.error('Authentication failed:', error.message) }) // Custom callback for device code display const customFlow = new Authflow( 'user123', './.cache', { flow: 'live', authTitle: Titles.MinecraftNintendoSwitch, deviceType: 'Nintendo' }, (response) => { console.log(`Go to ${response.verification_uri} and enter code: ${response.user_code}`) console.log(`Code expires in ${response.expires_in} seconds`) } ) ``` -------------------------------- ### Get Minecraft Java Token with Profile and Entitlements (JavaScript) Source: https://context7.com/prismarinejs/prismarine-auth/llms.txt Obtains a Minecraft Java Edition authentication token along with full profile data, entitlements (game ownership), and certificates for chat signing (1.19+). Requires 'prismarine-auth'. Handles success by logging token and details, or failure with specific error messages. ```javascript const { Authflow, Titles } = require('prismarine-auth') const flow = new Authflow('player123', './.cache', { flow: 'live', authTitle: Titles.MinecraftNintendoSwitch, deviceType: 'Nintendo' }) // Get Minecraft Java token with full profile and entitlements flow.getMinecraftJavaToken({ fetchProfile: true, fetchEntitlements: true, fetchCertificates: true }) .then(result => { console.log('Minecraft Token:', result.token) // Profile information if (result.profile) { console.log('UUID:', result.profile.id) console.log('Username:', result.profile.name) console.log('Skins:', result.profile.skins) console.log('Capes:', result.profile.capes) } // Entitlements (game ownership) if (result.entitlements) { console.log('Entitlements:', result.entitlements.items) } // Certificates for chat signing (1.19+) if (result.certificates) { console.log('Public Key:', result.certificates.profileKeys.publicPEM) console.log('Expires:', result.certificates.expiresOn) } // Use token to connect to Minecraft servers // Token format: eyJhbGciOiJIUzI1NiJ9... }) .catch(error => { if (error.message.includes('entitlements')) { console.error('Account does not own Minecraft') } else { console.error('Authentication failed:', error.message) } }) // Minimal token fetch (no additional requests) flow.getMinecraftJavaToken() .then(result => { console.log('Token only:', result.token) }) ``` -------------------------------- ### Get Xbox Live XSTS Token Source: https://context7.com/prismarinejs/prismarine-auth/llms.txt This example demonstrates how to acquire Xbox Live XSTS tokens, which are necessary for accessing Xbox Live services. It shows obtaining a token with the default relying party, using a custom relying party for specific services like Minecraft Bedrock, and forcing a token refresh to bypass the cache. ```javascript const { Authflow } = require('prismarine-auth') const flow = new Authflow('user123', './.cache') // Get Xbox token with default relying party flow.getXboxToken() .then(result => { console.log('Xbox User XUID:', result.userXUID) console.log('User Hash:', result.userHash) console.log('XSTS Token:', result.XSTSToken) console.log('Expires On:', new Date(result.expiresOn)) // Expected output structure: // { // userXUID: '2535405290510448', // userHash: 'abcd1234567890', // XSTSToken: 'eyJhbGciOiJSUzI1NiIsImtpZCI6...', // expiresOn: 1700000000000 // } }) .catch(error => { console.error('Xbox authentication failed:', error.message) }) // Get token with custom relying party for specific services const relyingParty = 'https://multiplayer.minecraft.net/' flow.getXboxToken(relyingParty, false) .then(result => { console.log('Bedrock Xbox token obtained for', relyingParty) }) // Force token refresh (bypass cache) flow.getXboxToken('http://xboxlive.com', true) .then(result => { console.log('Fresh Xbox token:', result.XSTSToken) }) ``` -------------------------------- ### Get Minecraft Bedrock Services Token (JavaScript) Source: https://context7.com/prismarinejs/prismarine-auth/llms.txt Retrieves an MCToken for Minecraft services and NetherNet WebRTC signaling. Requires 'prismarine-auth'. The result includes the mcToken, its validity period, feature treatments, and configuration parameters. Useful for WebSocket authentication or querying service APIs. ```javascript const { Authflow, Titles } = require('prismarine-auth') const flow = new Authflow('user123', './.cache', { flow: 'live', authTitle: Titles.MinecraftNintendoSwitch, deviceType: 'Nintendo' }) flow.getMinecraftBedrockServicesToken({ version: '1.21.50' }) .then(result => { console.log('MC Token:', result.mcToken) console.log('Valid Until:', result.validUntil) console.log('Treatment Count:', result.treatments.length) // Feature flags and treatments console.log('Enabled Features:', result.treatments.slice(0, 5)) // Example: ['mc-enable-feedback-landing-page', 'mc-store-enableinbox', ...] // Configuration parameters console.log('Configurations:', Object.keys(result.configurations)) if (result.configurations.minecraft) { console.log('Minecraft Config:', result.configurations.minecraft.parameters) } // Treatment context for A/B testing console.log('Treatment Context:', result.treatmentContext.substring(0, 50) + '...') // Use mcToken to authenticate WebSocket for NetherNet // or query minecraft-services.net/api endpoints }) .catch(error => { console.error('Failed to get services token:', error.message) }) ``` -------------------------------- ### Get Minecraft Java Edition Token with Entitlements and Profile Source: https://github.com/prismarinejs/prismarine-auth/blob/master/docs/API.md Retrieves a Minecraft Java Edition authentication token. Optionally fetches user entitlements to verify Minecraft ownership and user profile information. Returns undefined for entitlements or profile if the respective API calls fail. ```javascript const { Authflow } = require('prismarine-auth'); async function getJavaToken(username, cacheDir) { const authServer = 'https://authserver.mojang.com'; const authJava = 'https://sessionserver.mojang.com'; const flow = new Authflow({ username: username, cacheDir: cacheDir || './.minecraft_tokens', authServer: authServer, authJava: authJava, token: null, // This is not needed for getMinecraftJavaToken flow: 'msal' // or 'live' or 'sisu' }); try { const { token, entitlements, profile } = await flow.getMinecraftJavaToken({ fetchEntitlements: true, fetchProfile: true }); console.log('Minecraft Java Token:', token); console.log('Entitlements:', entitlements); console.log('Profile:', profile); return { token, entitlements, profile }; } catch (err) { console.error('Error getting Minecraft Java token:', err); return null; } } // Example usage: // getJavaToken('your_minecraft_email@example.com', './path/to/cache').then(data => console.log(data)); ``` -------------------------------- ### Get Minecraft Bedrock Services Token Source: https://github.com/prismarinejs/prismarine-auth/blob/master/docs/API.md Fetches an mctoken necessary for querying the minecraft-services.net API and for authenticating WebSocket connections in the NetherNet WebRTC signalling channel. The response includes the mcToken and user treatment information related to feature access. ```javascript const { Authflow } = require('prismarine-auth'); async function getBedrockServicesToken(username, cacheDir, mcVersion) { const authServer = 'https://authserver.mojang.com'; const authJava = 'https://sessionserver.mojang.com'; const flow = new Authflow({ username: username, cacheDir: cacheDir || './.minecraft_tokens', authServer: authServer, authJava: authJava, token: null, flow: 'msal' // or 'live' or 'sisu' }); try { const servicesTokenResponse = await flow.getMinecraftBedrockServicesToken({ version: mcVersion }); console.log('Minecraft Bedrock Services Token Response:', servicesTokenResponse); // The mcToken is available in servicesTokenResponse.mcToken return servicesTokenResponse; } catch (err) { console.error('Error getting Minecraft Bedrock services token:', err); return null; } } // Example usage: // getBedrockServicesToken('your_minecraft_email@example.com', './path/to/cache', '1.20.0').then(data => console.log(data)); ``` -------------------------------- ### Get Minecraft Bedrock Services Token with prismarine-auth Source: https://github.com/prismarinejs/prismarine-auth/blob/master/README.md Obtains a Minecraft Bedrock services token. This function provides a token necessary for accessing various Minecraft Bedrock services. The response includes the token, its validity period, and associated treatments and configurations. ```javascript const { Authflow, Titles } = require('prismarine-auth') const userIdentifier = 'any unique identifier' const cacheDir = './' // You can leave this as undefined unless you want to specify a caching directory const flow = new Authflow(userIdentifier, cacheDir) // Get a Minecraft Services token, then log it flow.getMinecraftBedrockServicesToken().then(console.log) ``` -------------------------------- ### Azure MSAL Authentication Flow Source: https://context7.com/prismarinejs/prismarine-auth/llms.txt This section illustrates how to authenticate using Azure Active Directory (Azure AD) with custom applications via the MSAL flow. It includes examples for using a standard Azure client ID and advanced configuration with custom MSAL settings, providing guidance on registering new applications if needed. ```javascript const { Authflow } = require('prismarine-auth') // Using Azure client ID with MSAL flow const azureClientId = '00000000-0000-0000-0000-000000000000' const flow = new Authflow('user@example.com', './.cache', { flow: 'msal', authTitle: azureClientId }) flow.getXboxToken() .then(result => { console.log('Authenticated with Azure app') console.log('XUID:', result.userXUID) console.log('Token:', result.XSTSToken) }) .catch(error => { if (error.message.includes('client ID')) { console.error('Invalid Azure client ID. Register your app at:') console.error('https://learn.microsoft.com/en-us/entra/identity-platform/quickstart-register-app') } else { console.error('MSAL authentication failed:', error.message) } }) // Advanced: Custom MSAL configuration const customMsalConfig = { auth: { clientId: azureClientId, authority: 'https://login.microsoftonline.com/consumers' } } const customFlow = new Authflow('user@example.com', './.cache', { flow: 'msal', msalConfig: customMsalConfig }) ``` -------------------------------- ### Password-Based Authentication for Microsoft Accounts Source: https://context7.com/prismarinejs/prismarine-auth/llms.txt This example demonstrates password-based authentication using a Microsoft account. It's important to note that this method may be unreliable due to factors like two-factor authentication, security verification requirements, or changes in Microsoft's policies. The output includes the XSTS Token upon successful authentication. ```javascript const { Authflow } = require('prismarine-auth') // Password auth does not require authTitle const flow = new Authflow('user@example.com', './.cache', { flow: 'live', password: 'your-password-here' }) flow.getXboxToken() .then(result => { console.log('Authenticated with password') console.log('XSTS Token:', result.XSTSToken) }) .catch(error => { if (error.message.includes('credentials')) { console.error('Invalid username or password') } else if (error.message.includes('2FA') || error.message.includes('verification')) { console.error('Account requires two-factor authentication') console.error('Password auth not supported for 2FA accounts') } else { console.error('Password authentication failed:', error.message) } }) // Note: Password authentication may fail with: // - Accounts with 2FA enabled // - Accounts requiring security verification // - Microsoft policy changes // Device code authentication is more reliable ``` -------------------------------- ### Get Minecraft Bedrock Edition Chain Tokens (JavaScript) Source: https://context7.com/prismarinejs/prismarine-auth/llms.txt Generates Minecraft Bedrock Edition chain tokens, including Xbox Live identity and Mojang/Xbox authentication tokens. Requires 'prismarine-auth' and Node.js 'crypto' module for ECDH key pair generation. Outputs JWT chain length and decoded token details like titleId and XUID. ```javascript const { Authflow, Titles } = require('prismarine-auth') const crypto = require('crypto') // Generate ECDH key pair for encryption const keypair = crypto.generateKeyPairSync('ec', { namedCurve: 'secp384r1' }) const publicKey = keypair.publicKey const flow = new Authflow('bedrockPlayer', './.cache', { flow: 'live', authTitle: Titles.MinecraftNintendoSwitch, deviceType: 'Nintendo' }) flow.getMinecraftBedrockToken(publicKey) .then(chain => { console.log('JWT Chain Length:', chain.length) console.log('Identity Chain:', chain[0]) console.log('Mojang Chain:', chain[1]) // Chain contains JWT tokens for Bedrock authentication // chain[0]: Xbox Live identity token // chain[1]: Mojang/Xbox authentication token with titleId // Decode to verify titleId presence (for realm access) const decoded = JSON.parse( Buffer.from(chain[1].split('.')[1], 'base64').toString() ) console.log('Title ID:', decoded.extraData.titleId) console.log('XUID:', decoded.extraData.XUID) console.log('Display Name:', decoded.extraData.displayName) }) .catch(error => { if (error.message.includes('titleId')) { console.error('Title authentication failed - missing titleId') } else if (error.message.includes('public key')) { console.error('Invalid ECDH public key provided') } else { console.error('Bedrock authentication failed:', error.message) } }) ``` -------------------------------- ### Prismarine Auth: Using Predefined Client IDs Source: https://github.com/prismarinejs/prismarine-auth/blob/master/docs/API.md Demonstrates how to use predefined client IDs for authentication with Prismarine Auth. It shows the import statement and the instantiation of Authflow with a specific device type and flow. ```javascript const { Authflow, Titles } = require('prismarine-auth') const flow = new Authflow('', './', { authTitle: Titles.MinecraftNintendoSwitch, deviceType: 'Nintendo', flow: 'live' }) flow.getMinecraftJavaToken().then(console.log) ``` -------------------------------- ### Initialize and Use Authflow for Xbox Token Source: https://github.com/prismarinejs/prismarine-auth/blob/master/docs/API.md Demonstrates how to create an instance of the Authflow class and obtain an Xbox Live token. The Authflow class manages token caching internally. This method requires no parameters for basic initialization. ```javascript const { Authflow } = require('prismarine-auth') const flow = new Authflow() // No parameters needed flow.getXboxToken().then(console.log) ``` -------------------------------- ### Enable Debug Logging for Prismarine-Auth (JavaScript) Source: https://context7.com/prismarinejs/prismarine-auth/llms.txt Shows how to enable debug logging for Prismarine-Auth to aid in troubleshooting authentication issues. Debugging can be enabled globally by setting the `DEBUG` environment variable or programmatically using the `debug` module. ```javascript // Enable debug logging at the start of your application process.env.DEBUG = 'prismarine-auth' const { Authflow, Titles } = require('prismarine-auth') const flow = new Authflow('user123', './.cache', { flow: 'live', authTitle: Titles.MinecraftNintendoSwitch, deviceType: 'Nintendo' }) flow.getMinecraftJavaToken({ fetchProfile: true }) .then(result => { console.log('Authentication successful') // Debug output will show: // prismarine-auth [msa] Using existing tokens +0ms // prismarine-auth [xbl] Using existing XSTS token +5ms // prismarine-auth [mc] Using existing tokens +2ms }) .catch(error => { console.error('Error:', error.message) // Debug output shows detailed error context and retry attempts }) // Or enable programmatically const debug = require('debug') debug.enable('prismarine-auth') // Debug shows: // - Token cache hits/misses // - API request attempts // - Retry logic execution // - Token expiration checks // - Authentication flow steps ``` -------------------------------- ### Enable Debugging with DEBUG Environment Variable Source: https://github.com/prismarinejs/prismarine-auth/blob/master/README.md This snippet shows how to enable debugging output for Prismarine-Auth by setting the DEBUG environment variable. This is useful for troubleshooting issues. The code should be placed at the top of your Node.js application. ```javascript process.env.DEBUG = 'prismarine-auth' ``` -------------------------------- ### Obtain PlayFab Session Ticket for Minecraft Source: https://context7.com/prismarinejs/prismarine-auth/llms.txt This code snippet demonstrates how to obtain a PlayFab session ticket for Minecraft game services using the prismarine-auth library. It requires specifying the authentication flow, cache directory, and auth title. The output includes session ticket, PlayFab ID, account information, and entity token details. ```javascript const { Authflow, Titles } = require('prismarine-auth') const flow = new Authflow('user123', './.cache', { flow: 'live', authTitle: Titles.MinecraftNintendoSwitch, deviceType: 'Nintendo' }) flow.getPlayfabLogin() .then(result => { console.log('Session Ticket:', result.SessionTicket) console.log('PlayFab ID:', result.PlayFabId) console.log('Newly Created:', result.NewlyCreated) // Account information console.log('Xbox User ID:', result.InfoResultPayload.AccountInfo.XboxInfo.XboxUserId) console.log('Created:', result.InfoResultPayload.AccountInfo.Created) console.log('Last Login:', result.InfoResultPayload.AccountInfo.TitleInfo.LastLogin) // Entity token for PlayFab services console.log('Entity Token:', result.EntityToken.EntityToken) console.log('Token Expiration:', result.EntityToken.TokenExpiration) console.log('Entity ID:', result.EntityToken.Entity.Id) console.log('Entity Type:', result.EntityToken.Entity.TypeString) // Settings console.log('Needs Attribution:', result.SettingsForUser.NeedsAttribution) console.log('Gather Device Info:', result.SettingsForUser.GatherDeviceInfo) // Use SessionTicket for PlayFab API calls or MCToken generation }) .catch(error => { console.error('PlayFab login failed:', error.message) }) ``` -------------------------------- ### Minecraft Java Edition Authentication Source: https://context7.com/prismarinejs/prismarine-auth/llms.txt Obtain Minecraft Java Edition authentication tokens with profile data. This endpoint supports fetching full profile information, entitlements (game ownership), and certificates for chat signing. ```APIDOC ## Minecraft Java Edition Authentication ### Description Obtain Minecraft Java Edition authentication tokens with profile data. This endpoint supports fetching full profile information, entitlements (game ownership), and certificates for chat signing. ### Method GET (Implicit, through library function) ### Endpoint N/A (Library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const { Authflow, Titles } = require('prismarine-auth') const flow = new Authflow('player123', './.cache', { flow: 'live', authTitle: Titles.MinecraftNintendoSwitch, deviceType: 'Nintendo' }) // Get Minecraft Java token with full profile and entitlements flow.getMinecraftJavaToken({ fetchProfile: true, fetchEntitlements: true, fetchCertificates: true }) .then(result => { console.log('Minecraft Token:', result.token) // Profile information if (result.profile) { console.log('UUID:', result.profile.id) console.log('Username:', result.profile.name) console.log('Skins:', result.profile.skins) console.log('Capes:', result.profile.capes) } // Entitlements (game ownership) if (result.entitlements) { console.log('Entitlements:', result.entitlements.items) } // Certificates for chat signing (1.19+) if (result.certificates) { console.log('Public Key:', result.certificates.profileKeys.publicPEM) console.log('Expires:', result.certificates.expiresOn) } }) .catch(error => { console.error('Authentication failed:', error.message) }) ``` ### Response #### Success Response (200) - **token** (string) - The authentication token for Minecraft Java Edition. - **profile** (object, optional) - Contains profile information including UUID, username, skins, and capes. - **entitlements** (object, optional) - Contains information about owned game entitlements. - **certificates** (object, optional) - Contains certificates for chat signing (for Minecraft 1.19+). #### Response Example ```json { "token": "eyJhbGciOiJIUzI1NiJ9...", "profile": { "id": "uuid-of-player", "name": "PlayerName", "skins": [...], "capes": [...] }, "entitlements": { "items": [...] }, "certificates": { "profileKeys": { "publicPEM": "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----" }, "expiresOn": "2024-12-31T23:59:59Z" } } ``` ``` -------------------------------- ### Minecraft Bedrock Services Token Source: https://context7.com/prismarinejs/prismarine-auth/llms.txt Obtain MCToken for Minecraft services and NetherNet WebRTC signaling. This endpoint provides a token valid for a specific duration and includes feature flags, treatments, and configurations. ```APIDOC ## Minecraft Bedrock Services Token ### Description Obtain MCToken for Minecraft services and NetherNet WebRTC signaling. This endpoint provides a token valid for a specific duration and includes feature flags, treatments, and configurations. ### Method POST (Implicit, through library function) ### Endpoint N/A (Library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **version** (string) - Required - The version of Minecraft Bedrock Edition (e.g., '1.21.50'). ### Request Example ```javascript const { Authflow, Titles } = require('prismarine-auth') const flow = new Authflow('user123', './.cache', { flow: 'live', authTitle: Titles.MinecraftNintendoSwitch, deviceType: 'Nintendo' }) flow.getMinecraftBedrockServicesToken({ version: '1.21.50' }) .then(result => { console.log('MC Token:', result.mcToken) console.log('Valid Until:', result.validUntil) }) .catch(error => { console.error('Failed to get services token:', error.message) }) ``` ### Response #### Success Response (200) - **mcToken** (string) - The Minecraft services token. - **validUntil** (string) - The expiration date and time of the token. - **treatments** (array) - A list of enabled features and treatments. - **configurations** (object) - Configuration parameters for various Minecraft services. - **treatmentContext** (string) - Context for A/B testing. #### Response Example ```json { "mcToken": "your_mc_token_here", "validUntil": "2024-07-26T10:00:00Z", "treatments": [ "mc-enable-feedback-landing-page", "mc-store-enableinbox" ], "configurations": { "minecraft": { "parameters": {...} } }, "treatmentContext": "some_ab_test_context_string..." } ``` ``` -------------------------------- ### Handle Authentication Errors with Retry Logic in JavaScript Source: https://context7.com/prismarinejs/prismarine-auth/llms.txt Demonstrates how to handle authentication errors using prismarine-auth's built-in retry mechanisms. The library automatically retries transient failures twice with 2-second delays. This snippet also shows how to catch and differentiate various error types, such as XSTS, device code, entitlements, and network issues. ```javascript const { Authflow, Titles } = require('prismarine-auth'); const flow = new Authflow('user123', './.cache', { flow: 'live', authTitle: Titles.MinecraftNintendoSwitch, deviceType: 'Nintendo' }); // Library automatically retries on transient failures flow.getMinecraftJavaToken({ fetchProfile: true }) .then(result => { console.log('Success after potential retries'); console.log('Token:', result.token); }) .catch(error => { // Handle different error types if (error.message.includes('XSTS')) { console.error('Xbox Live authentication failed'); console.error('Possible causes: Invalid title ID, account restrictions'); } else if (error.message.includes('device code')) { console.error('Device code authentication failed'); console.error('User may have cancelled or code expired'); } else if (error.message.includes('entitlements')) { console.error('Account does not own Minecraft'); } else if (error.message.includes('network') || error.message.includes('timeout')) { console.error('Network error - check connectivity'); } else { console.error('Unexpected error:', error.message); console.error('Stack:', error.stack); } }); // The library retries twice with 2-second delays between attempts // Automatically refreshes MSA tokens if XSTS token generation fails ``` -------------------------------- ### Authenticate using Xbox SISU Flow for Mobile Apps Source: https://context7.com/prismarinejs/prismarine-auth/llms.txt This snippet shows how to authenticate using the Xbox SISU flow, suitable for mobile applications. It covers authenticating for Minecraft Java on Win32 devices and for the Xbox App on iOS. The result typically includes an XSTS token, user XUID, and user hash, or a Minecraft token and profile information. ```javascript const { Authflow, Titles } = require('prismarine-auth') // SISU flow for Minecraft Java with Win32 device const flow = new Authflow('user123', './.cache', { flow: 'sisu', authTitle: Titles.MinecraftJava, deviceType: 'Win32' }) flow.getXboxToken() .then(result => { console.log('SISU Xbox Token:', result.XSTSToken) console.log('User XUID:', result.userXUID) console.log('User Hash:', result.userHash) }) .catch(error => { if (error.message.includes('Forbidden')) { console.error('Invalid authTitle/deviceType combination for SISU flow') console.error('Ensure authTitle and deviceType are compatible') } else { console.error('SISU authentication failed:', error.message) } }) // SISU flow with Xbox App for iOS const iosFlow = new Authflow('user123', './.cache', { flow: 'sisu', authTitle: Titles.XboxAppIOS, deviceType: 'iOS' }) // SISU flow regenerates user, device, and title tokens together iosFlow.getMinecraftJavaToken({ fetchProfile: true }) .then(result => { console.log('Minecraft token via SISU:', result.token) console.log('Player name:', result.profile.name) }) ``` -------------------------------- ### Force Token Refresh with Prismarine-Auth (JavaScript) Source: https://context7.com/prismarinejs/prismarine-auth/llms.txt Illustrates how to force a refresh of all cached authentication tokens or specific token requests in Prismarine-Auth. This is achieved by setting the `forceRefresh` option to `true` during `Authflow` initialization or by passing `true` as a parameter to specific token retrieval methods. ```javascript const { Authflow, Titles } = require('prismarine-auth') // Enable forceRefresh option to clear cache const flow = new Authflow('user123', './.cache', { flow: 'live', authTitle: Titles.MinecraftNintendoSwitch, deviceType: 'Nintendo', forceRefresh: true // Clear all cached tokens }) // All token requests will fetch fresh tokens flow.getMinecraftJavaToken({ fetchProfile: true }) .then(result => { console.log('Fresh token obtained:', result.token) console.log('Profile:', result.profile.name) }) // Alternative: Force refresh on specific token request const normalFlow = new Authflow('user123', './.cache') // Normal cached request normalFlow.getXboxToken() .then(result => console.log('Cached token:', result.XSTSToken)) // Force refresh this specific request normalFlow.getXboxToken('http://xboxlive.com', true) .then(result => console.log('Fresh token:', result.XSTSToken)) ``` -------------------------------- ### Retrieve Playfab Login Response Source: https://github.com/prismarinejs/prismarine-auth/blob/master/docs/API.md Obtains a Playfab login response, which is crucial for authenticating with the Playfab API. The SessionTicket provided in this response is subsequently used for generating Minecraft authentication tokens (MCToken). ```javascript const { Authflow } = require('prismarine-auth'); async function getPlayfabData(username, cacheDir) { const authServer = 'https://authserver.mojang.com'; const authJava = 'https://sessionserver.mojang.com'; const flow = new Authflow({ username: username, cacheDir: cacheDir || './.minecraft_tokens', authServer: authServer, authJava: authJava, token: null, flow: 'msal' // or 'live' or 'sisu' }); try { const playfabResponse = await flow.getPlayfabLogin(); console.log('Playfab Login Response:', playfabResponse); // The SessionTicket can be extracted from playfabResponse.SessionTicket return playfabResponse; } catch (err) { console.error('Error getting Playfab login data:', err); return null; } } // Example usage: // getPlayfabData('your_minecraft_email@example.com', './path/to/cache').then(data => console.log(data)); ``` -------------------------------- ### Minecraft Bedrock Edition Authentication Source: https://context7.com/prismarinejs/prismarine-auth/llms.txt Obtain Minecraft Bedrock Edition chain tokens with ECDH key. This endpoint returns JWT tokens for Xbox Live identity and Mojang/Xbox authentication. ```APIDOC ## Minecraft Bedrock Edition Authentication ### Description Obtain Minecraft Bedrock Edition chain tokens with ECDH key. This endpoint returns JWT tokens for Xbox Live identity and Mojang/Xbox authentication. ### Method POST (Implicit, through library function) ### Endpoint N/A (Library function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript const { Authflow, Titles } = require('prismarine-auth') const crypto = require('crypto') // Generate ECDH key pair for encryption const keypair = crypto.generateKeyPairSync('ec', { namedCurve: 'secp384r1' }) const publicKey = keypair.publicKey const flow = new Authflow('bedrockPlayer', './.cache', { flow: 'live', authTitle: Titles.MinecraftNintendoSwitch, deviceType: 'Nintendo' }) flow.getMinecraftBedrockToken(publicKey) .then(chain => { console.log('JWT Chain Length:', chain.length) console.log('Identity Chain:', chain[0]) console.log('Mojang Chain:', chain[1]) }) .catch(error => { console.error('Bedrock authentication failed:', error.message) }) ``` ### Response #### Success Response (200) - **chain** (array) - An array containing JWT tokens for Bedrock authentication. - **chain[0]** (string) - Xbox Live identity token. - **chain[1]** (string) - Mojang/Xbox authentication token with titleId. #### Response Example ```json [ "eyJhbGciOiJSUzI1NiIsImtpZCI6...", "eyJhbGciOiJSUzI1NiIsImtpZCI6..." ] ``` ``` -------------------------------- ### Obtain Minecraft Bedrock Edition Auth Tokens Source: https://github.com/prismarinejs/prismarine-auth/blob/master/docs/API.md Generates authentication tokens for Minecraft Bedrock Edition. This function requires a Node.js KeyObject as input, typically used for cryptographic operations. The output consists of multiple JWTs obtained from both Mojang and Xbox authentication steps. ```javascript const { Authflow } = require('prismarine-auth'); const crypto = require('crypto'); async function getBedrockTokens(publicKey) { const authServer = 'https://authserver.mojang.com'; const authJava = 'https://sessionserver.mojang.com'; const flow = new Authflow({ username: 'your_minecraft_email@example.com', // Replace with actual username cacheDir: './.minecraft_tokens', // Replace with your cache directory authServer: authServer, authJava: authJava, token: null, flow: 'msal' // or 'live' or 'sisu' }); try { // Note: publicKey needs to be a valid Node.js KeyObject // Example: const publicKey = crypto.createPublicKey('...'); const jwtTokens = await flow.getMinecraftBedrockToken(publicKey); console.log('Minecraft Bedrock JWT Tokens:', jwtTokens); return jwtTokens; } catch (err) { console.error('Error getting Minecraft Bedrock tokens:', err); return null; } } // Example usage (requires a valid KeyObject): // const keyPair = crypto.generateKeyPairSync('rsa', { // modulusLength: 4096, // publicKeyEncoding: { // type: 'spki', // format: 'pem' // }, // privateKeyEncoding: { // type: 'pkcs8', // format: 'pem' // } // }); // getBedrockTokens(keyPair.publicKey).then(tokens => console.log(tokens)); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.