Compare commits

..
Author SHA1 Message Date
Chad Curtis 272e07795e Soften tool output eviction: keep prefix and require 2+ assistant turns
- Preserve the first 1 KiB of truncated tool output instead of replacing
  with a zero-information placeholder, so the model retains partial context
  and can decide whether to re-fetch.
- Only evict tool outputs that are at least 2 assistant turns old, not
  everything before the most recent assistant message. This prevents
  truncating outputs the model may still need on the immediately following
  turn in multi-step agentic workflows.
2026-04-10 19:44:19 -05:00
Chad Curtis ebd6fc9a10 Evict large tool outputs from old messages before sending to API
Add evictSeenToolOutputs following the same pattern as evictSeenImages. Tool
results larger than 1 KiB that the model has already seen and responded to are
replaced with a short placeholder at send time. This prevents multi-MB tool
output history from being re-sent on every subsequent turn in long agentic
sessions.
2026-04-10 19:29:28 -05:00
Alex Gleason c285dbcd05 Merge branch 'fix/app-window-not-showing-on-mobile' into 'main'
fix: render AppDialog on mobile project view

See merge request soapbox-pub/shakespeare!108
2026-04-06 14:43:27 +00:00
Dmitriy E b80205a942 fix: render AppDialog on mobile project view 2026-04-06 15:13:12 +03:00
Alex Gleason 50f85f232d release: v9.11.2 2026-04-06 00:58:48 -05:00
Alex Gleason c5605c9be8 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.
2026-04-06 00:46:01 -05:00
8 changed files with 159 additions and 26 deletions

No files matched your search

+5
View File
@@ -1,5 +1,10 @@
# Changelog
## [9.11.2] - 2026-04-06
### Fixed
- Derive private preview subdomains with HMAC to prevent cross-project origin collisions on iframe.diy
## [9.11.1] - 2026-04-05
### Changed
+27 -2
View File
@@ -1,12 +1,12 @@
{
"name": "shakespeare.diy",
"version": "9.11.0",
"version": "9.11.2",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "shakespeare.diy",
"version": "9.11.0",
"version": "9.11.2",
"license": "AGPL-3.0-or-later",
"dependencies": {
"@capacitor/app": "^8.1.0",
@@ -5001,6 +5001,7 @@
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5014,6 +5015,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5027,6 +5029,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5040,6 +5043,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5053,6 +5057,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5066,6 +5071,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5079,6 +5085,7 @@
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5092,6 +5099,7 @@
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5105,6 +5113,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5118,6 +5127,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5131,6 +5141,7 @@
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5144,6 +5155,7 @@
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5157,6 +5169,7 @@
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5170,6 +5183,7 @@
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5183,6 +5197,7 @@
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5196,6 +5211,7 @@
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5209,6 +5225,7 @@
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5222,6 +5239,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5235,6 +5253,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5248,6 +5267,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5261,6 +5281,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5274,6 +5295,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5287,6 +5309,7 @@
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5300,6 +5323,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5313,6 +5337,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
+1 -1
View File
@@ -3,7 +3,7 @@
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment",
"homepage": "https://shakespeare.diy",
"license": "AGPL-3.0-or-later",
"version": "9.11.1",
"version": "9.11.2",
"type": "module",
"author": {
"name": "shakespeare.diy",
+5
View File
@@ -1,5 +1,10 @@
# Changelog
## [9.11.2] - 2026-04-06
### Fixed
- Derive private preview subdomains with HMAC to prevent cross-project origin collisions on iframe.diy
## [9.11.1] - 2026-04-05
### Changed
+24 -23
View File
@@ -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"
/>
+38
View File
@@ -396,6 +396,41 @@ export class SessionManager {
});
};
// Replace large tool result content with a truncated prefix for messages the
// model has already seen and responded to at least twice. Like evictSeenImages,
// this is a send-time transformation only — session.messages stays intact for
// the UI. We keep the first TOOL_OUTPUT_EVICTION_THRESHOLD bytes so the model
// retains partial context and can decide whether to re-fetch the full output.
const TOOL_OUTPUT_EVICTION_THRESHOLD = 1024; // 1 KiB
const TOOL_OUTPUT_MIN_ASSISTANT_TURNS = 2; // Only evict after 2+ assistant responses
const evictSeenToolOutputs = (msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[]): OpenAI.Chat.Completions.ChatCompletionMessageParam[] => {
// Collect indices of all assistant messages.
const assistantIndices: number[] = [];
for (let i = 0; i < msgs.length; i++) {
if (msgs[i].role === 'assistant') {
assistantIndices.push(i);
}
}
// Need at least TOOL_OUTPUT_MIN_ASSISTANT_TURNS + 1 assistant messages:
// the ones that have "seen" the tool output, plus the current pending turn.
if (assistantIndices.length < TOOL_OUTPUT_MIN_ASSISTANT_TURNS + 1) return msgs;
// The eviction cutoff is the assistant message N turns back from the end.
// Tool results before this index have been processed by at least N assistant
// turns, so truncating them is safe.
const cutoffIdx = assistantIndices[assistantIndices.length - TOOL_OUTPUT_MIN_ASSISTANT_TURNS];
return msgs.map((msg, idx) => {
if (idx >= cutoffIdx) return msg;
if (msg.role !== 'tool') return msg;
if (typeof msg.content !== 'string') return msg;
if (msg.content.length <= TOOL_OUTPUT_EVICTION_THRESHOLD) return msg;
return { ...msg, content: msg.content.slice(0, TOOL_OUTPUT_EVICTION_THRESHOLD) + '\n\n[… truncated]' };
});
};
// Prepare messages for AI
// Note: User messages with image_url content parts are valid ChatCompletionMessageParam types
// The AIMessage type includes ChatCompletionMessageParam, so this cast is safe
@@ -403,6 +438,9 @@ export class SessionManager {
? [{ role: 'system', content: systemPrompt }, ...session.messages]
: session.messages) as OpenAI.Chat.Completions.ChatCompletionMessageParam[];
// Evict large tool outputs the model has already processed.
messages = evictSeenToolOutputs(messages);
// Evict images the model has already seen (all except the last user message).
// This is a send-time transformation only — session.messages stays intact for the UI.
messages = evictSeenImages(messages);
+54
View File
@@ -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));
}
+5
View File
@@ -389,6 +389,11 @@ export function ProjectView() {
open={deleteDialogOpen}
onOpenChange={setDeleteDialogOpen}
/>
<AppDialog
projectId={project.id}
open={appDialogOpen}
onOpenChange={setAppDialogOpen}
/>
</>
)}
</div>