Open in a new tab

The production page shape: sanity's base tier is applied before any application code, the page reports what was hardened, and it probes the blocked globals without crashing.

Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.

When to use it

Every production page. The base tier freezes the prototypes and blocks the classic injection sinks (eval, Function, document.write, …) so a script that slips in has far less to work with; the rest of the app is unchanged. The other examples leave it out only to stay small.

Copy-paste steps

  1. npm install @awacloud/fw
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ (node serve.js from the examples root does this; any static server works).
  3. Copy index.html, main.js and harden.js next to each other and open index.html through that server. The ../../_style/examples.css link is optional: copy that file along, or delete the link.
  4. Keep import './harden.js' (or import { report } from './harden.js') as the FIRST line of your entry module. Imports run before the module's own body, so an applyBase() call in the entry module itself would come after fw and every other import. The .js specifier harden.js uses resolves under an import map, a bundler and Node alike.

What it shows

  • harden.js, a two-line first module: import { applyBase } from '@awacloud/fw/sanity/base.js' (importing is inert), then applyBase(), which hardens and returns { applied, steps }, or { applied: false, reason } outside a browser realm or on a second call. Because it is the first import, it runs before fw is evaluated.
  • A probe table: in a hardened browser realm, window.eval becomes a locked getter whose stub throws not allowed when called. The probe reads the descriptor and calls only that stub, never the real API (a real alert or document.write must not run), and shows the result as text.
  • The app code after it (dom.query, dom.text, a click counter) is ordinary fw.
  • In a browser all five probes read blocked: not allowed.

Code

main.js

javascriptApache-2.068 lines

// SPDX-License-Identifier: Apache-2.0
// The production page shape: `./harden.js` is imported FIRST. Imports run
// before this module's body, so calling `applyBase()` down here would come
// after fw itself; a first module of its own hardens before everything.
import { report } from './harden.js';
import fw from '@awacloud/fw';
import { dom } from '@awacloud/fw/dom/query/dom.js';

export { report };

fw.runtime.registerAllDeep([dom]);
const $ = fw.runtime.resolve('dom');

/** Globals the base tier blocks: each becomes a locked getter returning a stub that throws. */
export const PROBES = [
    ['window', 'eval'], ['window', 'Function'], ['window', 'alert'],
    ['document', 'write'], ['Element.prototype', 'setHTML'],
];

/**
 * Tell whether `name` on `target` is blocked, without ever calling the real
 * API (a real `alert` or `document.write` must not run): only the stub
 * behind a locked (non-configurable) getter is called.
 * @param {object} target
 * @param {string} name
 * @returns {string} `reachable`, or `blocked: <reason>`
 */
export function probe(target, name) {
    const descriptor = Object.getOwnPropertyDescriptor(target, name);
    if (!descriptor?.get || descriptor.configurable) return 'reachable';
    try {
        const stub = descriptor.get.call(target);
        if (typeof stub === 'function') stub();
        return 'reachable';
    } catch (err) {
        return `blocked: ${/** @type {Error} */ (err).message}`;
    }
}

/** @param {string} label */
const targetOf = (label) => (label === 'window' ? window : label === 'document' ? document : Element.prototype);

/**
 * @param {typeof report} r
 * @param {(label: string) => object} resolveTarget
 * @returns {string[]} the probe results, in `PROBES` order
 */
export function render(r, resolveTarget = targetOf) {
    const summary = r.applied
        ? `sanity applied: ${r.steps.length} steps (${r.steps.join(', ')})`
        : `sanity not applied: ${r.reason}`;
    $.text(/** @type {HTMLElement} */ ($.query(document.body, '#report')), summary);
    const table = /** @type {HTMLElement} */ ($.query(document.body, '#probes'));
    table.replaceChildren();
    return PROBES.map(([label, name]) => {
        const result = probe(resolveTarget(label), name);
        const tr = table.appendChild(document.createElement('tr'));
        tr.appendChild(document.createElement('td')).textContent = `${label}.${name}`;
        tr.appendChild(document.createElement('td')).textContent = result;
        return result;
    });
}

render(report);

let clicks = 0;
const button = /** @type {HTMLButtonElement} */ ($.query(document.body, '#count'));
button.addEventListener('click', () => { $.text(button, `clicked ${++clicks} times`); });

index.html

htmlApache-2.027 lines

<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>fw · Harden the realm before the app runs</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Harden the realm before the app runs</h1>
    <p id="report" aria-live="polite"></p>
    <table>
      <caption>What application code can no longer reach</caption>
      <thead><tr><th scope="col">Global</th><th scope="col">Access</th></tr></thead>
      <tbody id="probes"></tbody>
    </table>
    <p>The app still works: <button id="count" type="button">clicked 0 times</button></p>
  </main>
</body>
</html>

harden.js

javascriptApache-2.08 lines

// SPDX-License-Identifier: Apache-2.0
// The page's FIRST import. ES modules are evaluated in import order, each one
// completely, so this body hardens the realm before `@awacloud/fw` (imported
// after it) and any application module run.
import { applyBase } from '@awacloud/fw/sanity/base.js';

/** `{ applied, steps }`, or `{ applied: false, reason }` outside a browser realm. */
export const report = applyBase();