Compare commits

...
2 Commits
4 changed files with 374 additions and 16 deletions

No files matched your search

@@ -38,7 +38,14 @@ class JSONRPCClient {
}
}
async fetch(request) {
/**
* Generic JSON-RPC call method
* @param {string} method - The RPC method name
* @param {object} params - Parameters for the method
* @param {number} timeout - Timeout in milliseconds (default: 10000)
* @returns {Promise} - Resolves with the result or rejects with error
*/
async call(method, params, timeout = 10000) {
const id = ++this.requestId;
return new Promise((resolve, reject) => {
@@ -47,21 +54,25 @@ class JSONRPCClient {
// Send JSON-RPC request to parent
window.parent.postMessage({
jsonrpc: "2.0",
method: "fetch",
params: { request },
method,
params,
id,
}, "*");
// Timeout after 10 seconds
// Timeout handling
setTimeout(() => {
if (this.pendingRequests.has(id)) {
this.pendingRequests.delete(id);
reject(new Error(`Timeout fetching: ${request.url}`));
reject(new Error(`RPC call to ${method} with ID ${id} timed out`));
}
}, 10000);
}, timeout);
});
}
async fetch(request) {
return this.call("fetch", { request }, 10000);
}
handleResponse(message) {
const { id, result, error } = message;
const pending = this.pendingRequests.get(id);
@@ -153,6 +164,38 @@ class ConsoleInterceptor {
}
}
// Nostr Bridge - proxies window.nostr calls to parent window
class NostrBridge {
constructor(rpcClient) {
this.rpcClient = rpcClient;
console.log('[NostrBridge] initializing...');
this.injectNostr();
}
injectNostr() {
// Create the window.nostr object
window.nostr = {
getPublicKey: () => this.callNostrMethod('getPublicKey', []),
signEvent: (event) => this.callNostrMethod('signEvent', [event]),
nip04: {
encrypt: (pubkey, plaintext) => this.callNostrMethod('nip04.encrypt', [pubkey, plaintext]),
decrypt: (pubkey, ciphertext) => this.callNostrMethod('nip04.decrypt', [pubkey, ciphertext]),
},
nip44: {
encrypt: (pubkey, plaintext) => this.callNostrMethod('nip44.encrypt', [pubkey, plaintext]),
decrypt: (pubkey, ciphertext) => this.callNostrMethod('nip44.decrypt', [pubkey, ciphertext]),
},
};
console.log('[NostrBridge] window.nostr injected');
}
async callNostrMethod(method, args) {
// Use the generic RPC client call method
// Extension prompts may take time, so use 30 second timeout
return this.rpcClient.call('nostr', { method, args }, 30000);
}
}
// Navigation Handler - manages iframe navigation and history
class NavigationHandler {
constructor() {
@@ -319,8 +362,8 @@ class NavigationHandler {
// Main Fetch Client
class FetchClient {
constructor() {
this.rpcClient = new JSONRPCClient();
constructor(rpcClient) {
this.rpcClient = rpcClient;
this.consoleInterceptor = new ConsoleInterceptor();
this.navigationHandler = new NavigationHandler();
this.init();
@@ -393,8 +436,8 @@ class FetchClient {
active: navigator.serviceWorker.controller,
installing: null,
waiting: null,
addEventListener: () => {},
removeEventListener: () => {},
addEventListener: () => { },
removeEventListener: () => { },
});
};
}
@@ -569,8 +612,14 @@ const setupGlobalErrorHandlers = () => {
// Initialize
setupGlobalErrorHandlers();
const init = () => {
const rpcClient = new JSONRPCClient();
new FetchClient(rpcClient);
new NostrBridge(rpcClient);
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", () => new FetchClient());
document.addEventListener("DOMContentLoaded", init);
} else {
new FetchClient();
}
init();
}
+67
View File
@@ -0,0 +1,67 @@
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {
Alert,
AlertDescription,
AlertTitle,
} from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
interface NostrPermissionDialogProps {
open: boolean;
onResponse: (granted: boolean) => void;
}
export function NostrPermissionDialog({ open, onResponse }: NostrPermissionDialogProps) {
return (
<Dialog open={open} onOpenChange={(isOpen) => {
if (!isOpen) {
onResponse(false);
}
}}>
<DialogContent>
<DialogHeader>
<DialogTitle>Allow Nostr Access?</DialogTitle>
<DialogDescription className="space-y-3">
<p>
This project is requesting access to your Nostr signer (window.nostr).
</p>
<Alert variant="destructive">
<AlertTitle>Warning</AlertTitle>
<AlertDescription>
Granting access will allow this app to take actions on your behalf, including:
<ul className="list-disc list-inside mt-2 space-y-1">
<li>Read your public key</li>
<li>Sign events (publish posts, reactions, etc.)</li>
<li>Encrypt and decrypt messages</li>
</ul>
</AlertDescription>
</Alert>
<p className="text-sm text-muted-foreground">
Only grant access if you trust this application.
</p>
</DialogDescription>
</DialogHeader>
<DialogFooter className="gap-2">
<Button
variant="outline"
onClick={() => onResponse(false)}
>
Deny
</Button>
<Button
onClick={() => onResponse(true)}
>
Allow
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -0,0 +1,65 @@
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
interface NostrSignerRequiredDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
export function NostrSignerRequiredDialog({ open, onOpenChange }: NostrSignerRequiredDialogProps) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>Nostr Signer Required</DialogTitle>
<DialogDescription className="space-y-3">
<p>
This page tried to use a NIP-07 signer, but you don't have one installed!
</p>
<p>
Please install a Nostr signer extension to continue:
</p>
<div className="space-y-2 mt-4">
<a
href="https://github.com/soapbox-pub/soapbox-signer"
target="_blank"
rel="noopener noreferrer"
className="block text-primary hover:underline"
>
• Soapbox Signer
</a>
<a
href="https://getalby.com/"
target="_blank"
rel="noopener noreferrer"
className="block text-primary hover:underline"
>
• Alby
</a>
<a
href="https://github.com/fiatjaf/nos2x"
target="_blank"
rel="noopener noreferrer"
className="block text-primary hover:underline"
>
• nos2x
</a>
</div>
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
Close
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
+180 -3
View File
@@ -7,6 +7,7 @@ import { useFSPaths } from '@/hooks/useFSPaths';
import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/consoleMessages';
import { useConsoleError } from '@/hooks/useConsoleError';
import { useBuildProject } from '@/hooks/useBuildProject';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
@@ -25,6 +26,8 @@ import {
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover';
import { NostrPermissionDialog } from '@/components/NostrPermissionDialog';
import { NostrSignerRequiredDialog } from '@/components/NostrSignerRequiredDialog';
import { cn } from '@/lib/utils';
import { FileTree } from './FileTree';
import { FileEditor } from './FileEditor';
@@ -57,6 +60,16 @@ interface JSONRPCRequest {
id: number;
}
interface NostrRPCRequest {
jsonrpc: '2.0';
method: 'nostr';
params: {
method: string;
args: unknown[];
};
id: number;
}
interface JSONRPCResponse {
jsonrpc: '2.0';
result?: {
@@ -93,6 +106,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
const { fs } = useFS();
const { projectsPath } = useFSPaths();
const projectsManager = useProjectsManager();
const { user } = useCurrentUser();
// Use console error state from provider
const { hasErrors: hasConsoleErrors, clearErrors } = useConsoleError();
@@ -319,6 +333,155 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
}
}, [historyIndex, navigationHistory, sendNavigationCommand]);
// Track which projects have been granted Nostr access
const [nostrPermissions, setNostrPermissions] = useState<Set<string>>(new Set());
const [nostrPermissionDialog, setNostrPermissionDialog] = useState<{
open: boolean;
projectId: string;
resolve: (granted: boolean) => void;
} | null>(null);
const [noSignerDialog, setNoSignerDialog] = useState(false);
const requestNostrPermission = useCallback(async (projectId: string): Promise<boolean> => {
// Check if permission already granted
if (nostrPermissions.has(projectId)) {
return true;
}
// Show permission dialog and wait for user response
return new Promise<boolean>((resolve) => {
setNostrPermissionDialog({
open: true,
projectId,
resolve,
});
});
}, [nostrPermissions]);
const handleNostrPermissionResponse = useCallback((granted: boolean) => {
if (nostrPermissionDialog) {
const { projectId, resolve } = nostrPermissionDialog;
if (granted) {
// Grant permission for this project
setNostrPermissions(prev => new Set([...prev, projectId]));
}
// Close dialog and resolve the promise
setNostrPermissionDialog(null);
resolve(granted);
}
}, [nostrPermissionDialog]);
const handleNostr = useCallback(async (request: NostrRPCRequest) => {
const { params, id } = request;
const { method, args } = params;
console.log('[NOSTR BRIDGE] Handling request:', method, args);
try {
// Check if user is logged in with a signer
if (!user?.signer) {
// Show the "no signer" dialog
setNoSignerDialog(true);
throw new Error('NO_SIGNER_INSTALLED');
}
// Request permission if this is the first Nostr access from this project
const hasPermission = await requestNostrPermission(projectId);
if (!hasPermission) {
throw new Error('User denied Nostr access');
}
let result: unknown;
// Route to appropriate signer method
switch (method) {
case 'getPublicKey':
result = await user.signer.getPublicKey();
break;
case 'signEvent':
if (!args[0] || typeof args[0] !== 'object') {
throw new Error('Invalid event object');
}
result = await user.signer.signEvent(args[0] as Parameters<typeof user.signer.signEvent>[0]);
break;
case 'nip04.encrypt':
if (!user.signer.nip04?.encrypt) {
throw new Error('NIP-04 encryption not supported by signer');
}
if (typeof args[0] !== 'string' || typeof args[1] !== 'string') {
throw new Error('Invalid arguments for nip04.encrypt');
}
result = await user.signer.nip04.encrypt(args[0], args[1]);
break;
case 'nip04.decrypt':
if (!user.signer.nip04?.decrypt) {
throw new Error('NIP-04 decryption not supported by signer');
}
if (typeof args[0] !== 'string' || typeof args[1] !== 'string') {
throw new Error('Invalid arguments for nip04.decrypt');
}
result = await user.signer.nip04.decrypt(args[0], args[1]);
break;
case 'nip44.encrypt':
if (!user.signer.nip44?.encrypt) {
throw new Error('NIP-44 encryption not supported by signer');
}
if (typeof args[0] !== 'string' || typeof args[1] !== 'string') {
throw new Error('Invalid arguments for nip44.encrypt');
}
result = await user.signer.nip44.encrypt(args[0], args[1]);
break;
case 'nip44.decrypt':
if (!user.signer.nip44?.decrypt) {
throw new Error('NIP-44 decryption not supported by signer');
}
if (typeof args[0] !== 'string' || typeof args[1] !== 'string') {
throw new Error('Invalid arguments for nip44.decrypt');
}
result = await user.signer.nip44.decrypt(args[0], args[1]);
break;
default:
throw new Error(`Unsupported Nostr method: ${method}`);
}
console.log('[NOSTR BRIDGE] Success:', method, result);
// Send success response
if (iframeRef.current?.contentWindow) {
const targetOrigin = `https://${projectId}.${previewDomain}`;
iframeRef.current.contentWindow.postMessage({
jsonrpc: '2.0',
result,
id
}, targetOrigin);
}
} catch (error) {
console.error('[NOSTR BRIDGE] Error:', method, error);
// Send error response
if (iframeRef.current?.contentWindow) {
const targetOrigin = `https://${projectId}.${previewDomain}`;
iframeRef.current.contentWindow.postMessage({
jsonrpc: '2.0',
error: {
code: -32000,
message: error instanceof Error ? error.message : String(error),
},
id
}, targetOrigin);
}
}
}, [user, projectId, previewDomain, requestNostrPermission]);
const handleFetch = useCallback(async (request: JSONRPCRequest) => {
const { params, id } = request;
const { request: fetchRequest } = params;
@@ -441,7 +604,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
// Verify origin for security
const expectedOrigin = `https://${projectId}.${previewDomain}`;
if (event.origin !== expectedOrigin) {
console.log(`Ignoring message from unexpected origin: ${event.origin}, expected: ${expectedOrigin}`);
console.log(`Ignoring message with source ${event.data.source} from unexpected origin: ${event.origin}, expected: ${expectedOrigin}`);
return;
}
@@ -449,6 +612,8 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
console.log('Received message from iframe:', message);
if (message.jsonrpc === '2.0' && message.method === 'fetch') {
handleFetch(message);
} else if (message.jsonrpc === '2.0' && message.method === 'nostr') {
handleNostr(message);
} else if (message.jsonrpc === '2.0' && message.method === 'console') {
handleConsoleMessage(message);
} else if (message.jsonrpc === '2.0' && message.method === 'updateNavigationState') {
@@ -458,7 +623,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
window.addEventListener('message', handleMessage);
return () => window.removeEventListener('message', handleMessage);
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, projectId, previewDomain]);
}, [handleFetch, handleNostr, handleConsoleMessage, handleUpdateNavigationState, projectId, previewDomain]);
useEffect(() => {
if (selectedFile) {
@@ -948,6 +1113,18 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
onOpenChange={setDeployDialogOpen}
/>
)}
{/* Nostr Permission Dialog */}
<NostrPermissionDialog
open={nostrPermissionDialog?.open ?? false}
onResponse={handleNostrPermissionResponse}
/>
{/* No Signer Installed Dialog */}
<NostrSignerRequiredDialog
open={noSignerDialog}
onOpenChange={setNoSignerDialog}
/>
</div>
);
}
}