From 05c7261c46eef432ee0d433b819a06015ad8708a Mon Sep 17 00:00:00 2001 From: Enstrayed <48845980+Enstrayed@users.noreply.github.com> Date: Wed, 21 Aug 2024 17:26:23 -0700 Subject: [PATCH] Major changes --- README.md | 28 ++++------ liberals/auth.js | 34 ++++++------ liberals/authorization.js | 34 ------------ liberals/{nowplaying.js => libnowplaying.js} | 11 +++- liberals/logging.js | 17 ++++++ routes/blog.js | 55 -------------------- routes/etyd.js | 36 +++++++------ routes/ip.js | 4 +- routes/mailjet.js | 41 +++++---------- routes/nowplaying.js | 6 +-- 10 files changed, 90 insertions(+), 176 deletions(-) delete mode 100644 liberals/authorization.js rename liberals/{nowplaying.js => libnowplaying.js} (80%) create mode 100644 liberals/logging.js delete mode 100644 routes/blog.js diff --git a/README.md b/README.md index 8319009..040ab4f 100644 --- a/README.md +++ b/README.md @@ -14,11 +14,12 @@ On startup, this application will look for two files. If either cannot be read,
Configuration Example -* `couchdb.host`: Hostname/IP address and port of a CouchDB server. -* `couchdb.authorization`: Username & password used to access the CouchDB server, in HTTP Basic authentication format, e.g. `username:password`. -* `blog.postsDirectory`: Directory that will be parsed when calling /blogposts. If running in Docker this directory will need to be mounted to the container. -* `blog.postsDirUrl`: Location of the posts directory on the web server. -* `nowplaying.*.target`: Set to the Last.fm/Jellyfin username to query for playback information. +* `couchdbHhost`: URL of CouchDB server. +* `mailjet.apiKey`: Mailjet API Key. +* `mailjet.senderAddress`: Email address that emails will be received from, must be verified in Mailjet admin panel. +* `frontpage.frontpageDir`: Directory of frontpage, will be served at root with modifications. +* `nowplaying.*.apiKey`: API key of respective service. +* `nowplaying.*.target`: User that should be queried to retrieve playback information. ```json { @@ -27,28 +28,21 @@ On startup, this application will look for two files. If either cannot be read, "routesDir": "./routes" }, - "couchdb": { - "host": "hazeldale:5984", - "authorization": "" - }, + "couchdbHost": "", "mailjet": { "apiKey": "", - "senderAddress": "apinotifications@enstrayed.com", - "senderName": "API Notifications", - - "authKeysDoc": "mailjet" + "senderAddress": "" }, - "blog": { - "postsDirectory": "C:/Users/natha/Downloads/proto/posts", - "postsDirUrl": "/posts" + "frontpage": { + "frontpageDir": "" }, "nowplaying": { "lastfm": { "apiKey": "", - "target": "enstrayed" + "target": "" }, "jellyfin": { "apiKey": "", diff --git a/liberals/auth.js b/liberals/auth.js index 07ff077..28b9c2b 100644 --- a/liberals/auth.js +++ b/liberals/auth.js @@ -1,30 +1,28 @@ const { globalConfig } = require("../index.js") +/** + * Checks if a token exists in the sessions file (authentication) and if it has the correct permissions (authorization) + * @param {string} token Token as received by client + * @param {string} scope Scope the token will need to have in order to succeed + * @returns True for successful authentication and authorization, false if either fail + */ async function checkToken(token,scope) { return await fetch(`${globalConfig.couchdbHost}/auth/sessions`).then(fetchRes => { - // CouchDB should only ever return 200/304 for success so this should work - // https://docs.couchdb.org/en/stable/api/document/common.html#get--db-docid - if (fetchRes.status !== 200 || fetchRes.status !== 304) { - console.log(`ERROR: auth.js: Database request returned ${fetchRes.status}`) - return false - } else { + return fetchRes.json().then(dbRes => { - return fetchRes.json().then(dbRes => { + if (dbRes.sessions[token] == undefined) { // If the token is not on the sessions list then reject + return false + } else if (dbRes.sessions[token].scopes.includes(scope)) { // If the token is on the seesions list and includes the scope then accept + return true + } else { // Otherwise reject + return false + } - if (dbRes.sessions[token] == undefined) { // If the token is not on the sessions list then reject - return false - } else if (dbRes.sessions[token].scopes.includes(scope)) { // If the token is on the seesions list and includes the scope then accept - return true - } else { // Otherwise reject - return false - } - - }) - } + }) }).catch(error => { - console.log("ERROR: auth.js: " + error) + console.log(`ERROR: auth.js: Fetch failed: ${error}`) return false }) } diff --git a/liberals/authorization.js b/liberals/authorization.js deleted file mode 100644 index 49a14ed..0000000 --- a/liberals/authorization.js +++ /dev/null @@ -1,34 +0,0 @@ -const { globalConfig } = require("../index.js") - -async function checkAuthorization(documentToUse,keyToCheck) { - return await fetch(`${globalConfig.couchdbHost}/apiauthkeys/${documentToUse}`).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/liberals/nowplaying.js b/liberals/libnowplaying.js similarity index 80% rename from liberals/nowplaying.js rename to liberals/libnowplaying.js index ab7ec30..76fd8aa 100644 --- a/liberals/nowplaying.js +++ b/liberals/libnowplaying.js @@ -1,12 +1,16 @@ const { globalConfig } = require("../index.js") +/** + * Queries LastFM for user set in config file and returns formatted result + * @returns {object} Object containing response in JSON and HTML (as string), WILL RETURN EMPTY OBJECT ON FAILURE! + */ async function queryLastfm() { return await fetch(`https://ws.audioscrobbler.com/2.0/?format=json&method=user.getrecenttracks&limit=1&api_key=${globalConfig.nowplaying.lastfm.apiKey}&user=${globalConfig.nowplaying.lastfm.target}`).then(response => response.json()).then(response => { if (response["recenttracks"] == undefined) { - return 1 + return {} } else { if (response.recenttracks.track[0]["@attr"] == undefined) { - return 1 + return {} } else { return { "json": { @@ -20,6 +24,9 @@ async function queryLastfm() { } } } + }).catch(fetchError => { + console.log("libnowplaying.js: Fetch failed! "+fetchError) + return {} }) } diff --git a/liberals/logging.js b/liberals/logging.js new file mode 100644 index 0000000..1650318 --- /dev/null +++ b/liberals/logging.js @@ -0,0 +1,17 @@ +/** + * Logs various details about the request (IP, Token, Method, Path, etc) to the console for later review + * @param {object} response Parent response object + * @param {object} request Parent request object + * @param {number} code Status code to log, should be same as sent to client + * @param {string} extra Optional extra details to add to log, ideal for caught errors + */ +function logRequest(response,request,code,extra) { + if (extra) { + actualExtra = "; Extra: "+extra + } else { + actualExtra = "" + } + console.log(`${request.get("cf-connecting-ip") ?? request.ip} (${request.get("Authorization")}) ${request.method} ${request.path} returned ${code}${actualExtra}`) +} + +module.exports = { logRequest } \ No newline at end of file diff --git a/routes/blog.js b/routes/blog.js deleted file mode 100644 index 9a0bed0..0000000 --- a/routes/blog.js +++ /dev/null @@ -1,55 +0,0 @@ -const { app, globalConfig, fs } = require("../index.js") // Get globals from index - -var timeSinceLastQuery = Date.now()-10000 -var cachedResult = {} - -app.get("/blogposts", (rreq, rres) => { - - if (Date.now() < timeSinceLastQuery+10000) { // if it has been <10 seconds since last request - - - 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() - - - 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 result = { - asJson: [], - asHtml: "" - } - - for (x in files) { - if (files[x].endsWith(".html") === false) { break } // If file/dir is not .html then ignore - - let date = files[x].split("-")[0] - if (date < 10000000 || date > 99999999) { break } // If date does not fit ISO8601 format then ignore - - 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 - - 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 result -} - -module.exports = {app} \ No newline at end of file diff --git a/routes/etyd.js b/routes/etyd.js index b381c2c..e389447 100644 --- a/routes/etyd.js +++ b/routes/etyd.js @@ -1,8 +1,9 @@ const { app, globalConfig } = require("../index.js") // Get globals from index const { checkToken } = require("../liberals/auth.js") +const { logRequest } = require("../liberals/logging.js") -app.get("/etyd*", (rreq,rres) => { - fetch(`${globalConfig.couchdbHost}/etyd${rreq.path.replace("/etyd","")}`).then(dbRes => { +app.get("/api/etyd*", (rreq,rres) => { + fetch(`${globalConfig.couchdbHost}/etyd${rreq.path.replace("/api/etyd","")}`).then(dbRes => { if (dbRes.status == 404) { rres.sendStatus(404) } else { @@ -10,18 +11,18 @@ app.get("/etyd*", (rreq,rres) => { try { rres.redirect(dbRes.content.url) // Node will crash if the Database entry is malformed } catch (responseError) { + logRequest(rres,rreq,500,responseError) rres.sendStatus(500) - console.log(`${rres.get("cf-connecting-ip")} GET ${rreq.path} returned 500: ${responseError}`) } }) } }).catch(fetchError => { + logRequest(rres,rreq,500,fetchError) rres.sendStatus(500) - console.log(`${rres.get("cf-connecting-ip")} GET ${rreq.path} returned 500: ${fetchError}`) }) }) -app.delete("/etyd*", (rreq,rres) => { +app.delete("/api/etyd*", (rreq,rres) => { if (rreq.get("Authorization") === undefined) { rres.sendStatus(400) @@ -31,25 +32,27 @@ app.delete("/etyd*", (rreq,rres) => { rres.sendStatus(401) } else if (authRes === true) { // Authorization successful - fetch(`${globalConfig.couchdbHost}/etyd${rreq.path.replace("/etyd", "")}`).then(dbRes => { + fetch(`${globalConfig.couchdbHost}/etyd${rreq.path.replace("/api/etyd", "")}`).then(dbRes => { if (dbRes.status == 404) { - rres.sendStatus(404) + rres.sendStatus(404) // Entry does not exist } else { dbRes.json().then(dbRes => { - fetch(`${globalConfig.couchdbHost}/etyd${rreq.path.replace("/etyd", "")}`, { + fetch(`${globalConfig.couchdbHost}/etyd${rreq.path.replace("/api/etyd", "")}`, { method: "DELETE", headers: { "If-Match": dbRes["_rev"] // Using the If-Match header is easiest for deleting entries in couchdb } }).then(fetchRes => { if (fetchRes.status == 200) { - console.log(`${rres.get("cf-connecting-ip")} DELETE ${rreq.path} returned 200 KEY: ${rreq.get("Authorization")}`) + // console.log(`${rres.get("cf-connecting-ip")} DELETE ${rreq.path} returned 200 KEY: ${rreq.get("Authorization")}`) + logRequest(rres,rreq,200) rres.sendStatus(200) } }).catch(fetchError => { - console.log(`${rres.get("cf-connecting-ip")} DELETE ${rreq.path} returned 500: ${fetchError}`) + // console.log(`${rres.get("cf-connecting-ip")} DELETE ${rreq.path} returned 500: ${fetchError}`) + logRequest(rres,rreq,500,fetchError) rres.sendStatus(500) }) @@ -57,7 +60,7 @@ app.delete("/etyd*", (rreq,rres) => { } }).catch(fetchError => { - console.log(`${rres.get("cf-connecting-ip")} DELETE ${rreq.path} returned 500: ${fetchError}`) + logRequest(rres,rreq,500,fetchError) rres.sendStatus(500) }) @@ -67,7 +70,7 @@ app.delete("/etyd*", (rreq,rres) => { }) -app.post("/etyd*", (rreq,rres) => { +app.post("/api/etyd*", (rreq,rres) => { if (rreq.get("Authorization") === undefined) { rres.sendStatus(400) @@ -80,7 +83,7 @@ app.post("/etyd*", (rreq,rres) => { if (rreq.body["url"] == undefined) { rres.sendStatus(400) } else { - fetch(`${globalConfig.couchdbHost}/etyd${rreq.path.replace("/etyd", "")}`, { + fetch(`${globalConfig.couchdbHost}/etyd${rreq.path.replace("/api/etyd", "")}`, { method: "PUT", body: JSON.stringify({ "content": { @@ -95,16 +98,17 @@ app.post("/etyd*", (rreq,rres) => { break; case 201: - rres.status(200).send(rreq.path.replace("/etyd", "")) + rres.status(200).send(rreq.path.replace("/api/etyd", "")) break; default: - console.log(`ERROR: CouchDB PUT did not return expected code: ${dbRes.status}`) + logRequest(rres,rreq,500,`CouchDB PUT did not return expected code: ${dbRes.status}`) + rres.sendStatus(500) break; } }).catch(fetchError => { - console.log(`${rres.get("cf-connecting-ip")} DELETE ${rreq.path} returned 500: ${fetchError}`) + logRequest(rres,rreq,500,fetchError) rres.sendStatus(500) }) } diff --git a/routes/ip.js b/routes/ip.js index cb24c65..a547514 100644 --- a/routes/ip.js +++ b/routes/ip.js @@ -1,6 +1,6 @@ const { app } = require("../index.js") -app.get("/ip", (rreq,rres) => { +app.get("/api/ip", (rreq,rres) => { let jsonResponse = { "IP": rreq.get("cf-connecting-ip") || rreq.ip, "Country": rreq.get("cf-ipcountry") || "not_cloudflare", @@ -10,7 +10,7 @@ app.get("/ip", (rreq,rres) => { rres.send(jsonResponse) }) -app.get("/headers", (rreq,rres) => { +app.get("/api/headers", (rreq,rres) => { rres.send(rreq.headers) }) diff --git a/routes/mailjet.js b/routes/mailjet.js index 19d5e35..00a6e8a 100644 --- a/routes/mailjet.js +++ b/routes/mailjet.js @@ -1,38 +1,22 @@ const { app, globalConfig } = require("../index.js") // Get globals from index const { checkToken } = require("../liberals/auth.js") +const { logRequest } = require("../liberals/logging.js") -app.post("/sendemail", (rreq,rres) => { - +app.post("/api/sendemail", (rreq,rres) => { checkToken(rreq.get("Authorization"),"mailjet").then(authRes => { - if (authRes === false) { // If the supplied authorization is invalid or an error occured - - console.log(`${rreq.get("cf-connecting-ip")} POST /sendemail returned 401`) // Log the request + if (authRes === false) { rres.sendStatus(401) - - } 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]}`) + } else if (authRes === true) { + if (rreq.body == undefined || rreq.body.recipient == undefined) { // 2024-05-11: Turbo bodge check to make sure request JSON is valid, probably wont work but whatever rres.sendStatus(400) } else { - let message = { - "Messages": [ - { - "From": { - "Email": globalConfig.mailjet.senderAddress - }, - "To": [ - { - "Email": rreq.body.recipient, - } - ], - + "Messages": [{ + "From": { "Email": globalConfig.mailjet.senderAddress }, + "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", { @@ -44,17 +28,16 @@ app.post("/sendemail", (rreq,rres) => { 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]}`) + logRequest(rres,rreq,200) rres.sendStatus(200) } else { - console.log(`Mailjet Fetch returned result other than OK: ${fetchRes.status} ${fetchRes.statusText}`) + logRequest(rres,rreq,500,`Mailjet fetch did not return OK: ${fetchRes.status} ${fetchRes.statusText}`) rres.sendStatus(500) } }) } } }) - }) -module.exports = {app} // export routes to be imported by index for execution \ No newline at end of file +module.exports = {app} \ No newline at end of file diff --git a/routes/nowplaying.js b/routes/nowplaying.js index ab7e75b..0b4eb32 100644 --- a/routes/nowplaying.js +++ b/routes/nowplaying.js @@ -1,5 +1,5 @@ const { app, globalConfig } = require("../index.js") -const { queryLastfm } = require("../liberals/nowplaying.js") +const { queryLastfm } = require("../liberals/libnowplaying.js") var timeSinceLastLastfmQuery = Date.now()-5000 var cachedLastfmResult = {} @@ -11,14 +11,14 @@ const notPlayingAnythingPlaceholder = { "html": `I'm not currently listening to anything.` } -app.get("/nowplaying", (rreq,rres) => { +app.get("/api/nowplaying", (rreq,rres) => { if (Date.now() < timeSinceLastLastfmQuery+5000) { rres.send(cachedLastfmResult[rreq.query.format] ?? cachedLastfmResult.json) } else { timeSinceLastLastfmQuery = Date.now() queryLastfm().then(response => { - if (response == 1) { + if (response == {}) { cachedLastfmResult = notPlayingAnythingPlaceholder } else { cachedLastfmResult = response