You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

245 lines
7.9 KiB

5 years ago
  1. # 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/)
  2. A general-purpose utility for associating truly private state with any JavaScript object.
  3. Installation
  4. ---
  5. From NPM:
  6. npm install private
  7. From GitHub:
  8. cd path/to/node_modules
  9. git clone git://github.com/benjamn/private.git
  10. cd private
  11. npm install .
  12. Usage
  13. ---
  14. **Get or create a secret object associated with any (non-frozen) object:**
  15. ```js
  16. var getSecret = require("private").makeAccessor();
  17. var obj = Object.create(null); // any kind of object works
  18. getSecret(obj).totallySafeProperty = "p455w0rd";
  19. console.log(Object.keys(obj)); // []
  20. console.log(Object.getOwnPropertyNames(obj)); // []
  21. console.log(getSecret(obj)); // { totallySafeProperty: "p455w0rd" }
  22. ```
  23. Now, only code that has a reference to both `getSecret` and `obj` can possibly access `.totallySafeProperty`.
  24. *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.*
  25. **Create a unique property name that cannot be enumerated or guessed:**
  26. ```js
  27. var secretKey = require("private").makeUniqueKey();
  28. var obj = Object.create(null); // any kind of object works
  29. Object.defineProperty(obj, secretKey, {
  30. value: { totallySafeProperty: "p455w0rd" },
  31. enumerable: false // optional; non-enumerability is the default
  32. });
  33. Object.defineProperty(obj, "nonEnumerableProperty", {
  34. value: "anyone can guess my name",
  35. enumerable: false
  36. });
  37. console.log(obj[secretKey].totallySafeProperty); // p455w0rd
  38. console.log(obj.nonEnumerableProperty); // "anyone can guess my name"
  39. console.log(Object.keys(obj)); // []
  40. console.log(Object.getOwnPropertyNames(obj)); // ["nonEnumerableProperty"]
  41. for (var key in obj) {
  42. console.log(key); // never called
  43. }
  44. ```
  45. Because 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.
  46. Unless 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.
  47. Think 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`.
  48. Rationale
  49. ---
  50. In JavaScript, the only data that are truly private are local variables
  51. whose values do not *leak* from the scope in which they were defined.
  52. This notion of *closure privacy* is powerful, and it readily provides some
  53. of the benefits of traditional data privacy, a la Java or C++:
  54. ```js
  55. function MyClass(secret) {
  56. this.increment = function() {
  57. return ++secret;
  58. };
  59. }
  60. var mc = new MyClass(3);
  61. console.log(mc.increment()); // 4
  62. ```
  63. You can learn something about `secret` by calling `.increment()`, and you
  64. can increase its value by one as many times as you like, but you can never
  65. decrease its value, because it is completely inaccessible except through
  66. the `.increment` method. And if the `.increment` method were not
  67. available, it would be as if no `secret` variable had ever been declared,
  68. as far as you could tell.
  69. This style breaks down as soon as you want to inherit methods from the
  70. prototype of a class:
  71. ```js
  72. function MyClass(secret) {
  73. this.secret = secret;
  74. }
  75. MyClass.prototype.increment = function() {
  76. return ++this.secret;
  77. };
  78. ```
  79. The only way to communicate between the `MyClass` constructor and the
  80. `.increment` method in this example is to manipulate shared properties of
  81. `this`. Unfortunately `this.secret` is now exposed to unlicensed
  82. modification:
  83. ```js
  84. var mc = new MyClass(6);
  85. console.log(mc.increment()); // 7
  86. mc.secret -= Infinity;
  87. console.log(mc.increment()); // -Infinity
  88. mc.secret = "Go home JavaScript, you're drunk.";
  89. mc.increment(); // NaN
  90. ```
  91. Another problem with closure privacy is that it only lends itself to
  92. per-instance privacy, whereas the `private` keyword in most
  93. object-oriented languages indicates that the data member in question is
  94. visible to all instances of the same class.
  95. Suppose you have a `Node` class with a notion of parents and children:
  96. ```js
  97. function Node() {
  98. var parent;
  99. var children = [];
  100. this.getParent = function() {
  101. return parent;
  102. };
  103. this.appendChild = function(child) {
  104. children.push(child);
  105. child.parent = this; // Can this be made to work?
  106. };
  107. }
  108. ```
  109. The desire here is to allow other `Node` objects to manipulate the value
  110. returned by `.getParent()`, but otherwise disallow any modification of the
  111. `parent` variable. You could expose a `.setParent` function, but then
  112. anyone could call it, and you might as well give up on the getter/setter
  113. pattern.
  114. This module solves both of these problems.
  115. Usage
  116. ---
  117. Let's revisit the `Node` example from above:
  118. ```js
  119. var p = require("private").makeAccessor();
  120. function Node() {
  121. var privates = p(this);
  122. var children = [];
  123. this.getParent = function() {
  124. return privates.parent;
  125. };
  126. this.appendChild = function(child) {
  127. children.push(child);
  128. var cp = p(child);
  129. if (cp.parent)
  130. cp.parent.removeChild(child);
  131. cp.parent = this;
  132. return child;
  133. };
  134. }
  135. ```
  136. Now, in order to access the private data of a `Node` object, you need to
  137. have access to the unique `p` function that is being used here. This is
  138. already an improvement over the previous example, because it allows
  139. restricted access by other `Node` instances, but can it help with the
  140. `Node.prototype` problem too?
  141. Yes it can!
  142. ```js
  143. var p = require("private").makeAccessor();
  144. function Node() {
  145. p(this).children = [];
  146. }
  147. var Np = Node.prototype;
  148. Np.getParent = function() {
  149. return p(this).parent;
  150. };
  151. Np.appendChild = function(child) {
  152. p(this).children.push(child);
  153. var cp = p(child);
  154. if (cp.parent)
  155. cp.parent.removeChild(child);
  156. cp.parent = this;
  157. return child;
  158. };
  159. ```
  160. Because `p` is in scope not only within the `Node` constructor but also
  161. within `Node` methods, we can finally avoid redefining methods every time
  162. the `Node` constructor is called.
  163. Now, you might be wondering how you can restrict access to `p` so that no
  164. untrusted code is able to call it. The answer is to use your favorite
  165. module pattern, be it CommonJS, AMD `define`, or even the old
  166. Immediately-Invoked Function Expression:
  167. ```js
  168. var Node = (function() {
  169. var p = require("private").makeAccessor();
  170. function Node() {
  171. p(this).children = [];
  172. }
  173. var Np = Node.prototype;
  174. Np.getParent = function() {
  175. return p(this).parent;
  176. };
  177. Np.appendChild = function(child) {
  178. p(this).children.push(child);
  179. var cp = p(child);
  180. if (cp.parent)
  181. cp.parent.removeChild(child);
  182. cp.parent = this;
  183. return child;
  184. };
  185. return Node;
  186. }());
  187. var parent = new Node;
  188. var child = new Node;
  189. parent.appendChild(child);
  190. assert.strictEqual(child.getParent(), parent);
  191. ```
  192. Because this version of `p` never leaks from the enclosing function scope,
  193. only `Node` objects have access to it.
  194. So, you see, the claim I made at the beginning of this README remains
  195. true:
  196. > In JavaScript, the only data that are truly private are local variables
  197. > whose values do not *leak* from the scope in which they were defined.
  198. It just so happens that closure privacy is sufficient to implement a
  199. privacy model similar to that provided by other languages.