{"id":15645296,"url":"https://github.com/benjamn/private","last_synced_at":"2025-04-06T04:10:21.187Z","repository":{"id":60775127,"uuid":"9801367","full_name":"benjamn/private","owner":"benjamn","description":"Utility for associating truly private state with any JavaScript object","archived":false,"fork":false,"pushed_at":"2020-04-26T07:10:09.000Z","size":129,"stargazers_count":55,"open_issues_count":2,"forks_count":6,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-03-30T03:04:35.000Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/benjamn.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2013-05-01T22:28:00.000Z","updated_at":"2025-03-02T03:01:54.000Z","dependencies_parsed_at":"2022-10-04T16:35:04.625Z","dependency_job_id":null,"html_url":"https://github.com/benjamn/private","commit_stats":null,"previous_names":[],"tags_count":10,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/benjamn%2Fprivate","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/benjamn%2Fprivate/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/benjamn%2Fprivate/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/benjamn%2Fprivate/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/benjamn","download_url":"https://codeload.github.com/benjamn/private/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247430870,"owners_count":20937874,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-10-03T12:05:54.255Z","updated_at":"2025-04-06T04:10:21.054Z","avatar_url":"https://github.com/benjamn.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# private [![Build Status](https://travis-ci.org/benjamn/private.png?branch=master)](https://travis-ci.org/benjamn/private) [![Greenkeeper badge](https://badges.greenkeeper.io/benjamn/private.svg)](https://greenkeeper.io/)\n\nA general-purpose utility for associating truly private state with any JavaScript object.\n\nInstallation\n---\n\nFrom NPM:\n\n    npm install private\n\nFrom GitHub:\n\n    cd path/to/node_modules\n    git clone git://github.com/benjamn/private.git\n    cd private\n    npm install .\n\nUsage\n---\n**Get or create a secret object associated with any (non-frozen) object:**\n```js\nvar getSecret = require(\"private\").makeAccessor();\nvar obj = Object.create(null); // any kind of object works\ngetSecret(obj).totallySafeProperty = \"p455w0rd\";\n\nconsole.log(Object.keys(obj)); // []\nconsole.log(Object.getOwnPropertyNames(obj)); // []\nconsole.log(getSecret(obj)); // { totallySafeProperty: \"p455w0rd\" }\n```\nNow, only code that has a reference to both `getSecret` and `obj` can possibly access `.totallySafeProperty`.\n\n*Importantly, no global references to the secret object are retained by the `private` package, so as soon as `obj` gets garbage collected, the secret will be reclaimed as well. In other words, you don't have to worry about memory leaks.*\n\n**Create a unique property name that cannot be enumerated or guessed:**\n```js\nvar secretKey = require(\"private\").makeUniqueKey();\nvar obj = Object.create(null); // any kind of object works\n\nObject.defineProperty(obj, secretKey, {\n  value: { totallySafeProperty: \"p455w0rd\" },\n  enumerable: false // optional; non-enumerability is the default\n});\n\nObject.defineProperty(obj, \"nonEnumerableProperty\", {\n  value: \"anyone can guess my name\",\n  enumerable: false\n});\n\nconsole.log(obj[secretKey].totallySafeProperty); // p455w0rd\nconsole.log(obj.nonEnumerableProperty); // \"anyone can guess my name\"\nconsole.log(Object.keys(obj)); // []\nconsole.log(Object.getOwnPropertyNames(obj)); // [\"nonEnumerableProperty\"]\n\nfor (var key in obj) {\n  console.log(key); // never called\n}\n```\nBecause these keys are non-enumerable, you can't discover them using a `for`-`in` loop. Because `secretKey` is a long string of random characters, you would have a lot of trouble guessing it. And because the `private` module wraps `Object.getOwnPropertyNames` to exclude the keys it generates, you can't even use that interface to discover it.\n\nUnless you have access to the value of the `secretKey` property name, there is no way to access the value associated with it. So your only responsibility as secret-keeper is to avoid handing out the value of `secretKey` to untrusted code.\n\nThink of this style as a home-grown version of the first style. Note, however, that it requires a full implementation of ES5's `Object.defineProperty` method in order to make any safety guarantees, whereas the first example will provide safety even in environments that do not support `Object.defineProperty`.\n\nRationale\n---\n\nIn JavaScript, the only data that are truly private are local variables\nwhose values do not *leak* from the scope in which they were defined.\n\nThis notion of *closure privacy* is powerful, and it readily provides some\nof the benefits of traditional data privacy, a la Java or C++:\n```js\nfunction MyClass(secret) {\n    this.increment = function() {\n        return ++secret;\n    };\n}\n\nvar mc = new MyClass(3);\nconsole.log(mc.increment()); // 4\n```\nYou can learn something about `secret` by calling `.increment()`, and you\ncan increase its value by one as many times as you like, but you can never\ndecrease its value, because it is completely inaccessible except through\nthe `.increment` method. And if the `.increment` method were not\navailable, it would be as if no `secret` variable had ever been declared,\nas far as you could tell.\n\nThis style breaks down as soon as you want to inherit methods from the\nprototype of a class:\n```js\nfunction MyClass(secret) {\n    this.secret = secret;\n}\n\nMyClass.prototype.increment = function() {\n    return ++this.secret;\n};\n```\nThe only way to communicate between the `MyClass` constructor and the\n`.increment` method in this example is to manipulate shared properties of\n`this`. Unfortunately `this.secret` is now exposed to unlicensed\nmodification:\n```js\nvar mc = new MyClass(6);\nconsole.log(mc.increment()); // 7\nmc.secret -= Infinity;\nconsole.log(mc.increment()); // -Infinity\nmc.secret = \"Go home JavaScript, you're drunk.\";\nmc.increment(); // NaN\n```\nAnother problem with closure privacy is that it only lends itself to\nper-instance privacy, whereas the `private` keyword in most\nobject-oriented languages indicates that the data member in question is\nvisible to all instances of the same class.\n\nSuppose you have a `Node` class with a notion of parents and children:\n```js\nfunction Node() {\n    var parent;\n    var children = [];\n\n    this.getParent = function() {\n        return parent;\n    };\n\n    this.appendChild = function(child) {\n        children.push(child);\n        child.parent = this; // Can this be made to work?\n    };\n}\n```\nThe desire here is to allow other `Node` objects to manipulate the value\nreturned by `.getParent()`, but otherwise disallow any modification of the\n`parent` variable. You could expose a `.setParent` function, but then\nanyone could call it, and you might as well give up on the getter/setter\npattern.\n\nThis module solves both of these problems.\n\nUsage\n---\n\nLet's revisit the `Node` example from above:\n```js\nvar p = require(\"private\").makeAccessor();\n\nfunction Node() {\n    var privates = p(this);\n    var children = [];\n\n    this.getParent = function() {\n        return privates.parent;\n    };\n\n    this.appendChild = function(child) {\n        children.push(child);\n        var cp = p(child);\n        if (cp.parent)\n            cp.parent.removeChild(child);\n        cp.parent = this;\n        return child;\n    };\n}\n```\nNow, in order to access the private data of a `Node` object, you need to\nhave access to the unique `p` function that is being used here.  This is\nalready an improvement over the previous example, because it allows\nrestricted access by other `Node` instances, but can it help with the\n`Node.prototype` problem too?\n\nYes it can!\n```js\nvar p = require(\"private\").makeAccessor();\n\nfunction Node() {\n    p(this).children = [];\n}\n\nvar Np = Node.prototype;\n\nNp.getParent = function() {\n    return p(this).parent;\n};\n\nNp.appendChild = function(child) {\n    p(this).children.push(child);\n    var cp = p(child);\n    if (cp.parent)\n        cp.parent.removeChild(child);\n    cp.parent = this;\n    return child;\n};\n```\nBecause `p` is in scope not only within the `Node` constructor but also\nwithin `Node` methods, we can finally avoid redefining methods every time\nthe `Node` constructor is called.\n\nNow, you might be wondering how you can restrict access to `p` so that no\nuntrusted code is able to call it. The answer is to use your favorite\nmodule pattern, be it CommonJS, AMD `define`, or even the old\nImmediately-Invoked Function Expression:\n```js\nvar Node = (function() {\n    var p = require(\"private\").makeAccessor();\n\n    function Node() {\n        p(this).children = [];\n    }\n\n    var Np = Node.prototype;\n\n    Np.getParent = function() {\n        return p(this).parent;\n    };\n\n    Np.appendChild = function(child) {\n        p(this).children.push(child);\n        var cp = p(child);\n        if (cp.parent)\n            cp.parent.removeChild(child);\n        cp.parent = this;\n        return child;\n    };\n\n    return Node;\n}());\n\nvar parent = new Node;\nvar child = new Node;\nparent.appendChild(child);\nassert.strictEqual(child.getParent(), parent);\n```\nBecause this version of `p` never leaks from the enclosing function scope,\nonly `Node` objects have access to it.\n\nSo, you see, the claim I made at the beginning of this README remains\ntrue:\n\n\u003e In JavaScript, the only data that are truly private are local variables\n\u003e whose values do not *leak* from the scope in which they were defined.\n\nIt just so happens that closure privacy is sufficient to implement a\nprivacy model similar to that provided by other languages.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbenjamn%2Fprivate","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbenjamn%2Fprivate","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbenjamn%2Fprivate/lists"}