A Secure Approach: The Caja Project

The Caja project has emerged as a means for securing third-party frontend code (HTML, CSS, and JavaScript) to protect both the container on which that code is hosted as well as the end user who is exposed to it.

In simple terms, Caja works by encasing the third-party code in a container, such as a div node, that provides a sanitized version of the DOM. When the third-party code then calls a DOM method, it is not accessing the true DOM of the root page. This means that the Caja sanitization system can control every DOM request that is being made and can either grant or deny access to certain functionality.

Taking that a step further, the project works by employing a two-part sanitization system. When the third-party code is first rendered on the page, it will go through the server-side cajoler, which will sanitize the code and remove anything that it deems malicious. Next, if new code is injected into the application via a JavaScript method (e.g., innerHTML), that code will be pushed through the client-side sanitizer. This client-side sanitizer is a much stricter system, usually allowing only approved HTML and CSS while removing JavaScript content.

This is the core functionality of the Caja project. We’ll explore each component in more depth as we walk through the implementation of a Caja-protected application.

Get Programming Social Applications now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.