Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 10 additions & 4 deletions docs/CSP_POLICY.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ default-src 'self';
base-uri 'self';
form-action 'self';
object-src 'none';
script-src 'self' 'unsafe-inline' 'unsafe-eval' 'wasm-unsafe-eval' https://www.googletagmanager.com https://unpkg.com;
script-src 'self' 'wasm-unsafe-eval' https://www.googletagmanager.com https://unpkg.com;
style-src 'self' 'unsafe-inline';
img-src 'self' data: blob: https://www.google-analytics.com https://www.googletagmanager.com;
font-src 'self' data:;
Expand All @@ -53,10 +53,16 @@ Meta fallback policy (for static hosting without headers): same as above but wit

The policy uses strict defaults (`default-src 'self'`, `object-src 'none'`, explicit `connect-src`/`script-src`/`worker-src`) while preserving required runtime behavior.

Two allowances remain intentionally broad enough for current implementation:
One allowance remains intentionally broad:

- `'unsafe-inline'` in `script-src` / `style-src` due to inline scripts/styles in `index.html` and iframe sandbox bootstrap.
- `'unsafe-eval'` + `'wasm-unsafe-eval'` in `script-src` to support current sandbox/runtime execution stack.
- `'unsafe-inline'` in `style-src` — required for Blockly's runtime-injected inline styles (block colours, toolbox layout). Dynamically injected styles cannot be hashed, so this cannot be removed without modifying Blockly's theming internals.

`script-src` no longer requires `'unsafe-inline'` or `'unsafe-eval'`:

- The Google Analytics initialisation script was moved from an inline `<script>` block to `ga-init.js` (served from `self`), eliminating the only inline script in `index.html`.
- The `new Function(code)` syntax-check in `validateCode()` was removed; the AST-based `validateUserCodeAST()` already provides a stricter check before code reaches the sandbox.
- WASM execution (Draco, Manifold) is covered by `'wasm-unsafe-eval'`, which allows only WASM compilation rather than arbitrary JS `eval`.
- The sandbox iframe sets its own CSP (`script-src 'unsafe-inline' 'unsafe-eval'`) inside the iframe document — this is separate from the parent page's policy and governs only sandboxed user-code execution.

## CSP regression checks before merge

Expand Down
51 changes: 30 additions & 21 deletions flock.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// Flip Computing Limited - flipcomputing.com

import * as acorn from "acorn";
import ManifoldInit from "manifold-3d";
import * as walk from "acorn-walk";
import HavokPhysics from "@babylonjs/havok";
import * as BABYLON from "@babylonjs/core";
Expand Down Expand Up @@ -386,13 +387,6 @@ export const flock = {
throw new Error("Code too long (max 100KB)");
}

// Basic syntax check
try {
new Function(code); // Just check if it parses
} catch (e) {
throw new Error(`Syntax error: ${e.message}`);
}

// Optional: Warn about patterns (don't block)
const warnings = [];
if (/eval\s*\(/.test(code)) {
Expand Down Expand Up @@ -670,19 +664,24 @@ export const flock = {
sameOrigin: true,
});

// --- load SES text in parent and inject inline into iframe (CSP allows inline) ---
const sesResp = await fetch(
"vendor/ses/lockdown.umd.min.js",
);
if (!sesResp.ok)
throw new Error(
`Failed to fetch SES: ${sesResp.status}`,
);
const sesText = await sesResp.text();
const sesScript = doc.createElement("script");
sesScript.type = "text/javascript";
sesScript.text = sesText;
doc.head.appendChild(sesScript);
// Load SES lockdown via src= so the parent's script-src 'self' policy
// is satisfied — injecting inline text would require 'unsafe-inline'.
await new Promise((resolve, reject) => {
const sesScript = doc.createElement("script");
sesScript.type = "text/javascript";
sesScript.onload = resolve;
sesScript.onerror = () =>
reject(
new Error(
"Failed to load SES lockdown",
),
);
sesScript.src = new URL(
"vendor/ses/lockdown.umd.min.js",
document.baseURI,
).href;
doc.head.appendChild(sesScript);
});
Comment on lines +667 to +684
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify iframe CSP and SES external loading code paths
rg -n -C2 "const csp =|script-src|sesScript\\.src|lockdown\\.umd\\.min\\.js" flock.js

Repository: flipcomputing/flock

Length of output: 1005


🏁 Script executed:

#!/bin/bash
# Check CSP application context and SES script location
echo "=== Checking CSP context (around line 1176) ==="
sed -n '1170,1185p' flock.js

echo -e "\n=== Checking if vendor/ses/lockdown.umd.min.js exists ==="
find . -name "lockdown.umd.min.js" 2>/dev/null || echo "File not found in current search"

echo -e "\n=== Checking SES loading code context (around line 666) ==="
sed -n '660,690p' flock.js

Repository: flipcomputing/flock

Length of output: 2720


🏁 Script executed:

#!/bin/bash
# Check vendor directory and SES files
echo "=== Checking for vendor directory ==="
ls -la vendor/ 2>/dev/null || echo "vendor/ directory does not exist"

echo -e "\n=== Searching for any SES-related files ==="
find . -iname "*ses*" -o -iname "*lockdown*" 2>/dev/null | head -20

echo -e "\n=== Checking package.json for SES dependency ==="
grep -i "ses" package.json 2>/dev/null || echo "No SES mention in package.json"

echo -e "\n=== Checking if this code path is executed/tested ==="
rg -n "replaceSandboxIframe\|lockdown\(\)" flock.js | head -10

Repository: flipcomputing/flock

Length of output: 316


🏁 Script executed:

#!/bin/bash
# Check where replaceSandboxIframe is defined and called
echo "=== Finding replaceSandboxIframe definition ==="
rg -n "replaceSandboxIframe\s*[=:(]" flock.js | head -5

echo -e "\n=== Checking SES npm package installation ==="
ls -la node_modules/ses 2>/dev/null | head -5 || echo "SES not in node_modules"

echo -e "\n=== Checking actual SES file locations ==="
find node_modules/ses -name "lockdown*" 2>/dev/null | head -10

echo -e "\n=== Checking if vendor is built/created elsewhere ==="
rg -n "vendor.*ses\|lockdown.*umd" --type js | head -10

Repository: flipcomputing/flock

Length of output: 382


CSP blocks the SES script load — add 'self' to script-src.

The iframe CSP at line 1176 is script-src 'unsafe-inline' 'unsafe-eval', which blocks external scripts. Line 666-683 loads SES via sesScript.src, requiring the 'self' directive to allow same-origin external scripts. The promise will reject with a CSP violation.

Add 'self' to the script-src policy:

Minimal fix
-const csp = `default-src 'none'; style-src 'unsafe-inline'; script-src 'unsafe-inline' 'unsafe-eval'`;
+const csp = `default-src 'none'; style-src 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'`;

Note: Verify the SES file path vendor/ses/lockdown.umd.min.js exists in your build output, as the vendor directory is not in the source repo. The SES package is listed as a dependency ("ses": "^1.14.0").

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@flock.js` around lines 666 - 683, The iframe Content-Security-Policy used
when creating the iframe must include 'self' in its script-src so the
externally-loaded SES script (sesScript.src -> "vendor/ses/lockdown.umd.min.js"
resolved via document.baseURI) is allowed; update the CSP string/attribute that
sets script-src (where you currently have "script-src 'unsafe-inline'
'unsafe-eval'") to include 'self' (e.g., "script-src 'self' 'unsafe-inline'
'unsafe-eval'"), and verify the vendor/ses/lockdown.umd.min.js file is present
in the build output so the dynamic load via doc.createElement("script")
succeeds.


// lockdown the iframe realm
win.lockdown();
Expand Down Expand Up @@ -1258,7 +1257,17 @@ export const flock = {
flock.abortController = new AbortController();

try {
await flock.BABYLON.InitializeCSG2Async();
// Pre-initialize manifold-3d here so we can pass the instances
// directly to InitializeCSG2Async, bypassing its _LoadScriptModuleAsync
// path which injects an inline <script type="module"> — blocked by CSP.
const manifoldWasm = await ManifoldInit({
locateFile: (f) => "./wasm/" + f,
});
manifoldWasm.setup();
await flock.BABYLON.InitializeCSG2Async({
manifoldInstance: manifoldWasm.Manifold,
manifoldMeshInstance: manifoldWasm.Mesh,
});
} catch (error) {
console.error("Error initializing CSG2:", error);
}
Expand Down
7 changes: 7 additions & 0 deletions ga-init.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
window.dataLayer = window.dataLayer || [];
function gtag() { dataLayer.push(arguments); }
gtag('js', new Date());
gtag('config', 'G-QCGT3X072N', {
client_storage: 'none', // Prevents setting cookies
anonymize_ip: true // Hides IP addresses for privacy
});
Loading
Loading