tobiak777
tobiak777

Reputation: 3365

Are javascript private variables really safe?

I'm considering letting other people inject scripts in my web page. I have a number of secrets which are known by the user, so I don't mind if for example the user opens the debugger to inspect the variables. (Real secrets and real security are of course handled in the backend)

What I do not want is to let these third party scripts access these secrets.

So here is my question : can an external code access the private members of my objects ? Or put differently : how safe are private variables in JavaScript ? I'm perplex because the way I understand it, it seems like prototypes don't really help keeping secrets. At the same time I'm thinking that this security consideration might be the responsibility of web browsers but I'm not 100% sure here.

Thanks a lot !

Edit: I'm specifically thinking of the case where a malicious person will look at the source and deliberately write a code trying to extract the value of these private members. I want to know to which extent this is possible - if it is at all.

Edit:

I was referring to what TypeScript call "private" variables which translates to :

class Greeter {
    private greeting: string;
    public message: string;
    constructor(message: string) {
        this.message = message;
    }
    greet() {
        return "Hello, " + this.message;
    }
}

Looking at the JS, I can understand why it isn't very safe. I almost forgot TypeScript is not JS. But I'm generally talking about any way to encapsulate javascript.

Upvotes: 0

Views: 442

Answers (1)

Quentin
Quentin

Reputation: 944426

What I do not want is to let these third party scripts access these secrets.

Then don't give them access to the page. Lock them away in cross-origin iframe sandboxes.

Can an external code access the private members of my objects?

Yes. It might have to jump through some horrible hoops to do so (depending on how you implement the privacy) but I can't think of any way to reliably protect code from other code in the same JS environment.

How put differently : how safe are private variables in JavaScript ?

Not very.

At the same time I'm thinking that this security consideration might be the responsibility of web browsers

It is only up until the point where you load third party source code into your program.

Upvotes: 2

Related Questions