Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 31

Revocable Proxy for Temporary Access

This lesson is built with resources from developer.mozilla.org and javascript.info.

Hello! Welcome to the next lesson in our module on Metaprogramming with Proxies and Reflect.

In our previous lessons, we've explored how to intercept and customize fundamental object operations. We used the set trap to build observable objects and the get trap to implement elegant features like negative array indexing and default property values. So far, we've focused on controlling individual operations. Today, we'll zoom out and learn how to control the entire lifecycle of access to an object.

Our learning outcome is to create a revocable proxy for temporary access control that can be turned off. This is a powerful pattern for security and resource management, allowing you to grant access to an object and then completely invalidate that access at a later time, much like revoking a temporary API key or a security badge.

From Permanent to Temporary Access

Until now, the proxies we've created using new Proxy(target, handler) have been permanent. Once created, they continue to forward operations to the target object indefinitely. But what if you only want to grant access for a limited time or under specific conditions?

This is where revocable proxies come in. Instead of using the Proxy constructor, we use the Proxy.revocable() static factory method.

Proxy.revocable() - JavaScript - MDN Web Docs

To understand the basic mechanics, let's turn to the MDN Web Docs. This resource provides the canonical definition for Proxy.revocable(), its syntax, and its unique return value.

Please read the introduction, along with the 'Syntax', 'Parameters', and 'Return value' sections. The key takeaway is that this method returns an object containing both the proxy and a revoke function.

As you saw in the reading, the key difference is the return value. While new Proxy() returns just the proxy object, Proxy.revocable() returns an object with two properties:

  1. proxy: The proxy object itself, which works just like one created with new Proxy().
  2. revoke: A function that, when called, "switches off" the proxy.

Let's see this in action. The destructuring assignment syntax is perfect for capturing these two parts:

let target = {
  sensitiveData: "Initial Value"
};

let handler = {
  get(target, prop) {
    console.log(`Reading '${prop}'`);
    return target[prop];
  },
  set(target, prop, value) {
    console.log(`Writing '${prop}'`);
    target[prop] = value;
    return true;
  }
};

// Create the revocable proxy
const { proxy, revoke } = Proxy.revocable(target, handler);

// Interact with the proxy - this works as expected
console.log(proxy.sensitiveData); // Logs: Reading 'sensitiveData', then "Initial Value"
proxy.sensitiveData = "New Value";  // Logs: Writing 'sensitiveData'

console.log(target.sensitiveData); // "New Value"

The Act of Revocation

The revoke function is the control switch. Once you call it, the connection between the proxy and its target/handler is severed permanently. Any subsequent attempt to use the proxy (to get, set, or perform any other operation) will result in a TypeError.

Proxy.revocable() - JavaScript - MDN Web Docs

The MDN documentation also clearly explains the consequences of calling revoke(). This is essential for understanding the error behavior and the memory management benefits.

Please read the 'Description' section and carefully review the code in the 'Using Proxy.revocable()' example. Focus on what happens after revoke() is called and note the mention of garbage collection.

Let's continue our previous example and see what happens when we call revoke:

// ... from the previous code block

// Now, we revoke access.
console.log("Revoking access...");
revoke();

// Any attempt to use the proxy now will fail.
try {
  proxy.sensitiveData = "Attempting to write after revoke";
} catch (e) {
  console.error(e.message); // "Cannot perform 'set' on a proxy that has been revoked"
}

try {
  console.log(proxy.sensitiveData);
} catch (e) {
  console.error(e.message); // "Cannot perform 'get' on a proxy that has been revoked"
}

// Note: The original target object is unaffected.
console.log(target.sensitiveData); // "New Value"

This "fail-fast" behavior is highly desirable. Instead of an operation silently failing or working with stale data, the program immediately throws an error, making bugs related to expired access obvious.


Use Cases and a Key Design Choice

The power of this pattern lies in separating the capability (proxy) from the control switch (revoke). You can pass the proxy object to a different part of your applicationβ€”or even untrusted third-party codeβ€”while keeping the revoke function safely within your own scope.

Proxy and Reflect

The javascript.info article offers a practical perspective on this design, explaining why separating proxy and revoke is a deliberate and useful feature for access control.

Please read the section titled 'Revocable proxies'. Pay close attention to the example and the author's explanation of why proxy and revoke are separate.

This pattern is ideal for scenarios such as:

  • One-time setup: A function is given a proxy to a configuration object to perform its initial setup. Once setup is complete, the caller revokes the proxy to ensure the configuration is not modified later.
  • User sessions: When a user logs out, you can revoke proxies associated with their session data, ensuring no part of the UI can accidentally access or display stale, sensitive information.
  • Resource management: If a proxy wraps a live resource like a WebSocket connection, you can revoke the proxy when the connection closes. This prevents other parts of the code from trying to send messages over a dead connection.
Test your understanding!

Imagine you're building a simple plugin system. You want to allow a plugin to read and write to a shared state object, but only during its initialize phase.

Create a function runPlugin(plugin, state) that:

  1. Creates a revocable proxy for the state object.
  2. Calls the plugin's initialize method, passing the proxy to it.
  3. After initialize completes, immediately revokes the proxy.

Test it with a sample plugin that tries to access the state both inside and outside its initialize method.

const plugin = {
  initialize(stateProxy) {
    console.log("Plugin initializing...");
    stateProxy.pluginInitialized = true;
    console.log("Plugin can write to state:", stateProxy.pluginInitialized);
  },
  doSomethingLater(stateProxy) {
    // This should fail!
    console.log("Plugin trying to access state later...");
    stateProxy.sneakyUpdate = true;
  }
};
Show answer

Here's a possible implementation of runPlugin:

function runPlugin(plugin, state) {
  const { proxy, revoke } = Proxy.revocable(state, {});

  try {
    // Give the plugin temporary access
    plugin.initialize(proxy);
  } finally {
    // Ensure access is revoked, even if the plugin throws an error
    console.log("Revoking plugin access to state.");
    revoke();
  }
  
  // Return the proxy so we can test its revoked state
  return proxy;
}

const sharedState = { data: "some data" };
const pluginProxy = runPlugin(plugin, sharedState);

// The state should be updated from the initialize call
console.log("Shared state after init:", sharedState); // { data: 'some data', pluginInitialized: true }

// Now, let's see what happens if the plugin tries to use its (now revoked) proxy
try {
  plugin.doSomethingLater(pluginProxy);
} catch (e) {
  console.error("Caught expected error:", e.message); 
  // "Caught expected error: Cannot perform 'set' on a proxy that has been revoked"
}

This demonstrates how Proxy.revocable effectively creates a "sandbox" for the initialize method, guaranteeing that access is cut off once the operation is complete.


Preview: Managing Multiple Revocable Proxies

A natural question arises: if you create many revocable proxies, how do you keep track of which revoke function corresponds to which proxy? You can't store the revoke function on the proxy itself, as that would give the proxy's user the ability to revoke their own access.

This is a problem of associating private metadata with an objectβ€”a perfect lead-in to our next topic.

Proxy and Reflect

The javascript.info article continues by proposing an elegant solution to this very problem using a WeakMap. This is a fantastic preview of our next lesson, which focuses on using WeakMap for memory-safe metadata storage.

Read the rest of the 'Revocable proxies' section, focusing on the part that introduces WeakMap. Note the problem it solves and the reasoning for choosing WeakMap over a standard Map.

The use of WeakMap here is a key advanced JavaScript pattern. It allows us to build a lookup table to find the revoke function for any given proxy, without preventing the proxy from being garbage collected if it's no longer in use.


Conclusion

Today we've added a crucial tool to our metaprogramming arsenal. By moving from permanent proxies to revocable ones, we've gained fine-grained control over the entire lifecycle of object access.

Key Takeaways:

  • Proxy.revocable(target, handler) is a static factory method that creates a proxy that can be disabled.
  • It returns an object { proxy, revoke }, separating the capability from the control mechanism.
  • Calling revoke() permanently disables the proxy. Any subsequent operation will throw a TypeError.
  • This pattern is essential for implementing secure, temporary access control and for managing the lifecycle of resources.

Next Up

In our next lesson, we will dive deep into the WeakMap solution we just previewed. You will learn to use a WeakMap in a proxy handler to store private metadata without causing memory leaks. This will enable you to build even more sophisticated and memory-efficient proxies that can associate hidden state with target objects.