Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion app/auth.js
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ export const auth = betterAuth({
organization(),
multiSession(),
expo(),
bearer(),
bearer(),
],
trustedOrigins: [process.env.BETTER_AUTH_URL],
})
2 changes: 1 addition & 1 deletion app/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -467,7 +467,7 @@ export const auth = betterAuth({
organization(),
multiSession(),
expo(),
bearer(),
bearer(),
],
trustedOrigins: [process.env.BETTER_AUTH_URL],
})
2 changes: 1 addition & 1 deletion app/client/global/styles.css
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ body {
top: 0px;
left: 0px;
width: 100vw;
height: 100vh;
height: 100dvh;
background-color: #f4f4f4;
font-family: 'Figtree', sans-serif;
user-select: none;
Expand Down
45 changes: 19 additions & 26 deletions app/client/pages/channelpage.html
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@
if (element.parentmessageid == undefined) {
if (lastsenderid == element.userid) {
$("#messagearea").append(`
<div class="messagebox" style="margin-top: 10px; margin-left: 50px;" onclick="currentmessageid = '` + element.id + `'; NavigatePage('channelthreadpage')">
<span class="">
<div class="messagebox" style="margin-top: 10px; margin-left: 50px;" onclick="currentmessageid = '` + element.id + `'; NavigatePage('channelthreadpage')" data-messageid="` + element.id + `">
<span class="mstack">
<span class="message">
` + sanitizeHTML(element.content) + `
</span>
Expand All @@ -52,9 +52,9 @@
}
})
$("#messagearea").append(`
<div class="messagebox expandedmessagebox" onclick="currentmessageid = '` + element.id + `'; NavigatePage('channelthreadpage')">
<div class="messagebox expandedmessagebox" onclick="currentmessageid = '` + element.id + `'; NavigatePage('channelthreadpage')" data-messageid="` + element.id + `">
<img src="` + currentpfp + `" class="messageprofilepicture" />
<span class="message">
<span class="message mstack">
<b class="message-sendername">` + sanitizeHTML(element.sendername) + ` </b>
<span style="font-size: small;">
` + monthNames[d.getMonth()] + " " + d.getDate().toString() + " " + (d.getHours() < 10 ? '0' : '') + d.getHours().toString() + ":" + (d.getMinutes() < 10 ? '0' : '') + d.getMinutes().toString() + `
Expand All @@ -68,6 +68,14 @@
`)
}
lastsenderid = element.userid
} else {
var refmessage = $("#messagearea").find("[data-messageid='" + element.parentmessageid + "']")
if(refmessage.attr("isthread") != "true") {
refmessage.attr("isthread", "true")
refmessage.find(".mstack").append(`
<div class="threadviewbutton" onclick="currentmessageid = '` + element.parentmessageid + `; NavigatePage('channelthreadpage')">View Thread</div>
`)
}
}

// Broken Code
Expand Down Expand Up @@ -124,8 +132,8 @@
}
if (lastsenderid == element.sender) {
$("#messagearea").append(`
<div class="messagebox" style="margin-top: 10px; margin-left: 50px;" onclick="currentmessageid = '` + element.id + `'; NavigatePage('channelthreadpage')">
<span class="">
<div class="messagebox" style="margin-top: 10px; margin-left: 50px;" onclick="currentmessageid = '` + element.id + `'; NavigatePage('channelthreadpage')" data-messageid="` + element.id + `" ` + (extramessageui ? 'isthread="true"' : "") + `>
<span class="mstack">
<span class="messagetext">
` + sanitizeHTML(element.content) + `
</span>
Expand All @@ -145,9 +153,9 @@
}
})
$("#messagearea").append(`
<div class="messagebox expandedmessagebox" onclick="currentmessageid = '` + element.id + `'; NavigatePage('channelthreadpage')">
<div class="messagebox expandedmessagebox" onclick="currentmessageid = '` + element.id + `'; NavigatePage('channelthreadpage')" data-messageid="` + element.id + `" ` + (extramessageui ? 'isthread="true"' : "") + `>
<img src="` + currentpfp + `" class="messageprofilepicture" />
<span class="message">
<span class="message mstack">
<b class="message-sendername">` + sanitizeHTML(element.sendername) + ` </b>
<span style="font-size: small;">
` + monthNames[d.getMonth()] + " " + d.getDate().toString() + " " + (d.getHours() < 10 ? '0' : '') + d.getHours().toString() + ":" + (d.getMinutes() < 10 ? '0' : '') + d.getMinutes().toString() + `
Expand All @@ -167,29 +175,14 @@
}

var sendmessage = function(msg) {
fetch("/api/channel/" + currentchannelid + "/messages/send?message=" + msg, {
"method": "POST",
})

.then(function (response) {
console.log(response.status);
return response.text();
})

.then(function (data) {
console.log(data);
})

.catch(function (error) {
console.log(error.message);
});

socket.emit("clatter.channel.message.send", JSON.stringify({
"room": currentchannelid,
"userid": authsession.data.user.id,
"sendername": authsession.data.user.name,
"content": msg,
"type": "text"
"type": "text",
"method": "modern",
"token": authsession.data.session.token,
}))
}

Expand Down
21 changes: 3 additions & 18 deletions app/client/pages/channelthreadpage.html
Original file line number Diff line number Diff line change
Expand Up @@ -223,30 +223,15 @@
}

var sendmessage = function(msg) {
fetch("/api/channel/" + currentchannelid + "/thread/" + currentmessageid + "/send?message=" + msg, {
"method": "POST",
})

.then(function (response) {
console.log(response.status);
return response.text();
})

.then(function (data) {
console.log(data);
})

.catch(function (error) {
console.log(error.message);
});

socket.emit("clatter.channel.message.send", JSON.stringify({
"room": currentchannelid,
"userid": authsession.data.user.id,
"sendername": authsession.data.user.name,
"content": msg,
"type": "text",
"parentmessageid": currentmessageid
"parentmessageid": currentmessageid,
"method": "modern",
"token": authsession.data.session.token,
}))
}

Expand Down
43 changes: 35 additions & 8 deletions app/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,19 @@ import { createServer } from "http"
const app = express();
const server = createServer(app)
const prisma = new PrismaClient()
const io = new Server(server)
const io = new Server(server, {
cors: {
origin: "*",
},
})
Comment on lines +13 to +17
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Security concern: Overly permissive CORS configuration.

Using wildcard origin ("*") in CORS configuration allows any domain to access your API, which poses a significant security risk. This configuration enables cross-origin requests from potentially malicious websites.

Apply this diff to restrict CORS to specific allowed origins:

-const io = new Server(server, {
-    cors: {
-        origin: "*",
-    },
-})
+const io = new Server(server, {
+    cors: {
+        origin: process.env.ALLOWED_ORIGINS?.split(',') || ["http://localhost:3000"],
+        credentials: true,
+    },
+})
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const io = new Server(server, {
cors: {
origin: "*",
},
})
const io = new Server(server, {
cors: {
origin: process.env.ALLOWED_ORIGINS?.split(',') || ["http://localhost:3000"],
credentials: true,
},
})
🤖 Prompt for AI Agents
In app/server.js around lines 13 to 17, the CORS configuration uses a wildcard
origin "*" which is overly permissive and insecure. Replace the wildcard with a
list of specific allowed origins by defining an array of trusted domain URLs and
setting the cors.origin option to this array. This restricts cross-origin
requests to only those trusted domains, improving security.


// app.use(
// cors({
// origin: "*", // Replace with your frontend's origin
// methods: ["GET", "POST", "PUT", "DELETE"], // Specify allowed HTTP methods
// credentials: true, // Allow credentials (cookies, authorization headers, etc.)
// })
// );
app.use(
cors({
origin: "*", // Replace with your frontend's origin
methods: ["GET", "POST", "PUT", "DELETE"], // Specify allowed HTTP methods
credentials: true, // Allow credentials (cookies, authorization headers, etc.)
})
);
Comment on lines +19 to +25
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Security concern: Overly permissive CORS configuration in Express middleware.

Similar to the Socket.IO CORS configuration, allowing all origins ("*") with credentials enabled creates a security vulnerability. This combination is particularly dangerous as it allows any website to make authenticated requests to your API.

Apply this diff to secure the CORS configuration:

-app.use(
-    cors({
-      origin: "*", // Replace with your frontend's origin
-      methods: ["GET", "POST", "PUT", "DELETE"], // Specify allowed HTTP methods
-      credentials: true, // Allow credentials (cookies, authorization headers, etc.)
-    })
-);
+app.use(
+    cors({
+      origin: process.env.ALLOWED_ORIGINS?.split(',') || ["http://localhost:3000"],
+      methods: ["GET", "POST", "PUT", "DELETE"],
+      credentials: true,
+    })
+);
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
app.use(
cors({
origin: "*", // Replace with your frontend's origin
methods: ["GET", "POST", "PUT", "DELETE"], // Specify allowed HTTP methods
credentials: true, // Allow credentials (cookies, authorization headers, etc.)
})
);
app.use(
cors({
origin: process.env.ALLOWED_ORIGINS?.split(',') || ["http://localhost:3000"],
methods: ["GET", "POST", "PUT", "DELETE"],
credentials: true,
})
);
🤖 Prompt for AI Agents
In app/server.js around lines 19 to 25, the CORS middleware is configured with
origin set to "*" while credentials are enabled, which is a security risk. To
fix this, replace the wildcard origin with a specific allowed origin or a list
of trusted origins matching your frontend URLs, and keep credentials enabled
only if necessary. This ensures only authorized frontends can make authenticated
requests to your API.


app.all("/api/auth/*", toNodeHandler(auth));

Expand Down Expand Up @@ -250,6 +254,29 @@ io.on("connection", (socket) => {

argjson.DateCreated = new Date().toISOString()

if(argjson.method === "modern") {
const session = await auth.api.getSession({
headers: new Headers({
authorization: "Bearer " + argjson.token
})
});
if(argjson.parentmessageid) {
var parentid = argjson.parentmessageid
} else {
var parentid = null
}
var message = await prisma.message.create({
data: {
content: argjson.content,
sender: session.session.userId,
parentid: argjson.room,
parentmessageid: parentid,
sendername: session.user.name
}
})
argjson.id = message.id
}
Comment on lines +257 to +278
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix variable redeclaration and improve error handling.

The static analysis tool correctly identifies a variable redeclaration issue with parentid. Additionally, the code lacks proper error handling for authentication failures and database operations.

Apply this diff to fix the variable redeclaration and add error handling:

-    if(argjson.method === "modern") {
-      const session = await auth.api.getSession({
-        headers: new Headers({
-          authorization: "Bearer " + argjson.token
-        })
-      });
-      if(argjson.parentmessageid) {
-        var parentid = argjson.parentmessageid
-      } else {
-        var parentid = null
-      }
-      var message = await prisma.message.create({
-        data: {
-          content: argjson.content,
-          sender: session.session.userId,
-          parentid: argjson.room,
-          parentmessageid: parentid,
-          sendername: session.user.name
-        }
-      })
-      argjson.id = message.id
-    }
+    if(argjson.method === "modern") {
+      try {
+        const session = await auth.api.getSession({
+          headers: new Headers({
+            authorization: "Bearer " + argjson.token
+          })
+        });
+        
+        if (!session || !session.session?.userId) {
+          socket.emit("clatter.channel.message.send.error", "Authentication failed");
+          return;
+        }
+        
+        const parentMessageId = argjson.parentmessageid || null;
+        
+        const message = await prisma.message.create({
+          data: {
+            content: argjson.content,
+            sender: session.session.userId,
+            parentid: argjson.room,
+            parentmessageid: parentMessageId,
+            sendername: session.user.name
+          }
+        });
+        
+        argjson.id = message.id;
+      } catch (error) {
+        console.error("Error processing modern message:", error);
+        socket.emit("clatter.channel.message.send.error", "Failed to send message");
+        return;
+      }
+    }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if(argjson.method === "modern") {
const session = await auth.api.getSession({
headers: new Headers({
authorization: "Bearer " + argjson.token
})
});
if(argjson.parentmessageid) {
var parentid = argjson.parentmessageid
} else {
var parentid = null
}
var message = await prisma.message.create({
data: {
content: argjson.content,
sender: session.session.userId,
parentid: argjson.room,
parentmessageid: parentid,
sendername: session.user.name
}
})
argjson.id = message.id
}
if (argjson.method === "modern") {
try {
const session = await auth.api.getSession({
headers: new Headers({
authorization: "Bearer " + argjson.token
})
});
if (!session || !session.session?.userId) {
socket.emit("clatter.channel.message.send.error", "Authentication failed");
return;
}
const parentMessageId = argjson.parentmessageid || null;
const message = await prisma.message.create({
data: {
content: argjson.content,
sender: session.session.userId,
parentid: argjson.room,
parentmessageid: parentMessageId,
sendername: session.user.name
}
});
argjson.id = message.id;
} catch (error) {
console.error("Error processing modern message:", error);
socket.emit("clatter.channel.message.send.error", "Failed to send message");
return;
}
}
🧰 Tools
🪛 Biome (1.9.4)

[error] 266-266: Shouldn't redeclare 'parentid'. Consider to delete it or rename it.

'parentid' is defined here:

(lint/suspicious/noRedeclare)

🤖 Prompt for AI Agents
In app/server.js around lines 257 to 278, fix the variable redeclaration by
declaring 'parentid' once using 'let' before the if-else block and assign its
value conditionally. Add try-catch blocks around the authentication call and the
database create operation to handle potential errors gracefully, logging or
responding appropriately to authentication failures and database errors.


socket.emit("clatter.channel.message.send.response", "Sent Message")
socket.to(argjson.room).emit("clatter.channel.message.recieve", JSON.stringify(argjson))
})
Expand Down