mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Derive private iframe.diy subdomains with HMAC-SHA256
The project ID used for the preview iframe subdomain is AI-generated
from user input. Using it directly as the iframe.diy subdomain lets
a crafted project name produce a subdomain that collides with another
project's origin, gaining access to its localStorage/IndexedDB.
Introduce a persistent random seed in localStorage (shakespeare:seed)
and derive the subdomain as base36(HMAC-SHA256(seed, prefix|identifier)).
The prefix ("preview") domain-separates different use-cases.
The subdomain is stable per device+project but unpredictable to
third parties.
This commit is contained in:
2 files changed
+78
-23
No files matched your search
@@ -1,5 +1,5 @@
|
||||
import { encodeBase64 } from '@std/encoding/base64';
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useState, useEffect, useCallback, useRef, useMemo } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
@@ -25,6 +25,7 @@ import { Terminal as TerminalComponent } from '@/components/Terminal';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { isMediaFile } from '@/lib/fileUtils';
|
||||
import { deriveIframeSubdomain } from '@/lib/iframeSubdomain';
|
||||
import { getPreviewInjectedScript } from '@/lib/previewInjectedScript';
|
||||
|
||||
interface PreviewPaneProps {
|
||||
@@ -68,6 +69,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
const { t } = useTranslation();
|
||||
const { config } = useAppContext();
|
||||
const { previewDomain } = config;
|
||||
|
||||
// Derive a private, stable subdomain from a device-local seed + the project ID.
|
||||
// This prevents malicious project names from colliding with another project's
|
||||
// origin on iframe.diy, protecting localStorage/IndexedDB isolation.
|
||||
const previewSubdomain = useMemo(() => deriveIframeSubdomain('preview', projectId), [projectId]);
|
||||
const previewOrigin = useMemo(() => `https://${previewSubdomain}.${previewDomain}`, [previewSubdomain, previewDomain]);
|
||||
|
||||
const [selectedFile, setSelectedFile] = useState<string | null>(null);
|
||||
const [fileContent, setFileContent] = useState<string>('');
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
@@ -183,18 +191,15 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
|
||||
const sendResponse = useCallback((message: JSONRPCResponse) => {
|
||||
if (iframeRef.current?.contentWindow) {
|
||||
|
||||
const targetOrigin = `https://${projectId}.${previewDomain}`;
|
||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
||||
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
|
||||
}
|
||||
}, [projectId, previewDomain]);
|
||||
}, [previewOrigin]);
|
||||
|
||||
const sendError = useCallback((message: JSONRPCResponse) => {
|
||||
if (iframeRef.current?.contentWindow) {
|
||||
const targetOrigin = `https://${projectId}.${previewDomain}`;
|
||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
||||
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
|
||||
}
|
||||
}, [projectId, previewDomain]);
|
||||
}, [previewOrigin]);
|
||||
|
||||
const handleConsoleMessage = useCallback((message: {
|
||||
jsonrpc: '2.0';
|
||||
@@ -256,10 +261,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
method,
|
||||
params: params || {},
|
||||
};
|
||||
const targetOrigin = `https://${projectId}.${previewDomain}`;
|
||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
||||
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
|
||||
}
|
||||
}, [projectId, previewDomain]);
|
||||
}, [previewOrigin]);
|
||||
|
||||
const sendNavigationCommand = useCallback((method: string, params?: Record<string, unknown>) => {
|
||||
if (iframeRef.current?.contentWindow) {
|
||||
@@ -269,10 +273,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
params: params || {},
|
||||
id: Date.now()
|
||||
};
|
||||
const targetOrigin = `https://${projectId}.${previewDomain}`;
|
||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
||||
iframeRef.current.contentWindow.postMessage(message, previewOrigin);
|
||||
}
|
||||
}, [projectId, previewDomain]);
|
||||
}, [previewOrigin]);
|
||||
|
||||
const navigateIframe = useCallback((url: string) => {
|
||||
// Send semantic path directly (e.g., "/about", "/contact")
|
||||
@@ -307,16 +310,15 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
try {
|
||||
// Parse the URL and validate origin
|
||||
const url = new URL(fetchRequest.url);
|
||||
const expectedOrigin = `https://${projectId}.${previewDomain}`;
|
||||
|
||||
if (url.origin !== expectedOrigin) {
|
||||
console.log(`Invalid origin: ${url.origin}, expected: ${expectedOrigin}`);
|
||||
if (url.origin !== previewOrigin) {
|
||||
console.log(`Invalid origin: ${url.origin}, expected: ${previewOrigin}`);
|
||||
sendError({
|
||||
jsonrpc: '2.0',
|
||||
error: {
|
||||
code: -32003,
|
||||
message: 'Invalid URL - origin mismatch',
|
||||
data: { url: fetchRequest.url, expectedOrigin }
|
||||
data: { url: fetchRequest.url, expectedOrigin: previewOrigin }
|
||||
},
|
||||
id
|
||||
});
|
||||
@@ -446,14 +448,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
id
|
||||
});
|
||||
}
|
||||
}, [projectId, projectsManager, sendResponse, sendError, previewDomain, injectScript]);
|
||||
}, [projectId, projectsManager, sendResponse, sendError, previewOrigin, injectScript]);
|
||||
|
||||
// Setup messaging protocol for iframe communication
|
||||
useEffect(() => {
|
||||
const handleMessage = (event: MessageEvent) => {
|
||||
// Verify origin for security
|
||||
const expectedOrigin = `https://${projectId}.${previewDomain}`;
|
||||
if (event.origin !== expectedOrigin) {
|
||||
if (event.origin !== previewOrigin) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -477,7 +478,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
|
||||
window.addEventListener('message', handleMessage);
|
||||
return () => window.removeEventListener('message', handleMessage);
|
||||
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, sendNotification, projectId, previewDomain]);
|
||||
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, sendNotification, previewOrigin]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedFile) {
|
||||
@@ -710,7 +711,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, isPreviewable
|
||||
<iframe
|
||||
key={projectId}
|
||||
ref={iframeRef}
|
||||
src={`https://${projectId}.${previewDomain}/`}
|
||||
src={`${previewOrigin}/`}
|
||||
className="w-full h-full border-0"
|
||||
title="Project Preview"
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { hmac } from '@noble/hashes/hmac';
|
||||
import { sha256 } from '@noble/hashes/sha256';
|
||||
import { bytesToHex } from '@noble/hashes/utils';
|
||||
|
||||
const SEED_STORAGE_KEY = 'shakespeare:seed';
|
||||
|
||||
/**
|
||||
* Encode a hex string as a zero-padded 50-character base36 string.
|
||||
* Replicates the encoding used for nsite subdomains.
|
||||
*/
|
||||
function hexToBase36(hex: string): string {
|
||||
let n = 0n;
|
||||
for (let i = 0; i < hex.length; i++) {
|
||||
n = n * 16n + BigInt(parseInt(hex[i], 16));
|
||||
}
|
||||
return n.toString(36).padStart(50, '0');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get or create a device-local random seed persisted in localStorage.
|
||||
* This is a general-purpose secret used to derive private identifiers
|
||||
* (e.g. iframe.diy subdomains) that must not be predictable by third parties.
|
||||
*/
|
||||
function getSeed(): string {
|
||||
const stored = localStorage.getItem(SEED_STORAGE_KEY);
|
||||
if (stored) return stored;
|
||||
|
||||
const seed = crypto.randomUUID();
|
||||
localStorage.setItem(SEED_STORAGE_KEY, seed);
|
||||
return seed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive a stable, private subdomain label for an iframe.diy iframe.
|
||||
*
|
||||
* Uses HMAC-SHA256 with the device-local seed as the key and
|
||||
* `prefix|identifier` as the message. Because the seed is secret to
|
||||
* this device, a third party cannot predict or collide with another
|
||||
* app's subdomain, preventing cross-app localStorage/IndexedDB access
|
||||
* on iframe.diy.
|
||||
*
|
||||
* The `prefix` acts as a domain separator so that different use-cases
|
||||
* (e.g. "preview", "sandbox") produce distinct subdomains even for the
|
||||
* same identifier.
|
||||
*
|
||||
* The result is a 50-character base36 string (256 bits of entropy) that
|
||||
* fits within the 63-character subdomain label limit.
|
||||
*/
|
||||
export function deriveIframeSubdomain(prefix: string, identifier: string): string {
|
||||
const seed = getSeed();
|
||||
const enc = new TextEncoder();
|
||||
const mac = hmac(sha256, enc.encode(seed), enc.encode(`${prefix}|${identifier}`));
|
||||
return hexToBase36(bytesToHex(mac));
|
||||
}
|
||||
Reference in new issue
Block a user