mojang-auth
Version:
Mojang authentication client, re-implementing parts of `node-yggdrasil` in classes, and adding support for custom auth servers.
75 lines (70 loc) • 3.1 kB
text/typescript
import * as uuid from 'uuid'
import * as utils from './utils';
import type { Agent } from 'http'
export let defaultHost = 'https://authserver.mojang.com';
export const setDefaultHost = (val: string) => {
defaultHost = val;
}
export default class Client {
constructor(options?: { defaultHost: string }) {
Object.assign(this, options);
}
/**
* Attempts to authenticate a user.
* @param {Object} options Config object
* @param {Function} cb Callback
*/
async auth(options: { agent?: string, user: string, pass: string, token?: string, version: string, requestUser?: boolean }) {
if (options.token === null) delete options.token
else options.token = options.token ?? uuid.v4()
options.agent = options.agent ?? 'Minecraft'
return await utils.call(
(this as any)?.host as string ?? defaultHost,
'authenticate',
{
agent: {
name: options.agent,
version: options.agent === 'Minecraft' ? 1 : options.version
},
username: options.user,
password: options.pass,
clientToken: options.token,
requestUser: options.requestUser === true
},
(this as any)?.agent as Agent
);
}
/**
* Refreshes a accessToken.
* @param {String} accessToken Old Access Token
* @param {String} clientToken Client Token
* @param {String=false} requestUser Whether to request the user object
* @param {Function} cb (err, new token, full response body)
*/
async refresh(accessToken: string, clientToken: string, requestUser?: boolean) {
const data = await utils.call((this as any)?.host as string ?? defaultHost, 'refresh', { accessToken, clientToken, requestUser: requestUser ?? false }, (this as any)?.agent as Agent)
if (data.clientToken !== clientToken) throw new Error('clientToken assertion failed')
return [data.accessToken, data];
}
/**
* Validates an access token
* @param {String} accessToken Token to validate
* @param {Function} cb (error)
*/
async validate(accessToken: string) {
return await utils.call((this as any)?.host as string ?? defaultHost, 'validate', { accessToken }, (this as any)?.agent as Agent);
}
/**
* Invalidates all access tokens.
* @param {String} username User's user
* @param {String} password User's pass
* @param {Function} cb (error)
*/
async signout(username: string, password: string) {
return await utils.call((this as any)?.host as string ?? defaultHost, 'signout', { username, password }, (this as any)?.agent as Agent);
}
}
Client.prototype.auth = utils.callbackify(Client.prototype.auth, 1);
Client.prototype.refresh = utils.callbackify(Client.prototype.refresh, 3);
Client.prototype.signout = utils.callbackify(Client.prototype.signout, 1);
Client.prototype.validate = utils.callbackify(Client.prototype.validate, 2);