From 2e6b4db4fd2a82d2d37666211aa5fad814c7003b Mon Sep 17 00:00:00 2001 From: Enstrayed <48845980+Enstrayed@users.noreply.github.com> Date: Wed, 12 Jun 2024 17:43:42 -0700 Subject: [PATCH 1/4] improve blogpost and disable cider --- routes/blog.js | 27 +++++++-- routes/cider.js | 154 ++++++++++++++++++++++++++---------------------- 2 files changed, 104 insertions(+), 77 deletions(-) diff --git a/routes/blog.js b/routes/blog.js index c1e6f22..b0415d7 100644 --- a/routes/blog.js +++ b/routes/blog.js @@ -7,19 +7,33 @@ app.get("/blogposts", (rreq, rres) => { if (Date.now() < timeSinceLastQuery+10000) { // if it has been <10 seconds since last request rres.set("Access-Control-Allow-Origin","*") - rres.send(cachedResult) // send cached json + + if (rreq.query.format === "html") { // if ?format=html then send HTML + rres.send(cachedResult.asHtml) + } else { // otherwise send json + rres.send(cachedResult.asJson) + } + } else { timeSinceLastQuery = Date.now() cachedResult = parseFiles() rres.set("Access-Control-Allow-Origin","*") - rres.send(cachedResult); + + if (rreq.query.format === "html") { // if ?format=html then send HTML + rres.send(cachedResult.asHtml) + } else { // otherwise send json + rres.send(cachedResult.asJson) + } } }) function parseFiles() { let files = fs.readdirSync(globalConfig.blog.postsDirectory) - let parsedFiles = [] + let result = { + asJson: [], + asHtml: "" + } for (x in files) { if (files[x].endsWith(".html") === false) { break } // If file/dir is not .html then ignore @@ -29,12 +43,13 @@ function parseFiles() { date = date.replace(/.{2}/g,"$&-").replace("-","").slice(0,-1) // Insert a dash every 2 characters, remove the first dash, remove the last character - let name = files[x].slice(9).replace(/รท/g," ").replace(".html","") // Strip Date, replace seperator with space & remove file extension + let name = files[x].slice(9).replace(/-/g," ").replace(".html","") // Strip Date, replace seperator with space & remove file extension - parsedFiles.push({ "date": date, "name": name, "path": `${globalConfig.blog.postsDirUrl}/${files[x]}`}) // Add metadata as JSON to array + result.asJson.unshift({ "date": date, "name": name, "path": `${globalConfig.blog.postsDirUrl}/${files[x]}`}) // Add to asJson array in the result + result.asHtml = `${date} ${name}`+result.asHtml } - return parsedFiles.reverse() + return result } module.exports = {app} \ No newline at end of file diff --git a/routes/cider.js b/routes/cider.js index b309411..22118b6 100644 --- a/routes/cider.js +++ b/routes/cider.js @@ -2,87 +2,99 @@ const { app, db, globalConfig } = require("../index.js") // Get globals from ind var timeSinceLastCiderQuery = Date.now()-2000; var currentListening = {} +var currentListeningHtml = "" -app.get("/cider", (rreq,rres) => { // GET current listening from target - - if (Date.now() < timeSinceLastCiderQuery+2000) { - rres.send(currentListening); // If it has been <2 seconds since the last request, return the cached result. - } else { - getCurrentListening(globalConfig.cider.targetHosts[0]).then(funcRes => { - if (funcRes == 1) { - rres.sendStatus(503) // If there was a problem getting the upstream JSON, return 503 Service Unavailable. - } else { - rres.set("Access-Control-Allow-Origin","*") // Required (I think?) because of CORS. - currentListening = funcRes - rres.send(funcRes) - } - }) - } - +app.get("/cider", (rreq,rres) => { + rres.send("Cider endpoint is temporarily unavailable.") }) +// app.get("/cider", (rreq,rres) => { // GET current listening from target -app.post("/cider", (rreq,rres) => { // POST stop listening on cider target +// if (Date.now() < timeSinceLastCiderQuery+2000) { +// rres.send(currentListening); // If it has been <2 seconds since the last request, return the cached result. +// } else { +// getCurrentListening(globalConfig.cider.targetHosts[0],"json").then(funcRes => { +// if (funcRes == 1) { +// rres.sendStatus(503) // If there was a problem getting the upstream JSON, return 503 Service Unavailable. +// } else { +// rres.set("Access-Control-Allow-Origin","*") // Required (I think?) because of CORS. +// currentListening = funcRes +// rres.send(funcRes) +// } +// }) +// } - fetch(`http://${globalConfig.couchdb.host}/apiauthkeys/${globalConfig.cider.authKeysDoc}`, { - headers: { - "Authorization": `Basic ${btoa(globalConfig.couchdb.authorization)}` - } - }).then(dbRes => dbRes.json()).then(dbRes => { +// }) - if (dbRes.status == 404) { // If document containing cider auth keys does not exist - console.log(`ERROR: Could not find apiauthkeys/${globalConfig.mailjet.authKeysDoc}`) - rres.sendStatus(500) // Refuse request - } else { - if (dbRes["content"][rreq.get("Authorization").split("_")[0]] === rreq.get("Authorization").split("_")[1]) { +// app.post("/cider", (rreq,rres) => { // POST stop listening on cider target - fetch(`http://${globalConfig.cider.targetHosts[0]}/stop`).then(fres => { // send GET /stop to cider target - if (fres.status == 204) { - console.log(`${rreq.get("cf-connecting-ip")} POST /cider returned 200 KEY:${rreq.get("Authorization")}`) - rres.sendStatus(200) // if that works then 200 - } else { - rres.sendStatus(500) // otherwise lol - } - }).catch(ferror => { - rres.sendStatus(503) // and if a problem happens its probably cause cider target is unavailable - }) +// fetch(`http://${globalConfig.couchdb.host}/apiauthkeys/${globalConfig.cider.authKeysDoc}`, { +// headers: { +// "Authorization": `Basic ${btoa(globalConfig.couchdb.authorization)}` +// } +// }).then(dbRes => dbRes.json()).then(dbRes => { - } else { - console.log(`${rreq.get("cf-connecting-ip")} POST /cider returned 401`) // log ip of unauthorized requests - rres.sendStatus(401) // received auth key was not in database - } - } - }) +// if (dbRes.status == 404) { // If document containing cider auth keys does not exist +// console.log(`ERROR: Could not find apiauthkeys/${globalConfig.mailjet.authKeysDoc}`) +// rres.sendStatus(500) // Refuse request +// } else { +// if (dbRes["content"][rreq.get("Authorization").split("_")[0]] === rreq.get("Authorization").split("_")[1]) { -}) +// fetch(`http://${globalConfig.cider.targetHosts[0]}/stop`).then(fres => { // send GET /stop to cider target +// if (fres.status == 204) { +// console.log(`${rreq.get("cf-connecting-ip")} POST /cider returned 200 KEY:${rreq.get("Authorization")}`) +// rres.sendStatus(200) // if that works then 200 +// } else { +// rres.sendStatus(500) // otherwise lol +// } +// }).catch(ferror => { +// rres.sendStatus(503) // and if a problem happens its probably cause cider target is unavailable +// }) + +// } else { +// console.log(`${rreq.get("cf-connecting-ip")} POST /cider returned 401`) // log ip of unauthorized requests +// rres.sendStatus(401) // received auth key was not in database +// } +// } +// }) + +// }) // 2024-04-10: Retrieves currentPlayingSong JSON from specified Cider host and -// returns JSON containing the useful bits if successful, returning 1 if not. -async function getCurrentListening(host) { // Host should be hostname/ip & port only. - timeSinceLastCiderQuery = Date.now(); // Save last time function was run, used to indicate when the cache needs refreshed. - return await fetch(`http://${host}/currentPlayingSong`).then(fetchRes => { - if (fetchRes.status == 502) { - return 1 // If the upstream server returns 502 (Bad Gateway) then internally return 1, indicating error. - } else { - return fetchRes.json().then(jsonRes => { - if (jsonRes.info.name == undefined) { - return 1 // If Cider is running but not playing a song this check prevents an undefined variable error. - } else { - return { - "songName": jsonRes.info.name, - "artistName": jsonRes.info.artistName, - "albumName": jsonRes.info.albumName, - "songLinkUrl": jsonRes.info.url.songLink, - "endtimeEpochInMs": jsonRes.info.endTime, - "artworkUrl": jsonRes.info.artwork.url.replace("{w}", jsonRes.info.artwork.width).replace("{h}", jsonRes.info.artwork.height) - } - } - }) - } - }).catch(fetchError => { - console.error("Error fetch()ing upstream Cider host: "+fetchError) - return 1 // If something else happens then log it and return 1, indicating error. - }) -} +// returns JSON/HTML containing the useful bits if successful, returning 1 if not. + +// async function getCurrentListening(host,contentType) { // Host should be hostname/ip & port only. +// timeSinceLastCiderQuery = Date.now(); // Save last time function was run, used to indicate when the cache needs refreshed. +// return await fetch(`http://${host}/currentPlayingSong`).then(fetchRes => { +// if (fetchRes.status == 502) { +// return 1 // If the upstream server returns 502 (Bad Gateway) then internally return 1, indicating error. +// } else { +// return fetchRes.json().then(jsonRes => { +// if (jsonRes.info.name == undefined) { +// return 1 // If Cider is running but not playing a song this check prevents an undefined variable error. +// } else { +// if (contentType === "json") { +// return { +// "songName": jsonRes.info.name, +// "artistName": jsonRes.info.artistName, +// "albumName": jsonRes.info.albumName, +// "songLinkUrl": jsonRes.info.url.songLink, +// "endtimeEpochInMs": jsonRes.info.endTime, +// "artworkUrl": jsonRes.info.artwork.url.replace("{w}", jsonRes.info.artwork.width).replace("{h}", jsonRes.info.artwork.height) +// } +// } else if (contentType === "html") { +// return `Album Art

I'm listening to

${`${jsonRes.info.name} by ${jsonRes.info.artistName}`}

from ${jsonRes.info.albumName}

song.link
` +// } else { +// return 1 +// } + +// } +// }) +// } +// }).catch(fetchError => { +// console.error("Error fetch()ing upstream Cider host: "+fetchError) +// return 1 // If something else happens then log it and return 1, indicating error. +// }) +// } module.exports = {app} // export routes to be imported by index for execution \ No newline at end of file From 45b7b3541f861b63aa357af325f4ec246a61625c Mon Sep 17 00:00:00 2001 From: Enstrayed <48845980+Enstrayed@users.noreply.github.com> Date: Wed, 12 Jun 2024 17:44:59 -0700 Subject: [PATCH 2/4] god I fucking hate CORS I should just do this in caddy --- routes/cider.js | 1 + 1 file changed, 1 insertion(+) diff --git a/routes/cider.js b/routes/cider.js index 22118b6..7f26a18 100644 --- a/routes/cider.js +++ b/routes/cider.js @@ -5,6 +5,7 @@ var currentListening = {} var currentListeningHtml = "" app.get("/cider", (rreq,rres) => { + rres.set("Access-Control-Allow-Origin","*") rres.send("Cider endpoint is temporarily unavailable.") }) From c615d9c3f986540424ee710ca4655c67902395e6 Mon Sep 17 00:00:00 2001 From: Enstrayed <48845980+Enstrayed@users.noreply.github.com> Date: Wed, 12 Jun 2024 17:55:38 -0700 Subject: [PATCH 3/4] I should read the manual on how to squash commits (fix cider again) --- routes/cider.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/routes/cider.js b/routes/cider.js index 7f26a18..4960cea 100644 --- a/routes/cider.js +++ b/routes/cider.js @@ -6,7 +6,7 @@ var currentListeningHtml = "" app.get("/cider", (rreq,rres) => { rres.set("Access-Control-Allow-Origin","*") - rres.send("Cider endpoint is temporarily unavailable.") + rres.send("Cider endpoint is temporarily unavailable.") }) // app.get("/cider", (rreq,rres) => { // GET current listening from target From e5ab498161be94ae7f3f08be07e09c95ecc0377a Mon Sep 17 00:00:00 2001 From: Enstrayed <48845980+Enstrayed@users.noreply.github.com> Date: Wed, 12 Jun 2024 20:21:14 -0700 Subject: [PATCH 4/4] move authorization code into new file --- liberals/authorization.js | 38 ++++++++++++++ routes/mailjet.js | 102 +++++++++++++++++--------------------- 2 files changed, 84 insertions(+), 56 deletions(-) create mode 100644 liberals/authorization.js diff --git a/liberals/authorization.js b/liberals/authorization.js new file mode 100644 index 0000000..4ca6348 --- /dev/null +++ b/liberals/authorization.js @@ -0,0 +1,38 @@ +const { globalConfig } = require("../index.js") + +async function checkAuthorization(documentToUse,keyToCheck) { + return await fetch(`http://${globalConfig.couchdb.host}/apiauthkeys/${documentToUse}`, { + headers: { + "Authorization": `Basic ${btoa(globalConfig.couchdb.authorization)}` + } + }).then(fetchRes => { + + if (fetchRes.status === 404) { // If document doesnt exist fail gracefully + + console.log("ERROR: Failed to check authorization: Requested document returned 404") + return false + + } else if (fetchRes.status === 401) { // If couchdb is reporting unauthorized fail gracefully + + console.log("ERROR: Failed to check authorization: Database authorization is incorrect") + return false + + } else { + return fetchRes.json().then(dbRes => { // Get response json and check it + + if (dbRes["content"][keyToCheck.split("_")[0]] === keyToCheck.split("_")[1]) { + return true + } else { + return false + } + + }) + } + + }).catch(error => { + console.log("ERROR: Failed to check authorization: " + error) + return false + }) +} + +module.exports = {checkAuthorization} \ No newline at end of file diff --git a/routes/mailjet.js b/routes/mailjet.js index e53f3f1..1ef3cc1 100644 --- a/routes/mailjet.js +++ b/routes/mailjet.js @@ -1,67 +1,57 @@ -const { app, db, globalConfig } = require("../index.js") // Get globals from index +const { app, globalConfig } = require("../index.js") // Get globals from index +const { checkAuthorization } = require("../liberals/authorization.js") app.post("/sendemail", (rreq,rres) => { - fetch(`http://${globalConfig.couchdb.host}/apiauthkeys/${globalConfig.mailjet.authKeysDoc}`, { - headers: { - "Authorization": `Basic ${btoa(globalConfig.couchdb.authorization)}` - } - }).then(dbRes => dbRes.json()).then(dbRes => { + checkAuthorization(globalConfig.mailjet.authKeysDoc,rreq.get("Authorization")).then(authRes => { + if (authRes === false) { // If the supplied authorization is invalid or an error occured - if (dbRes.status == 404) { // If document containing mailjet auth keys does not exist - console.log(`ERROR: Could not find apiauthkeys/${globalConfig.mailjet.authKeysDoc}`) - rres.sendStatus(500) // Refuse request - } else { - if (dbRes["content"][rreq.get("Authorization").split("_")[0]] === rreq.get("Authorization").split("_")[1]) { + console.log(`${rreq.get("cf-connecting-ip")} POST /sendemail returned 401`) // Log the request + rres.sendStatus(401) // Return 401 Unauthorized - // 2024-05-11: Turbo bodge check to make sure request JSON is valid, probably wont work but whatever - if (rreq.body == undefined || rreq.body.recipient == undefined) { - console.log(`${rreq.get("cf-connecting-ip")} POST /sendemail returned 400 KEY:${rreq.get("Authorization").split("_")[1]}`) - rres.sendStatus(400) - } else { - - let message = { - "Messages": [ - { - "From": { - "Email": globalConfig.mailjet.senderAddress, - "Name": globalConfig.mailjet.senderName, - }, - "To": [ - { - "Email": rreq.body.recipient, - } - ], - - "Subject": rreq.body.subject || "Request did not include a subject.", - "TextPart": rreq.body.message || "Request did not include a message.", - } - ] - } - - fetch("https://api.mailjet.com/v3.1/send", { - method: "POST", - headers: { - "Authorization": `Basic ${btoa(globalConfig.mailjet.apiKey)}`, - "Content-Type": "application/json" - }, - body: JSON.stringify(message) - }).then(fetchRes => { - if (fetchRes.status == 200) { - console.log(`${rreq.get("cf-connecting-ip")} POST /sendemail returned 200 KEY:${rreq.get("Authorization").split("_")[1]}`) - rres.sendStatus(200) - } else { - console.log(`Mailjet Fetch returned result other than OK: ${fetchRes.status} ${fetchRes.statusText}`) - rres.sendStatus(500) + } else if (authRes === true) { // If the authorization was valid, continue function + + // 2024-05-11: Turbo bodge check to make sure request JSON is valid, probably wont work but whatever + if (rreq.body == undefined || rreq.body.recipient == undefined) { + console.log(`${rreq.get("cf-connecting-ip")} POST /sendemail returned 400 KEY:${rreq.get("Authorization").split("_")[0]}`) + rres.sendStatus(400) + } else { + + let message = { + "Messages": [ + { + "From": { + "Email": globalConfig.mailjet.senderAddress, + "Name": globalConfig.mailjet.senderName, + }, + "To": [ + { + "Email": rreq.body.recipient, + } + ], + + "Subject": rreq.body.subject || "Request did not include a subject.", + "TextPart": rreq.body.message || "Request did not include a message.", } - }) + ] } - - - } else { - console.log(`${rreq.get("cf-connecting-ip")} POST /sendemail returned 401`) // log ip of unauthorized requests - rres.sendStatus(401) // received auth key was not in database + fetch("https://api.mailjet.com/v3.1/send", { + method: "POST", + headers: { + "Authorization": `Basic ${btoa(globalConfig.mailjet.apiKey)}`, + "Content-Type": "application/json" + }, + body: JSON.stringify(message) + }).then(fetchRes => { + if (fetchRes.status == 200) { + console.log(`${rreq.get("cf-connecting-ip")} POST /sendemail returned 200 KEY:${rreq.get("Authorization").split("_")[1]}`) + rres.sendStatus(200) + } else { + console.log(`Mailjet Fetch returned result other than OK: ${fetchRes.status} ${fetchRes.statusText}`) + rres.sendStatus(500) + } + }) } } })