Skip to content

Instantly share code, notes, and snippets.

@MisterFixx
Last active February 28, 2021 21:46
Show Gist options
  • Save MisterFixx/f079d6a60706c098beac958b23753c12 to your computer and use it in GitHub Desktop.
Save MisterFixx/f079d6a60706c098beac958b23753c12 to your computer and use it in GitHub Desktop.
/* The MIT License (MIT)
Copyright (c) 2020 Mister_Fix
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
const WORKER_ID = makeid(6);
const localCache = caches.default
const cacheTtl = parseInt(cache_ttl);
var currentEvent;
addEventListener('fetch', event => {
event.respondWith(serveRoute(event));
});
async function serveRoute(event) {
let finalResponse;
currentEvent = event;
const timeStart = Date.now();
const route = event.request.url.split("/").slice(3, 7);
try {
let path = route[0];
let identifier = route[1];
let nameRequired = 0;
if (path === "name") nameRequired = 1;
if(identifier === undefined || identifier == ""){
finalResponse = badRequest();
logflare(finalResponse, event, timeStart);
return finalResponse;
}
identifier = identifier.replace(/-/g, '');
if (nameRequired == 0 && identifier.length != 32) {
response = await usernameToUuid(identifier);
if(response.status != undefined) {
finalResponse = response;
logflare(finalResponse, event, timeStart);
return finalResponse;
}
else{
identifier = response.id;
}
}
//ROUTES
if(path === "textures") {
finalResponse = await textures(identifier);
}
else if(path === "user") {
finalResponse = await user(identifier, (route[2] == "signed"));
}
else if(path === "name") {
finalResponse = await uuid(identifier);
}
else if(path === "names") {
finalResponse = await name_history(identifier);
}
else {
finalResponse = notFound(`Unknown route '${path}'`);
}
}
catch (err) {
finalResponse = error(err.stack);
event.waitUntil(logflare_debug(err.stack));
}
logflare(finalResponse, event, timeStart);
return finalResponse;
}
async function uuid(identifier) {
if(identifier.length == 32) {
return badRequest(`Invalid name '${identifier}' provided`);
}
else {
response = await usernameToUuid(identifier);
if(response.status != undefined) {
return response;
}
return respond(response);
}
}
async function textures(identifier) {
let response = {};
profile = await uuidToProfile(identifier);
if(profile.status != undefined) {
return profile;
}
else {
texturesRaw = profile.properties[0];
textures_array = JSON.parse(atob(texturesRaw.value || "e30=")).textures || {};
response.uuid = profile.id;
response.name = profile.name;
response.skinRaw = null;
if(profile.hasOwnProperty("legacy")) {
response.legacy = profile.legacy;
}
if(textures_array.hasOwnProperty("CAPE")) {
response.cape = textures_array.CAPE.url;
}
if(textures_array.hasOwnProperty("SKIN")) {
response.skin = textures_array.SKIN.url;
skin = await buffer(textures_array.SKIN.url);
if (skin.status == undefined) {
response.skinRaw = skin;
}
}
}
return respond(response);
}
async function user(identifier, signed) {
[response, history] = await Promise.all([
uuidToProfile(identifier, signed),
uuidToUsernameHistory(identifier)
]);
if(response.status != undefined) {
return response;
}
if(history.status != undefined) {
history = [{name: response.name}];
}
response.name_history = history;
return respond(response);
}
async function name_history(identifier) {
let response = await uuidToUsernameHistory(identifier);
if(response.status != undefined) {
return response;
}
return respond(response);
}
// Respond to a client with a Http response.
// @param {object} data - Data to send back in the response.
// @param {integer} code - Http status code.
// @returns {response} - Raw response object.
function respond(data, code = 200) {
data = JSON.stringify(data, undefined, 4);
return new Response(data, {
status: code,
headers: {
"Content-type": "application/json",
"Access-Control-Allow-Origin": "*"
}
});
}
// Respond with a generic Http error.
// @see #respond(data)
function error(reason = null, {code, type} = {}) {
if(code == null) {
code = 500;
}
if(type == null) {
type = "Internal Error";
}
return respond({code: code, error: type, reason: reason}, code);
}
//Respond with a 400 - Bad Request error.
//@see #error(code, message, reason)
function badRequest(reason = null) {
return error(reason, {code: 400, type: "Bad Request"});
}
//Respond with a 404 - Not Found error.
//@see #error(code, message, reason)
function notFound(reason = null) {
return error(reason, {code: 404, type: "Not Found"});
}
// Send a Http request and get a response.
// @param {string} url - Url of the request.
// @param {function} parser - Function to parse the raw response.
// @returns {promise<response>} - Promise of the parsed response.
async function request(url, {parser} = {}) {
response = await fetch(url);
if(response.status != 200 && response.status != 204){
currentEvent.waitUntil(logflare_debug(JSON.stringify(response)));
}
if(parser && response.status == 200){
response = await parser(response);
}
return response;
}
// Ftech JSON by url either from KV/Cache or from web if it doesn't exist in cache.
// @param {string} url - Url of the request.
// @returns {promise<object>} - Promise of a Json response.
async function json(url) {
let response = await CACHE.get(url, "json");
if(response === null){
let localCachedResponse = await localCache.match(url);
if(!localCachedResponse){
response = await request(url, {
parser: (async function(response) {
return (await response.json());
})
});
if(response.status == undefined){
let cachedResponse = jsonToResponse(response);
//We cache the result of the request both locall and on KV because it takes several seconds for KV entries to become available globally, in the mean time,
//If the same request is requested again while the cached request is still not available, it will attempt to write it again, wasting time and (((metered))) write operations
currentEvent.waitUntil(localCache.put(url, cachedResponse));
currentEvent.waitUntil(CACHE.put(url, JSON.stringify(response), {expirationTtl: cacheTtl}));
}
}
else{
response = await localCachedResponse.json();
}
}
return response;
}
// Send a Http request and get a Buffer response.
// @param {string} url - Url of the request.
// @returns {string} - base64 string of a Buffer response.
function buffer(url) {
return request(url, {
parser: (async function(response) {
response = (await response.arrayBuffer());
response = response.asBase64();
return response;
})
});
}
// Get the Uuid of a username at a given time.
// @example
// {
// "id": "dad8b95ccf6a44df982e8c8dd70201e0",
// "name": "ElectroidFilms"
// }
// @param {string} username - Minecraft username.
// @param {integer} secs - Unix seconds to set the search context.
// @throws {204} - When no user exists with that name.
// @returns {promise<object>} - Uuid response.
function usernameToUuid(username) {
return json(`https://api.mojang.com/users/profiles/minecraft/${username}`);
}
// Get the history of usernames for the Uuid.
// @example
// [
// {
// "name": "ElectroidFilms"
// },
// {
// "name": "Electric",
// "changedToAt": 1423059891000
// }
// ]
// @param {string} id - Uuid to check the username history.
// @returns {promise<object>} - Username history response.
function uuidToUsernameHistory(id) {
return json(`https://api.mojang.com/user/profiles/${id}/names`);
}
// Get the session profile of the Uuid.
// @example
// {
// "id": "dad8b95ccf6a44df982e8c8dd70201e0",
// "name": "ElectroidFilms",
// "properties": [
// {"name": "textures", "value": "...base64"}
// ]
// }
// @param {string} id - Uuid to get the session profile.
// @returns {promise<object>} - Uuid session profile.
function uuidToProfile(id, signed = false) {
url = `https://sessionserver.mojang.com/session/minecraft/profile/${id}`;
if(signed) url += "?unsigned=false";
return json(url);
}
// Turn JSON into a response object that we can cache using the Caching Runtime API.
// @param {JSON} json - the input JSON that a response object will be built around.
// @returns {Response} - The newly created Response object.
function jsonToResponse(json){
let blob = new Blob([JSON.stringify(json)], {type: 'application/json'});
let response = new Response(blob, {"status": 200, "statusText": "OK"});
response.headers.append("Cache-Control", "s-maxage=120");
return response;
}
// Check if string is actually empty
// @param {String} string - the string to check
// @return {boolean} - true if string is empty, false otherwise.
String.prototype.isEmpty = function() {
return (this.length === 0 || !this.trim());
}
// Fast method of encoding an array buffer as a base64 string.
// @copyright https://gist.github.com/jonleighton/958841
// @returns {string} - Array buffer as base64 string.
ArrayBuffer.prototype.asBase64 = function() {
var base64 = ''
var encodings = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
var bytes = new Uint8Array(this)
var byteLength = bytes.byteLength
var byteRemainder = byteLength % 3
var mainLength = byteLength - byteRemainder
var a, b, c, d
var chunk
// Main loop deals with bytes in chunks of 3
for (var i = 0; i < mainLength; i = i + 3) {
// Combine the three bytes into a single integer
chunk = (bytes[i] << 16) | (bytes[i + 1] << 8) | bytes[i + 2]
// Use bitmasks to extract 6-bit segments from the triplet
a = (chunk & 16515072) >> 18 // 16515072 = (2^6 - 1) << 18
b = (chunk & 258048) >> 12 // 258048 = (2^6 - 1) << 12
c = (chunk & 4032) >> 6 // 4032 = (2^6 - 1) << 6
d = chunk & 63 // 63 = 2^6 - 1
// Convert the raw binary segments to the appropriate ASCII encoding
base64 += encodings[a] + encodings[b] + encodings[c] + encodings[d]
}
// Deal with the remaining bytes and padding
if (byteRemainder == 1) {
chunk = bytes[mainLength]
a = (chunk & 252) >> 2 // 252 = (2^6 - 1) << 2
// Set the 4 least significant bits to zero
b = (chunk & 3) << 4 // 3 = 2^2 - 1
base64 += encodings[a] + encodings[b] + '=='
}
else if (byteRemainder == 2) {
chunk = (bytes[mainLength] << 8) | bytes[mainLength + 1]
a = (chunk & 64512) >> 10 // 64512 = (2^6 - 1) << 10
b = (chunk & 1008) >> 4 // 1008 = (2^6 - 1) << 4
// Set the 2 least significant bits to zero
c = (chunk & 15) << 2 // 15 = 2^4 - 1
base64 += encodings[a] + encodings[b] + encodings[c] + '='
}
return base64
}
// Generate a random alphanumeric ID
// @param {int} length - desired ID character length.
// @returns {string} - a random ID.
function makeid(length){
let text = ""
const possible = "ABCDEFGHIJKLMNPQRSTUVWXYZ0123456789"
for (let i = 0; i < length; i += 1) {
text += possible.charAt(Math.floor(Math.random() * possible.length))
}
return text
}
// generate a header dump from headers array
// @param {array} headers - Request/Response headers.
// @returns {array} - header dump array.
function buildMetadataFromHeaders(headers){
const responseMetadata = {}
Array.from(headers).forEach(([key, value]) => {
responseMetadata[key.replace(/-/g, "_")] = value
})
return responseMetadata
}
// Log request to logflare
// @param {Response} response - final request response.
// @param {FetchEvent} event - the fetch event for this request.
// @param {int} timeStart - timestamp of when the worker began creating a response.
// @param {int} timeStop - timestamp of when the worker finished creating a response.
// @returns {void}
// By the way this method is horrible and i hate how long it is.
function logflare(response, event, timeStart) {
const timeStop = Date.now();
let {request} = event;
rMeth = request.method;
rUrl = request.url;
uAgent = request.headers.get("user-agent");
rHost = request.headers.get("host");
cfRay = request.headers.get("cf-ray");
cIP = request.headers.get("cf-connecting-ip");
rCf = request.cf;
requestMetadata = buildMetadataFromHeaders(request.headers);
originTimeMs = timeStop - timeStart;
statusCode = response.status;
responseMetadata = buildMetadataFromHeaders(response.headers);
logEntry = `${env} || ${statusCode} | ${cIP} | ${cfRay} | ${rUrl} | ${uAgent}`;
logflareEventBody = {
source: logflare_log_source,
log_entry: logEntry,
metadata: {
response: {
headers: responseMetadata,
origin_time: originTimeMs,
status_code: response.status,
},
request: {
url: rUrl,
method: rMeth,
headers: requestMetadata,
cf: rCf,
},
logflare_worker: {
worker_id: WORKER_ID,
}
}
};
init = {
method: "POST",
headers: {
"X-API-KEY": logflare_api_key,
"Content-Type": "application/json",
"User-Agent": `Cloudflare Worker via ${rHost}`
},
body: JSON.stringify(logflareEventBody),
};
event.waitUntil(fetch("https://api.logflare.app/logs", init));
}
// Log debug message to logflare - since we can't always console.log() kappa
// @param {String} msg - The message to log.
// @returns {void}
async function logflare_debug(msg) {
logflareEventBody = {
source: logflare_debug_source,
log_entry: `${env} || ${msg}`
};
init = {
method: "POST",
headers: {
"X-API-KEY": logflare_api_key,
"Content-Type": "application/json",
"User-Agent": `Cloudflare Worker via debug log`
},
body: JSON.stringify(logflareEventBody),
};
fetch("https://api.logflare.app/logs", init);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment