mojang-auth
Version:
Mojang authentication client, re-implementing parts of `node-yggdrasil` in classes, and adding support for custom auth servers.
59 lines (56 loc) • 2.7 kB
text/typescript
import { createHash } from 'crypto'
import utils from './utils';
import fetch from 'node-fetch'
import type { Agent } from 'http';
export let defaultHost = 'https://sessionserver.mojang.com';
export const setDefaultHost = (val: string) => {
defaultHost = val;
}
export default class Server {
constructor(options?: { defaultHost: string }) {
Object.assign(this, options);
}
/**
* Client's Mojang handshake call
* See http://wiki.vg/Protocol_Encryption#Client
* @param {String} accessToken Client's accessToken
* @param {String} selectedProfile Client's selectedProfile
* @param {String} serverid ASCII encoding of the server ID
* @param {String} sharedsecret Server's secret string
* @param {String} serverkey Server's encoded public key
* @param {Function} cb (is okay, data returned by server)
* @async
*/
async join(accessToken: string, selectedProfile: string, serverid: string, sharedsecret: string, serverkey: string) {
return await utils.call(
(this as any)?.host as string ??
defaultHost,
'session/minecraft/join',
{
accessToken,
selectedProfile,
serverId: utils.mcHexDigest(createHash('sha1').update(serverid).update(sharedsecret).update(serverkey).digest())
},
(this as any)?.agent as Agent
)
}
/**
* Server's Mojang handshake call
* @param {String} username Client's username, case-sensitive
* @param {String} serverid ASCII encoding of the server ID
* @param {String} sharedsecret Server's secret string
* @param {String} serverkey Server's encoded public key
* @param {Function} cb (is okay, client info)
* @async
*/
async hasJoined(username: string, serverid: string, sharedsecret: string, serverkey: string) {
const host = (this as any)?.host as string ?? defaultHost
const hash = utils.mcHexDigest(createHash('sha1').update(serverid).update(sharedsecret).update(serverkey).digest())
const data = await fetch(`${host}/session/minecraft/hasJoined?username=${username}&serverId=${hash}`, { agent: (this as any)?.agent as Agent, method: 'GET' })
const body = JSON.parse(await data.text())
if (body.id !== undefined) return body
else throw new Error('Failed to verify username!')
}
}
Server.prototype.join = utils.callbackify(Server.prototype.join, 5)
Server.prototype.hasJoined = utils.callbackify(Server.prototype.hasJoined, 4)