Home > OS >  How to return a function instead of only values
How to return a function instead of only values

Time:09-28

Here is my code on server side

socket.on('new message', msg => {
   io.emit('new message', {
     name: socket.username,
     msg: msg   
   });
  });

and on client side

socket.on('new message', function(data) {
    var item = document.createElement('div');
    item.textContent = data.name data.msg;
    messages.appendChild(item);
    window.scrollTo(0, document.body.scrollHeight);
   });

it works but I want to go secure and expose source code as least as possible so I wonder if this possible to do it the other way around, like this?

socket.on('new message', msg => {
   io.emit('new message', () => {
    var item = document.createElement('div');
    item.textContent = socket.username msg;
    messages.appendChild(item);  
   });
  });

socket.on('new message', function(data) {
    data();
   });

this wont work but if there is a way please let me know.

CodePudding user response:

It looks like you are using socket.io, which sends JSON data over WebSockets, and JavaScript functions can't be serialized as JSON.

You could achieve this functionality by sending code as a string and calling eval to run it in your current context.

But aside from this being insecure (If the code sent can be affected by user input, and without proper sanitization it could lead to remote code execution on the browser), people could still see the code which is being sent and ran in their Browser's Network tab or by other means of inspecting network traffic.

At the end of the day, you can't really hide what runs on the browser, you can make effort to obfuscate it (There are plenty of tools that do this), but this just makes it harder to figure out the functionality, not impossible.

CodePudding user response:

Im sorry but I don't understand why you would hide appending a div to the dom from the user.

Any user that really wanted to view the clients logic can do just that, as everything is already available to them. If you are trying to 'obfuscate' your code and logic, then I suggest you think once again.

Edit: If you really want to continue, then paste this into the console tab of your browser's devtools.

function a(b) {
  return b   1;
}

String(a);

you should be able to figure it out.

  • Related