From 31a22703c18f7e94bcdf344f55759a14f766acc2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sun, 8 Dec 2024 12:05:01 +0100 Subject: [PATCH 01/19] initial commit --- server/app.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/server/app.js b/server/app.js index 8a2e17bbd..fab56e624 100644 --- a/server/app.js +++ b/server/app.js @@ -312,6 +312,34 @@ app.get('/user/:username', async (req, res, next)=>{ return next(); }); +//Rename Brews +app.put('/user/:username/rename-brews', async (req, res) => { + const { username } = req.params; + const { newUsername } = req.body; + + if (!username || !newUsername) { + return res.status(400).json({ error: 'Username and newUsername are required.' }); + } + try { + const brews = await HomebrewModel.getByUser(username, true, ['authors']); + const renamePromises = brews.map(async (brew) => { + const updatedAuthors = brew.authors.map((author) => + author === username ? newUsername : author + ); + return HomebrewModel.updateOne( + { _id: brew._id }, + { $set: { authors: updatedAuthors } } + ); + }); + await Promise.all(renamePromises); + + return res.json({ success: true, message: `Brews for ${username} renamed to ${newUsername}.` }); + } catch (error) { + console.error('Error renaming brews:', error); + return res.status(500).json({ error: 'Failed to rename brews.' }); + } +}); + //Edit Page app.get('/edit/:id', asyncHandler(getBrew('edit')), asyncHandler(async(req, res, next)=>{ req.brew = req.brew.toObject ? req.brew.toObject() : req.brew; From db9212bd12a9837b7882cc1006d6b0b353a96f58 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sun, 8 Dec 2024 20:45:43 +0100 Subject: [PATCH 02/19] log req --- server/middleware/check-client-version.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/server/middleware/check-client-version.js b/server/middleware/check-client-version.js index 001995f4e..e72a7fd0b 100644 --- a/server/middleware/check-client-version.js +++ b/server/middleware/check-client-version.js @@ -2,6 +2,9 @@ import packageJSON from '../../package.json' with { type: "json" }; const version = packageJSON.version; export default (req, res, next)=>{ + console.log(req); + //check if req comes from localhost + const userVersion = req.get('Homebrewery-Version'); if(userVersion != version) { From 1b20c008425271897ae81be4da9616705062a4f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sun, 8 Dec 2024 20:46:02 +0100 Subject: [PATCH 03/19] log headers --- server/middleware/check-client-version.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/middleware/check-client-version.js b/server/middleware/check-client-version.js index e72a7fd0b..3cd30582e 100644 --- a/server/middleware/check-client-version.js +++ b/server/middleware/check-client-version.js @@ -2,7 +2,7 @@ import packageJSON from '../../package.json' with { type: "json" }; const version = packageJSON.version; export default (req, res, next)=>{ - console.log(req); + console.log(req.headers); //check if req comes from localhost const userVersion = req.get('Homebrewery-Version'); From ef0ee787583a27748a47c03f149c262f86dbb75a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sun, 8 Dec 2024 23:43:06 +0100 Subject: [PATCH 04/19] revert check client version changes --- server/middleware/check-client-version.js | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/server/middleware/check-client-version.js b/server/middleware/check-client-version.js index 3cd30582e..19cb40b25 100644 --- a/server/middleware/check-client-version.js +++ b/server/middleware/check-client-version.js @@ -1,10 +1,9 @@ import packageJSON from '../../package.json' with { type: "json" }; const version = packageJSON.version; +//This should be only for internal calls, but right now prevents spam api calls, this should be done with a proper cors policy + export default (req, res, next)=>{ - console.log(req.headers); - //check if req comes from localhost - const userVersion = req.get('Homebrewery-Version'); if(userVersion != version) { From 23910cc94c6002696b436b13c5c332abf6408422 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sun, 8 Dec 2024 23:43:32 +0100 Subject: [PATCH 05/19] add cors policy and rename route --- package-lock.json | 14 ++++++++++++++ package.json | 1 + server/app.js | 47 ++++++++++++++++++++++++++++++++++++++--------- 3 files changed, 53 insertions(+), 9 deletions(-) diff --git a/package-lock.json b/package-lock.json index 820e01c46..bcff9a861 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19,6 +19,7 @@ "classnames": "^2.5.1", "codemirror": "^5.65.6", "cookie-parser": "^1.4.7", + "cors": "^2.8.5", "create-react-class": "^15.7.0", "dedent-tabs": "^0.10.3", "dompurify": "^3.2.2", @@ -4805,6 +4806,19 @@ "integrity": "sha512-ZQBvi1DcpJ4GDqanjucZ2Hj3wEO5pZDS89BWbkcrvdxksJorwUDDZamX9ldFkp9aw2lmBDLgkObEA4DWNJ9FYQ==", "license": "MIT" }, + "node_modules/cors": { + "version": "2.8.5", + "resolved": "https://registry.npmjs.org/cors/-/cors-2.8.5.tgz", + "integrity": "sha512-KIHbLJqu73RGr/hnbrO9uBeixNGuvSQjul/jdFvS/KFSIH1hWVd1ng7zOHx+YrEfInLG7q4n6GHQ9cDtxv/P6g==", + "license": "MIT", + "dependencies": { + "object-assign": "^4", + "vary": "^1" + }, + "engines": { + "node": ">= 0.10" + } + }, "node_modules/cosmiconfig": { "version": "9.0.0", "resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-9.0.0.tgz", diff --git a/package.json b/package.json index d5ea0b1de..2fa8bce4a 100644 --- a/package.json +++ b/package.json @@ -91,6 +91,7 @@ "classnames": "^2.5.1", "codemirror": "^5.65.6", "cookie-parser": "^1.4.7", + "cors": "^2.8.5", "create-react-class": "^15.7.0", "dedent-tabs": "^0.10.3", "dompurify": "^3.2.2", diff --git a/server/app.js b/server/app.js index fab56e624..4ec6ecdff 100644 --- a/server/app.js +++ b/server/app.js @@ -55,6 +55,31 @@ app.use(bodyParser.json({ limit: '25mb' })); app.use(cookieParser()); app.use(forceSSL); +import cors from 'cors'; + +// CORS Configuration +const corsOptions = { + + origin: (origin, callback) => { + const allowedOrigins = [ + 'https://homebrewery.naturalcrit.com', + 'http://localhost:8000', + 'http://localhost:8010', + 'https://naturalcrit.com' + ]; //allow natcrit local and live to call + if (!origin || allowedOrigins.includes(origin)) { + callback(null, true); + } else { + console.log(origin, 'not allowed'); + callback(new Error('Not allowed by CORS')); + } + }, + methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], + credentials: true, +}; + +app.use(cors(corsOptions)); + //Account Middleware app.use((req, res, next)=>{ if(req.cookies && req.cookies.nc_session){ @@ -313,9 +338,10 @@ app.get('/user/:username', async (req, res, next)=>{ }); //Rename Brews -app.put('/user/:username/rename-brews', async (req, res) => { - const { username } = req.params; - const { newUsername } = req.body; +app.put('/api/user/rename', async (req, res) => { + const { username, newUsername } = req.body; + + console.log('renaming'); if (!username || !newUsername) { return res.status(400).json({ error: 'Username and newUsername are required.' }); @@ -504,12 +530,15 @@ app.get('/vault', asyncHandler(async(req, res, next)=>{ })); //Send rendered page -app.use(asyncHandler(async (req, res, next)=>{ - if (!req.route) return res.redirect('/'); // Catch-all for invalid routes - - const page = await renderPage(req, res); - if(!page) return; - res.send(page); +app.use(asyncHandler(async (req, res, next) => { + if (!req.route && !req.path.startsWith('/api/')) { + return res.redirect('/'); + } + + const page = await renderPage(req, res); + if (!page) return; + + res.send(page); })); //Render the page From 4eb8abf1e7fdb5351261eccd404899138fa31ac9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sun, 8 Dec 2024 23:46:27 +0100 Subject: [PATCH 06/19] `Update CORS error message in app.js` --- server/app.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/app.js b/server/app.js index 4ec6ecdff..46aabc088 100644 --- a/server/app.js +++ b/server/app.js @@ -71,7 +71,7 @@ const corsOptions = { callback(null, true); } else { console.log(origin, 'not allowed'); - callback(new Error('Not allowed by CORS')); + callback(new Error('Not allowed by CORS, if you think this is an error, please contact us')); } }, methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], From 81f56ec91d864c73b41ed797869ac15f939d070d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Mon, 9 Dec 2024 18:59:48 +0100 Subject: [PATCH 07/19] add heroku apps to cors --- server/app.js | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) diff --git a/server/app.js b/server/app.js index 46aabc088..de44f0609 100644 --- a/server/app.js +++ b/server/app.js @@ -59,18 +59,20 @@ import cors from 'cors'; // CORS Configuration const corsOptions = { - origin: (origin, callback) => { const allowedOrigins = [ - 'https://homebrewery.naturalcrit.com', - 'http://localhost:8000', - 'http://localhost:8010', - 'https://naturalcrit.com' - ]; //allow natcrit local and live to call - if (!origin || allowedOrigins.includes(origin)) { + 'https://homebrewery.naturalcrit.com', + 'http://localhost:8000', + 'http://localhost:8010', + 'https://naturalcrit.com' + ]; + + const herokuRegex = /^https:\/\/.*\.herokuapp\.com$/; // Matches any Heroku app + + if (!origin || allowedOrigins.includes(origin) || herokuRegex.test(origin)) { callback(null, true); } else { - console.log(origin, 'not allowed'); + console.log(origin, 'not allowed'); callback(new Error('Not allowed by CORS, if you think this is an error, please contact us')); } }, @@ -78,6 +80,7 @@ const corsOptions = { credentials: true, }; + app.use(cors(corsOptions)); //Account Middleware From c29e1905bf4a578a42e1dd6fd86b89f3d0621c7a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Tue, 10 Dec 2024 19:24:23 +0100 Subject: [PATCH 08/19] add localhost to allowed origins only if in local, also remake regex --- server/app.js | 20 ++++++++++++-------- 1 file changed, 12 insertions(+), 8 deletions(-) diff --git a/server/app.js b/server/app.js index de44f0609..4c6c9ba1f 100644 --- a/server/app.js +++ b/server/app.js @@ -57,17 +57,24 @@ app.use(forceSSL); import cors from 'cors'; -// CORS Configuration +const nodeEnv = config.get('node_env'); +const isLocalEnvironment = config.get('local_environments').includes(nodeEnv); + const corsOptions = { origin: (origin, callback) => { + const allowedOrigins = [ 'https://homebrewery.naturalcrit.com', - 'http://localhost:8000', - 'http://localhost:8010', - 'https://naturalcrit.com' + 'https://naturalcrit.com', + 'https://naturalcrit-stage.herokuapp.com', + 'https://homebrewery-stage.herokuapp.com', ]; - const herokuRegex = /^https:\/\/.*\.herokuapp\.com$/; // Matches any Heroku app + if (isLocalEnvironment) { + allowedOrigins.push('http://localhost:8000', 'http://localhost:8010'); + } + + const herokuRegex = /^https:\/\/(?:homebrewery-pr-\d+\.herokuapp\.com|naturalcrit-pr-\d+\.herokuapp\.com)$/; // Matches any Heroku app if (!origin || allowedOrigins.includes(origin) || herokuRegex.test(origin)) { callback(null, true); @@ -80,7 +87,6 @@ const corsOptions = { credentials: true, }; - app.use(cors(corsOptions)); //Account Middleware @@ -505,8 +511,6 @@ app.get('/account', asyncHandler(async (req, res, next)=>{ return next(); })); -const nodeEnv = config.get('node_env'); -const isLocalEnvironment = config.get('local_environments').includes(nodeEnv); // Local only if(isLocalEnvironment){ // Login From 57cb334c15ad23b377347a183611c20eabdcacf8 Mon Sep 17 00:00:00 2001 From: Trevor Buckner Date: Tue, 10 Dec 2024 13:35:16 -0500 Subject: [PATCH 09/19] Update pull_request_template.md --- .github/pull_request_template.md | 25 +++++++++++++------------ 1 file changed, 13 insertions(+), 12 deletions(-) diff --git a/.github/pull_request_template.md b/.github/pull_request_template.md index b02835726..020653272 100644 --- a/.github/pull_request_template.md +++ b/.github/pull_request_template.md @@ -1,26 +1,29 @@ - +> [!TIP] +> Before submitting a Pull Request, please consider the following to speed up reviews: +> - 👷‍♀️ Create small PRs. Large PRs can usually be broken down into incremental PRs. +> - 🚩 Do you already have several open PRs? Consider finishing or asking for help with existing PRs first. +> - 🔧 Does your PR reference a discussed and approved issue, especially for personal or edge-case requests? +> - 💡 Is the solution agreed upon? Save rework time by discussing strategy before coding. ## Description +_Describe what your PR accomplishes. Consider walking through the main changes to aid reviewers in following your code, especially if it covers multiple files._ ## Related Issues or Discussions +> [!CAUTION] +> If no issue exists yet, create it, and get agreement on the approach (or paste in a previous agreement from chat, etc.) before moving forward. (Experimental PRs are OK without prior discussion, but do not expect to get merged.) + - Closes # ## QA Instructions, Screenshots, Recordings -_Please replace this line with instructions on how to test or view your changes, as well as any before/after -images for UI changes._ +_Replace this line with instructions on how to test or view your changes, as well as any before/after +screenshots or recordings for UI changes._ ### Reviewer Checklist -_Please replace the list below with specific features you want reviewers to look at._ +_Replace the list below with specific features you want reviewers to look at._ *Reviewers, refer to this list when testing features, or suggest new items * - [ ] Verify new features are functional @@ -32,5 +35,3 @@ _Please replace the list below with specific features you want reviewers to look - [ ] Feature A handles negative numbers - [ ] Identify opportunities for simplification and refactoring - [ ] Check for code legibility and appropriate comments - -
Copy this list From 5e5c637c79b252e4d5a1003bb0a9ce8235e4e76a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sat, 14 Dec 2024 20:59:51 +0100 Subject: [PATCH 10/19] revert api catch on wrong route middleware --- server/app.js | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/server/app.js b/server/app.js index 4c6c9ba1f..b10f36c4e 100644 --- a/server/app.js +++ b/server/app.js @@ -346,7 +346,7 @@ app.get('/user/:username', async (req, res, next)=>{ return next(); }); -//Rename Brews +//Change author name on brews app.put('/api/user/rename', async (req, res) => { const { username, newUsername } = req.body; @@ -538,14 +538,11 @@ app.get('/vault', asyncHandler(async(req, res, next)=>{ //Send rendered page app.use(asyncHandler(async (req, res, next) => { - if (!req.route && !req.path.startsWith('/api/')) { - return res.redirect('/'); - } + if (!req.route) return res.redirect('/'); // Catch-all for invalid routes - const page = await renderPage(req, res); - if (!page) return; - - res.send(page); + const page = await renderPage(req, res); + if(!page) return; + res.send(page); })); //Render the page From a1c228b1d1fb03b8b11e6ae1f1089d5c47b9434e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sat, 14 Dec 2024 21:01:38 +0100 Subject: [PATCH 11/19] log req account --- server/app.js | 2 ++ 1 file changed, 2 insertions(+) diff --git a/server/app.js b/server/app.js index b10f36c4e..6108c380d 100644 --- a/server/app.js +++ b/server/app.js @@ -277,6 +277,7 @@ app.get('/css/:id', asyncHandler(getBrew('share')), (req, res)=>{getCSS(req, res //User Page app.get('/user/:username', async (req, res, next)=>{ const ownAccount = req.account && (req.account.username == req.params.username); + console.log(req.account); req.ogMeta = { ...defaultMetaTags, title : `${req.params.username}'s Collection`, @@ -348,6 +349,7 @@ app.get('/user/:username', async (req, res, next)=>{ //Change author name on brews app.put('/api/user/rename', async (req, res) => { + console.log(req.account); const { username, newUsername } = req.body; console.log('renaming'); From f0c094e9d80459eb9ac9db2e9fb74eff7a1f1740 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sat, 14 Dec 2024 21:12:35 +0100 Subject: [PATCH 12/19] logs to account middleware --- server/app.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/server/app.js b/server/app.js index 6108c380d..40ec19ab6 100644 --- a/server/app.js +++ b/server/app.js @@ -91,12 +91,16 @@ app.use(cors(corsOptions)); //Account Middleware app.use((req, res, next)=>{ + console.log('passing through acc middleware') if(req.cookies && req.cookies.nc_session){ try { + console.log(`creating req.account equal to "${jwt.decode(req.cookies.nc_session, config.get('secret'))}"`); req.account = jwt.decode(req.cookies.nc_session, config.get('secret')); //console.log("Just loaded up JWT from cookie:"); //console.log(req.account); - } catch (e){} + } catch (e){ + console.log(e); + } } req.config = { From 666a94cd658c0ca71a3546db4f30bf0a1b724b98 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sat, 14 Dec 2024 21:15:16 +0100 Subject: [PATCH 13/19] fix log --- server/app.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/app.js b/server/app.js index 40ec19ab6..0b0cfb9d2 100644 --- a/server/app.js +++ b/server/app.js @@ -94,7 +94,7 @@ app.use((req, res, next)=>{ console.log('passing through acc middleware') if(req.cookies && req.cookies.nc_session){ try { - console.log(`creating req.account equal to "${jwt.decode(req.cookies.nc_session, config.get('secret'))}"`); + console.log(`creating req.account equal to "${JSON.stringify(jwt.decode(req.cookies.nc_session, config.get('secret')))}"`); req.account = jwt.decode(req.cookies.nc_session, config.get('secret')); //console.log("Just loaded up JWT from cookie:"); //console.log(req.account); From 4f57f006ce86154fe170e28b9950029295315e1b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sat, 14 Dec 2024 21:20:39 +0100 Subject: [PATCH 14/19] log cookies at auth middleware --- server/app.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/server/app.js b/server/app.js index 0b0cfb9d2..73eb876f8 100644 --- a/server/app.js +++ b/server/app.js @@ -91,7 +91,7 @@ app.use(cors(corsOptions)); //Account Middleware app.use((req, res, next)=>{ - console.log('passing through acc middleware') + console.log('passing through acc middleware, checking for cookies now: does cookies exist? ', !!req.cookies, ', ok, does the session cookie exist? ', !!req.cookies.nc_session); if(req.cookies && req.cookies.nc_session){ try { console.log(`creating req.account equal to "${JSON.stringify(jwt.decode(req.cookies.nc_session, config.get('secret')))}"`); From b26526a2f10626eadb897f530823de73f4853589 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sat, 14 Dec 2024 22:24:52 +0100 Subject: [PATCH 15/19] lint and logging pass prepared for in server auth from this end --- server/app.js | 102 +++++++++++++++++++++++++------------------------- 1 file changed, 50 insertions(+), 52 deletions(-) diff --git a/server/app.js b/server/app.js index 73eb876f8..58132b6f0 100644 --- a/server/app.js +++ b/server/app.js @@ -2,7 +2,7 @@ // Set working directory to project root import { dirname } from 'path'; import { fileURLToPath } from 'url'; -import packageJSON from './../package.json' with { type: "json" }; +import packageJSON from './../package.json' with { type: 'json' }; const __dirname = dirname(fileURLToPath(import.meta.url)); process.chdir(`${__dirname}/..`); @@ -26,7 +26,7 @@ import serveCompressedStaticAssets from './static-assets.mv.js'; import sanitizeFilename from 'sanitize-filename'; import asyncHandler from 'express-async-handler'; import templateFn from '../client/template.js'; -import {model as HomebrewModel } from './homebrew.model.js'; +import { model as HomebrewModel } from './homebrew.model.js'; import { DEFAULT_BREW } from './brewDefaults.js'; import { splitTextStyleAndMetadata } from '../shared/helpers.js'; @@ -47,7 +47,7 @@ const sanitizeBrew = (brew, accessType)=>{ return brew; }; -app.set('trust proxy', 1 /* number of proxies between user and server */) +app.set('trust proxy', 1 /* number of proxies between user and server */); app.use('/', serveCompressedStaticAssets(`build`)); app.use(contentNegotiation); @@ -61,30 +61,30 @@ const nodeEnv = config.get('node_env'); const isLocalEnvironment = config.get('local_environments').includes(nodeEnv); const corsOptions = { - origin: (origin, callback) => { + origin : (origin, callback)=>{ - const allowedOrigins = [ - 'https://homebrewery.naturalcrit.com', - 'https://naturalcrit.com', - 'https://naturalcrit-stage.herokuapp.com', - 'https://homebrewery-stage.herokuapp.com', - ]; + const allowedOrigins = [ + 'https://homebrewery.naturalcrit.com', + 'https://naturalcrit.com', + 'https://naturalcrit-stage.herokuapp.com', + 'https://homebrewery-stage.herokuapp.com', + ]; - if (isLocalEnvironment) { - allowedOrigins.push('http://localhost:8000', 'http://localhost:8010'); - } + if(isLocalEnvironment) { + allowedOrigins.push('http://localhost:8000', 'http://localhost:8010'); + } - const herokuRegex = /^https:\/\/(?:homebrewery-pr-\d+\.herokuapp\.com|naturalcrit-pr-\d+\.herokuapp\.com)$/; // Matches any Heroku app + const herokuRegex = /^https:\/\/(?:homebrewery-pr-\d+\.herokuapp\.com|naturalcrit-pr-\d+\.herokuapp\.com)$/; // Matches any Heroku app - if (!origin || allowedOrigins.includes(origin) || herokuRegex.test(origin)) { - callback(null, true); - } else { - console.log(origin, 'not allowed'); - callback(new Error('Not allowed by CORS, if you think this is an error, please contact us')); - } - }, - methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], - credentials: true, + if(!origin || allowedOrigins.includes(origin) || herokuRegex.test(origin)) { + callback(null, true); + } else { + console.log(origin, 'not allowed'); + callback(new Error('Not allowed by CORS, if you think this is an error, please contact us')); + } + }, + methods : ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], + credentials : true, }; app.use(cors(corsOptions)); @@ -94,7 +94,6 @@ app.use((req, res, next)=>{ console.log('passing through acc middleware, checking for cookies now: does cookies exist? ', !!req.cookies, ', ok, does the session cookie exist? ', !!req.cookies.nc_session); if(req.cookies && req.cookies.nc_session){ try { - console.log(`creating req.account equal to "${JSON.stringify(jwt.decode(req.cookies.nc_session, config.get('secret')))}"`); req.account = jwt.decode(req.cookies.nc_session, config.get('secret')); //console.log("Just loaded up JWT from cookie:"); //console.log(req.account); @@ -312,7 +311,7 @@ app.get('/user/:username', async (req, res, next)=>{ console.log(err); }); - brews.forEach(brew => brew.stubbed = true); //All brews from MongoDB are "stubbed" + brews.forEach((brew)=>brew.stubbed = true); //All brews from MongoDB are "stubbed" if(ownAccount && req?.account?.googleId){ const auth = await GoogleActions.authCheck(req.account, res); @@ -352,33 +351,32 @@ app.get('/user/:username', async (req, res, next)=>{ }); //Change author name on brews -app.put('/api/user/rename', async (req, res) => { +app.put('/api/user/rename', async (req, res)=>{ console.log(req.account); - const { username, newUsername } = req.body; - + const { username, newUsername } = req.body; + console.log(`is user ${req.account.username} equal to ${username}? ${req.account.username === username} ${req.account.username === username && 'then add the damn auth for renaming!'}`); console.log('renaming'); - if (!username || !newUsername) { - return res.status(400).json({ error: 'Username and newUsername are required.' }); - } - try { - const brews = await HomebrewModel.getByUser(username, true, ['authors']); - const renamePromises = brews.map(async (brew) => { - const updatedAuthors = brew.authors.map((author) => - author === username ? newUsername : author - ); - return HomebrewModel.updateOne( - { _id: brew._id }, - { $set: { authors: updatedAuthors } } - ); - }); - await Promise.all(renamePromises); + if(!username || !newUsername) { + return res.status(400).json({ error: 'Username and newUsername are required.' }); + } + try { + const brews = await HomebrewModel.getByUser(username, true, ['authors']); + const renamePromises = brews.map(async (brew)=>{ + const updatedAuthors = brew.authors.map((author)=>author === username ? newUsername : author + ); + return HomebrewModel.updateOne( + { _id: brew._id }, + { $set: { authors: updatedAuthors } } + ); + }); + await Promise.all(renamePromises); - return res.json({ success: true, message: `Brews for ${username} renamed to ${newUsername}.` }); - } catch (error) { - console.error('Error renaming brews:', error); - return res.status(500).json({ error: 'Failed to rename brews.' }); - } + return res.json({ success: true, message: `Brews for ${username} renamed to ${newUsername}.` }); + } catch (error) { + console.error('Error renaming brews:', error); + return res.status(500).json({ error: 'Failed to rename brews.' }); + } }); //Edit Page @@ -468,7 +466,7 @@ app.get('/share/:id', asyncHandler(getBrew('share')), asyncHandler(async (req, r app.get('/account', asyncHandler(async (req, res, next)=>{ const data = {}; data.title = 'Account Information Page'; - + if(!req.account) { res.set('WWW-Authenticate', 'Bearer realm="Authorization Required"'); const error = new Error('No valid account'); @@ -482,7 +480,7 @@ app.get('/account', asyncHandler(async (req, res, next)=>{ let googleCount = []; if(req.account) { if(req.account.googleId) { - auth = await GoogleActions.authCheck(req.account, res, false) + auth = await GoogleActions.authCheck(req.account, res, false); googleCount = await GoogleActions.listGoogleBrews(auth) .catch((err)=>{ @@ -543,8 +541,8 @@ app.get('/vault', asyncHandler(async(req, res, next)=>{ })); //Send rendered page -app.use(asyncHandler(async (req, res, next) => { - if (!req.route) return res.redirect('/'); // Catch-all for invalid routes +app.use(asyncHandler(async (req, res, next)=>{ + if(!req.route) return res.redirect('/'); // Catch-all for invalid routes const page = await renderPage(req, res); if(!page) return; From afc92c4545fd1529daedd7fca5e0dacec29590c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sat, 14 Dec 2024 22:30:24 +0100 Subject: [PATCH 16/19] fix check client version middleware to stop checking outside calls --- server/middleware/check-client-version.js | 26 ++++++++++++++--------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/server/middleware/check-client-version.js b/server/middleware/check-client-version.js index 19cb40b25..dcb18dace 100644 --- a/server/middleware/check-client-version.js +++ b/server/middleware/check-client-version.js @@ -1,16 +1,22 @@ import packageJSON from '../../package.json' with { type: "json" }; -const version = packageJSON.version; -//This should be only for internal calls, but right now prevents spam api calls, this should be done with a proper cors policy +export default (req, res, next) => { + const origin = req.get('Origin'); + const sameSite = req.get('Host'); -export default (req, res, next)=>{ - const userVersion = req.get('Homebrewery-Version'); + if (origin && origin !== `http://${sameSite}` && origin !== `https://${sameSite}`) { + return next(); // Skip version check if the request is from another site, like naturalcrit.com + } - if(userVersion != version) { - return res.status(412).send({ - message : `Client version ${userVersion} is out of date. Please save your changes elsewhere and refresh to pick up client version ${version}.` - }); - } + const userVersion = req.get('Homebrewery-Version'); + const version = packageJSON.version; - next(); + if (userVersion !== version) { + return res.status(412).send({ + message: `Client version ${userVersion} is out of date. Please save your changes elsewhere and refresh to pick up client version ${version}.` + }); + } + + next(); }; + From 99f2972079561b6f996756b36c2af842e06e7005 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sat, 14 Dec 2024 23:34:12 +0100 Subject: [PATCH 17/19] fixes as asked --- server/app.js | 2 -- server/homebrew.api.js | 11 +++++---- server/middleware/check-client-version.js | 27 +++++++++-------------- 3 files changed, 15 insertions(+), 25 deletions(-) diff --git a/server/app.js b/server/app.js index 58132b6f0..0d82642d9 100644 --- a/server/app.js +++ b/server/app.js @@ -280,7 +280,6 @@ app.get('/css/:id', asyncHandler(getBrew('share')), (req, res)=>{getCSS(req, res //User Page app.get('/user/:username', async (req, res, next)=>{ const ownAccount = req.account && (req.account.username == req.params.username); - console.log(req.account); req.ogMeta = { ...defaultMetaTags, title : `${req.params.username}'s Collection`, @@ -352,7 +351,6 @@ app.get('/user/:username', async (req, res, next)=>{ //Change author name on brews app.put('/api/user/rename', async (req, res)=>{ - console.log(req.account); const { username, newUsername } = req.body; console.log(`is user ${req.account.username} equal to ${username}? ${req.account.username === username} ${req.account.username === username && 'then add the damn auth for renaming!'}`); console.log('renaming'); diff --git a/server/homebrew.api.js b/server/homebrew.api.js index a75887742..159c08b47 100644 --- a/server/homebrew.api.js +++ b/server/homebrew.api.js @@ -467,12 +467,11 @@ const api = { } }; -router.use('/api', checkClientVersion); -router.post('/api', asyncHandler(api.newBrew)); -router.put('/api/:id', asyncHandler(api.getBrew('edit', true)), asyncHandler(api.updateBrew)); -router.put('/api/update/:id', asyncHandler(api.getBrew('edit', true)), asyncHandler(api.updateBrew)); -router.delete('/api/:id', asyncHandler(api.deleteBrew)); -router.get('/api/remove/:id', asyncHandler(api.deleteBrew)); +router.post('/api', checkClientVersion, asyncHandler(api.newBrew)); +router.put('/api/:id', checkClientVersion, asyncHandler(api.getBrew('edit', true)), asyncHandler(api.updateBrew)); +router.put('/api/update/:id', checkClientVersion, asyncHandler(api.getBrew('edit', true)), asyncHandler(api.updateBrew)); +router.delete('/api/:id', checkClientVersion, asyncHandler(api.deleteBrew)); +router.get('/api/remove/:id', checkClientVersion, asyncHandler(api.deleteBrew)); router.get('/api/theme/:renderer/:id', asyncHandler(api.getThemeBundle)); export default api; \ No newline at end of file diff --git a/server/middleware/check-client-version.js b/server/middleware/check-client-version.js index dcb18dace..45d868a5a 100644 --- a/server/middleware/check-client-version.js +++ b/server/middleware/check-client-version.js @@ -1,22 +1,15 @@ -import packageJSON from '../../package.json' with { type: "json" }; +import packageJSON from '../../package.json' with { type: 'json' }; -export default (req, res, next) => { - const origin = req.get('Origin'); - const sameSite = req.get('Host'); +export default (req, res, next)=>{ + const userVersion = req.get('Homebrewery-Version'); + const version = packageJSON.version; - if (origin && origin !== `http://${sameSite}` && origin !== `https://${sameSite}`) { - return next(); // Skip version check if the request is from another site, like naturalcrit.com - } + if(userVersion !== version) { + return res.status(412).send({ + message : `Client version ${userVersion} is out of date. Please save your changes elsewhere and refresh to pick up client version ${version}.` + }); + } - const userVersion = req.get('Homebrewery-Version'); - const version = packageJSON.version; - - if (userVersion !== version) { - return res.status(412).send({ - message: `Client version ${userVersion} is out of date. Please save your changes elsewhere and refresh to pick up client version ${version}.` - }); - } - - next(); + next(); }; From a9275698faecbc8211311591380dacb872dd4617 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADctor=20Losada=20Hern=C3=A1ndez?= Date: Sat, 14 Dec 2024 23:41:05 +0100 Subject: [PATCH 18/19] add comment to tell future me to remove logs when feature comes --- server/app.js | 3 +++ 1 file changed, 3 insertions(+) diff --git a/server/app.js b/server/app.js index 0d82642d9..39086cc21 100644 --- a/server/app.js +++ b/server/app.js @@ -352,6 +352,9 @@ app.get('/user/:username', async (req, res, next)=>{ //Change author name on brews app.put('/api/user/rename', async (req, res)=>{ const { username, newUsername } = req.body; + + //this next logs will be removed in a next PR, as i need to get this live to test if req.account is created when passing the request from naturalcrit.com + console.log(`is user ${req.account.username} equal to ${username}? ${req.account.username === username} ${req.account.username === username && 'then add the damn auth for renaming!'}`); console.log('renaming'); From fdaf9d4808499407489273c45b57ab6abb77e3f4 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sun, 15 Dec 2024 00:10:44 +0000 Subject: [PATCH 19/19] Bump react-router-dom from 6.28.0 to 7.0.2 Bumps [react-router-dom](https://github.com/remix-run/react-router/tree/HEAD/packages/react-router-dom) from 6.28.0 to 7.0.2. - [Release notes](https://github.com/remix-run/react-router/releases) - [Changelog](https://github.com/remix-run/react-router/blob/main/packages/react-router-dom/CHANGELOG.md) - [Commits](https://github.com/remix-run/react-router/commits/react-router-dom@7.0.2/packages/react-router-dom) --- updated-dependencies: - dependency-name: react-router-dom dependency-type: direct:production update-type: version-update:semver-major ... Signed-off-by: dependabot[bot] --- package-lock.json | 69 +++++++++++++++++++++++++++++++---------------- package.json | 2 +- 2 files changed, 47 insertions(+), 24 deletions(-) diff --git a/package-lock.json b/package-lock.json index 949829051..cb0cfc89d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -46,7 +46,7 @@ "react": "^18.3.1", "react-dom": "^18.3.1", "react-frame-component": "^4.1.3", - "react-router-dom": "6.28.0", + "react-router-dom": "7.0.2", "sanitize-filename": "1.6.3", "superagent": "^10.1.1", "vitreum": "git+https://git@github.com/calculuschild/vitreum.git" @@ -2897,14 +2897,6 @@ "node": ">= 8" } }, - "node_modules/@remix-run/router": { - "version": "1.21.0", - "resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.21.0.tgz", - "integrity": "sha512-xfSkCAchbdG5PnbrKqFWwia4Bi61nH+wm8wLEqfHDyp7Y3dZzgqS2itV8i4gAq9pC2HsTpwyBC6Ds8VHZ96JlA==", - "engines": { - "node": ">=14.0.0" - } - }, "node_modules/@sinclair/typebox": { "version": "0.27.8", "resolved": "https://registry.npmjs.org/@sinclair/typebox/-/typebox-0.27.8.tgz", @@ -2999,6 +2991,11 @@ "@babel/types": "^7.20.7" } }, + "node_modules/@types/cookie": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.6.0.tgz", + "integrity": "sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==" + }, "node_modules/@types/estree": { "version": "1.0.6", "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.6.tgz", @@ -12327,33 +12324,49 @@ "license": "MIT" }, "node_modules/react-router": { - "version": "6.28.0", - "resolved": "https://registry.npmjs.org/react-router/-/react-router-6.28.0.tgz", - "integrity": "sha512-HrYdIFqdrnhDw0PqG/AKjAqEqM7AvxCz0DQ4h2W8k6nqmc5uRBYDag0SBxx9iYz5G8gnuNVLzUe13wl9eAsXXg==", + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/react-router/-/react-router-7.0.2.tgz", + "integrity": "sha512-m5AcPfTRUcjwmhBzOJGEl6Y7+Crqyju0+TgTQxoS4SO+BkWbhOrcfZNq6wSWdl2BBbJbsAoBUb8ZacOFT+/JlA==", "dependencies": { - "@remix-run/router": "1.21.0" + "@types/cookie": "^0.6.0", + "cookie": "^1.0.1", + "set-cookie-parser": "^2.6.0", + "turbo-stream": "2.4.0" }, "engines": { - "node": ">=14.0.0" + "node": ">=20.0.0" }, "peerDependencies": { - "react": ">=16.8" + "react": ">=18", + "react-dom": ">=18" + }, + "peerDependenciesMeta": { + "react-dom": { + "optional": true + } } }, "node_modules/react-router-dom": { - "version": "6.28.0", - "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.28.0.tgz", - "integrity": "sha512-kQ7Unsl5YdyOltsPGl31zOjLrDv+m2VcIEcIHqYYD3Lp0UppLjrzcfJqDJwXxFw3TH/yvapbnUvPlAj7Kx5nbg==", + "version": "7.0.2", + "resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.0.2.tgz", + "integrity": "sha512-VJOQ+CDWFDGaWdrG12Nl+d7yHtLaurNgAQZVgaIy7/Xd+DojgmYLosFfZdGz1wpxmjJIAkAMVTKWcvkx1oggAw==", "dependencies": { - "@remix-run/router": "1.21.0", - "react-router": "6.28.0" + "react-router": "7.0.2" }, "engines": { - "node": ">=14.0.0" + "node": ">=20.0.0" }, "peerDependencies": { - "react": ">=16.8", - "react-dom": ">=16.8" + "react": ">=18", + "react-dom": ">=18" + } + }, + "node_modules/react-router/node_modules/cookie": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-1.0.2.tgz", + "integrity": "sha512-9Kr/j4O16ISv8zBBhJoi4bXOYNTkFLOqSL3UDB0njXxCXNezjeyVrJyGOWtgfs/q2km1gwBcfH8q1yEGoMYunA==", + "engines": { + "node": ">=18" } }, "node_modules/read-only-stream": { @@ -12913,6 +12926,11 @@ "node": ">= 0.8.0" } }, + "node_modules/set-cookie-parser": { + "version": "2.7.1", + "resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.1.tgz", + "integrity": "sha512-IOc8uWeOZgnb3ptbCURJWNjWUPcO3ZnTTdzsurqERrP6nPyv+paC55vJM0LpOlT2ne+Ix+9+CRG1MNLlyZ4GjQ==" + }, "node_modules/set-function-length": { "version": "1.2.2", "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", @@ -14405,6 +14423,11 @@ "integrity": "sha512-C3TaO7K81YvjCgQH9Q1S3R3P3BtN3RIM8n+OvX4il1K1zgE8ZhI0op7kClgkxtutIE8hQrcrHBXvIheqKUUCxw==", "license": "MIT" }, + "node_modules/turbo-stream": { + "version": "2.4.0", + "resolved": "https://registry.npmjs.org/turbo-stream/-/turbo-stream-2.4.0.tgz", + "integrity": "sha512-FHncC10WpBd2eOmGwpmQsWLDoK4cqsA/UT/GqNoaKOQnT8uzhtCbg3EoUDMvqpOSAI0S26mr0rkjzbOO6S3v1g==" + }, "node_modules/type-check": { "version": "0.4.0", "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", diff --git a/package.json b/package.json index 690fd7312..7c067d2e7 100644 --- a/package.json +++ b/package.json @@ -118,7 +118,7 @@ "react": "^18.3.1", "react-dom": "^18.3.1", "react-frame-component": "^4.1.3", - "react-router-dom": "6.28.0", + "react-router-dom": "7.0.2", "sanitize-filename": "1.6.3", "superagent": "^10.1.1", "vitreum": "git+https://git@github.com/calculuschild/vitreum.git"