mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-06 08:37:22 +00:00
Merge branch 'nsite-v2' into 'main'
Update nsite deployment See merge request soapbox-pub/shakespeare!104
This commit is contained in:
commit
a8c19bd0ad
11 files changed
+1110
-265
No files matched your search
Generated
+20
@@ -4677,6 +4677,7 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm"
|
"arm"
|
||||||
],
|
],
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4690,6 +4691,7 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4703,6 +4705,7 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4716,6 +4719,7 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4729,6 +4733,7 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4742,6 +4747,7 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4755,6 +4761,7 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm"
|
"arm"
|
||||||
],
|
],
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4768,6 +4775,7 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm"
|
"arm"
|
||||||
],
|
],
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4781,6 +4789,7 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4794,6 +4803,7 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4807,6 +4817,7 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"loong64"
|
"loong64"
|
||||||
],
|
],
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4820,6 +4831,7 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"ppc64"
|
"ppc64"
|
||||||
],
|
],
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4833,6 +4845,7 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"riscv64"
|
"riscv64"
|
||||||
],
|
],
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4846,6 +4859,7 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"riscv64"
|
"riscv64"
|
||||||
],
|
],
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4859,6 +4873,7 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"s390x"
|
"s390x"
|
||||||
],
|
],
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4872,6 +4887,7 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4885,6 +4901,7 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4898,6 +4915,7 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"arm64"
|
"arm64"
|
||||||
],
|
],
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4911,6 +4929,7 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"ia32"
|
"ia32"
|
||||||
],
|
],
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
@@ -4924,6 +4943,7 @@
|
|||||||
"cpu": [
|
"cpu": [
|
||||||
"x64"
|
"x64"
|
||||||
],
|
],
|
||||||
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"optional": true,
|
"optional": true,
|
||||||
"os": [
|
"os": [
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import { useTranslation } from 'react-i18next';
|
import { useTranslation } from 'react-i18next';
|
||||||
import { Check } from 'lucide-react';
|
import { Check } from 'lucide-react';
|
||||||
|
import { UrlListEditor } from '@/components/UrlListEditor';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Input } from '@/components/ui/input';
|
import { Input } from '@/components/ui/input';
|
||||||
import { PasswordInput } from '@/components/ui/password-input';
|
import { PasswordInput } from '@/components/ui/password-input';
|
||||||
@@ -63,8 +64,8 @@ export function AddCustomProviderDialog({
|
|||||||
const [customHost, setCustomHost] = useState('');
|
const [customHost, setCustomHost] = useState('');
|
||||||
const [customProxy, setCustomProxy] = useState(false);
|
const [customProxy, setCustomProxy] = useState(false);
|
||||||
const [customGateway, setCustomGateway] = useState('');
|
const [customGateway, setCustomGateway] = useState('');
|
||||||
const [customRelayUrls, setCustomRelayUrls] = useState('');
|
const [customRelayUrls, setCustomRelayUrls] = useState<string[]>([]);
|
||||||
const [customBlossomServers, setCustomBlossomServers] = useState('');
|
const [customBlossomServers, setCustomBlossomServers] = useState<string[]>([]);
|
||||||
|
|
||||||
const handleAdd = () => {
|
const handleAdd = () => {
|
||||||
if (!customProviderType || !customName.trim()) return;
|
if (!customProviderType || !customName.trim()) return;
|
||||||
@@ -84,12 +85,8 @@ export function AddCustomProviderDialog({
|
|||||||
type: 'nsite',
|
type: 'nsite',
|
||||||
name: customName.trim(),
|
name: customName.trim(),
|
||||||
gateway: customGateway.trim() || 'nsite.lol',
|
gateway: customGateway.trim() || 'nsite.lol',
|
||||||
relayUrls: customRelayUrls.trim()
|
relayUrls: customRelayUrls.length > 0 ? customRelayUrls : ['wss://relay.ditto.pub'],
|
||||||
? customRelayUrls.split(',').map(s => s.trim()).filter(Boolean)
|
blossomServers: customBlossomServers.length > 0 ? customBlossomServers : ['https://blossom.primal.net/'],
|
||||||
: ['wss://relay.ditto.pub'],
|
|
||||||
blossomServers: customBlossomServers.trim()
|
|
||||||
? customBlossomServers.split(',').map(s => s.trim()).filter(Boolean)
|
|
||||||
: ['https://blossom.primal.net/'],
|
|
||||||
};
|
};
|
||||||
} else if (customProviderType === 'netlify') {
|
} else if (customProviderType === 'netlify') {
|
||||||
if (!customApiKey.trim()) return;
|
if (!customApiKey.trim()) return;
|
||||||
@@ -157,8 +154,8 @@ export function AddCustomProviderDialog({
|
|||||||
setCustomHost('');
|
setCustomHost('');
|
||||||
setCustomProxy(false);
|
setCustomProxy(false);
|
||||||
setCustomGateway('');
|
setCustomGateway('');
|
||||||
setCustomRelayUrls('');
|
setCustomRelayUrls([]);
|
||||||
setCustomBlossomServers('');
|
setCustomBlossomServers([]);
|
||||||
|
|
||||||
onOpenChange(false);
|
onOpenChange(false);
|
||||||
};
|
};
|
||||||
@@ -198,8 +195,8 @@ export function AddCustomProviderDialog({
|
|||||||
setCustomHost('');
|
setCustomHost('');
|
||||||
setCustomProxy(false);
|
setCustomProxy(false);
|
||||||
setCustomGateway('');
|
setCustomGateway('');
|
||||||
setCustomRelayUrls('');
|
setCustomRelayUrls([]);
|
||||||
setCustomBlossomServers('');
|
setCustomBlossomServers([]);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<SelectTrigger>
|
<SelectTrigger>
|
||||||
@@ -249,7 +246,7 @@ export function AddCustomProviderDialog({
|
|||||||
) : customProviderType === 'nsite' ? (
|
) : customProviderType === 'nsite' ? (
|
||||||
<>
|
<>
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-muted-foreground">
|
||||||
Deploy to Nostr as a static website. Uses kind 34128 events and Blossom file storage.
|
Deploy to Nostr as a static website. Uses a kind 15128 site manifest event and Blossom file storage.
|
||||||
</p>
|
</p>
|
||||||
<div className="grid gap-2">
|
<div className="grid gap-2">
|
||||||
<Label htmlFor="custom-gateway">Gateway</Label>
|
<Label htmlFor="custom-gateway">Gateway</Label>
|
||||||
@@ -260,24 +257,20 @@ export function AddCustomProviderDialog({
|
|||||||
onChange={(e) => setCustomGateway(e.target.value)}
|
onChange={(e) => setCustomGateway(e.target.value)}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="grid gap-2">
|
<UrlListEditor
|
||||||
<Label htmlFor="custom-relays">Relay URLs (comma-separated)</Label>
|
label="Relay URLs"
|
||||||
<Input
|
items={customRelayUrls}
|
||||||
id="custom-relays"
|
onChange={setCustomRelayUrls}
|
||||||
placeholder="wss://relay.ditto.pub, wss://relay.damus.io"
|
protocol="wss"
|
||||||
value={customRelayUrls}
|
placeholder="relay.ditto.pub"
|
||||||
onChange={(e) => setCustomRelayUrls(e.target.value)}
|
/>
|
||||||
/>
|
<UrlListEditor
|
||||||
</div>
|
label="Blossom Servers"
|
||||||
<div className="grid gap-2">
|
items={customBlossomServers}
|
||||||
<Label htmlFor="custom-blossom">Blossom Servers (comma-separated)</Label>
|
onChange={setCustomBlossomServers}
|
||||||
<Input
|
protocol="https"
|
||||||
id="custom-blossom"
|
placeholder="blossom.primal.net"
|
||||||
placeholder="https://blossom.primal.net/"
|
/>
|
||||||
value={customBlossomServers}
|
|
||||||
onChange={(e) => setCustomBlossomServers(e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import {
|
|||||||
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
||||||
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
||||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||||
|
import { UrlListEditor } from '@/components/UrlListEditor';
|
||||||
|
|
||||||
interface ProviderConfigDialogProps {
|
interface ProviderConfigDialogProps {
|
||||||
open: boolean;
|
open: boolean;
|
||||||
@@ -138,34 +139,22 @@ export function ProviderConfigDialog({
|
|||||||
onChange={(e) => setLocalProvider({ ...localProvider, gateway: e.target.value })}
|
onChange={(e) => setLocalProvider({ ...localProvider, gateway: e.target.value })}
|
||||||
/>
|
/>
|
||||||
</div>
|
</div>
|
||||||
<div className="grid gap-2">
|
<UrlListEditor
|
||||||
<Label htmlFor="provider-relays">
|
label="Relay URLs"
|
||||||
Relay URLs (comma-separated) <span className="text-destructive">*</span>
|
items={localProvider.relayUrls ?? []}
|
||||||
</Label>
|
onChange={(urls) => setLocalProvider({ ...localProvider, relayUrls: urls })}
|
||||||
<Input
|
protocol="wss"
|
||||||
id="provider-relays"
|
placeholder="relay.ditto.pub"
|
||||||
placeholder="wss://relay.ditto.pub, wss://relay.damus.io"
|
required
|
||||||
value={localProvider.relayUrls?.join(', ') || ''}
|
/>
|
||||||
onChange={(e) => setLocalProvider({
|
<UrlListEditor
|
||||||
...localProvider,
|
label="Blossom Servers"
|
||||||
relayUrls: e.target.value.split(',').map(s => s.trim()).filter(Boolean)
|
items={localProvider.blossomServers ?? []}
|
||||||
})}
|
onChange={(servers) => setLocalProvider({ ...localProvider, blossomServers: servers })}
|
||||||
/>
|
protocol="https"
|
||||||
</div>
|
placeholder="blossom.primal.net"
|
||||||
<div className="grid gap-2">
|
required
|
||||||
<Label htmlFor="provider-blossom">
|
/>
|
||||||
Blossom Servers (comma-separated) <span className="text-destructive">*</span>
|
|
||||||
</Label>
|
|
||||||
<Input
|
|
||||||
id="provider-blossom"
|
|
||||||
placeholder="https://blossom.primal.net/"
|
|
||||||
value={localProvider.blossomServers?.join(', ') || ''}
|
|
||||||
onChange={(e) => setLocalProvider({
|
|
||||||
...localProvider,
|
|
||||||
blossomServers: e.target.value.split(',').map(s => s.trim()).filter(Boolean)
|
|
||||||
})}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
|
|||||||
@@ -0,0 +1,147 @@
|
|||||||
|
import { useState, useRef, KeyboardEvent } from 'react';
|
||||||
|
import { X, Plus } from 'lucide-react';
|
||||||
|
import { Button } from '@/components/ui/button';
|
||||||
|
import { Input } from '@/components/ui/input';
|
||||||
|
import { Label } from '@/components/ui/label';
|
||||||
|
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||||
|
import { cn } from '@/lib/utils';
|
||||||
|
|
||||||
|
interface UrlListEditorProps {
|
||||||
|
/** Label shown above the list */
|
||||||
|
label: string;
|
||||||
|
/** Current array of full URLs */
|
||||||
|
items: string[];
|
||||||
|
/** Called when the list changes */
|
||||||
|
onChange: (items: string[]) => void;
|
||||||
|
/** Controls auto-prefix on bare domain entry */
|
||||||
|
protocol: 'wss' | 'https';
|
||||||
|
/** Placeholder shown in the add input */
|
||||||
|
placeholder?: string;
|
||||||
|
/** Whether to show the required asterisk */
|
||||||
|
required?: boolean;
|
||||||
|
/** Additional CSS classes for the root element */
|
||||||
|
className?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Normalize a bare domain or partial URL to a fully-qualified URL.
|
||||||
|
* If the value already has any protocol it is returned as-is.
|
||||||
|
*/
|
||||||
|
function normalizeEntry(value: string, protocol: 'wss' | 'https'): string {
|
||||||
|
const trimmed = value.trim();
|
||||||
|
if (!trimmed) return '';
|
||||||
|
if (/^wss?:\/\//i.test(trimmed) || /^https?:\/\//i.test(trimmed)) return trimmed;
|
||||||
|
return `${protocol}://${trimmed}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert a URL to an https:// form suitable for favicon lookup.
|
||||||
|
* wss:// → https://, ws:// → http://
|
||||||
|
*/
|
||||||
|
function toHttpsUrl(url: string): string {
|
||||||
|
return url.replace(/^wss:\/\//i, 'https://').replace(/^ws:\/\//i, 'http://');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Strip the protocol prefix for compact display */
|
||||||
|
function displayLabel(url: string): string {
|
||||||
|
return url.replace(/^wss?:\/\//i, '').replace(/^https?:\/\//i, '');
|
||||||
|
}
|
||||||
|
|
||||||
|
export function UrlListEditor({
|
||||||
|
label,
|
||||||
|
items,
|
||||||
|
onChange,
|
||||||
|
protocol,
|
||||||
|
placeholder,
|
||||||
|
required,
|
||||||
|
className,
|
||||||
|
}: UrlListEditorProps) {
|
||||||
|
const [inputValue, setInputValue] = useState('');
|
||||||
|
const inputRef = useRef<HTMLInputElement>(null);
|
||||||
|
|
||||||
|
const handleAdd = () => {
|
||||||
|
const normalized = normalizeEntry(inputValue, protocol);
|
||||||
|
if (!normalized) return;
|
||||||
|
// Silently ignore duplicates
|
||||||
|
if (items.includes(normalized)) {
|
||||||
|
setInputValue('');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
onChange([...items, normalized]);
|
||||||
|
setInputValue('');
|
||||||
|
inputRef.current?.focus();
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleRemove = (index: number) => {
|
||||||
|
onChange(items.filter((_, i) => i !== index));
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault();
|
||||||
|
handleAdd();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={cn('grid gap-2', className)}>
|
||||||
|
<Label>
|
||||||
|
{label}
|
||||||
|
{required && <span className="text-destructive ml-1">*</span>}
|
||||||
|
</Label>
|
||||||
|
|
||||||
|
{/* Scrollable list of existing items */}
|
||||||
|
{items.length > 0 && (
|
||||||
|
<div className="rounded-md border overflow-y-auto max-h-48">
|
||||||
|
{items.map((item, index) => (
|
||||||
|
<div
|
||||||
|
key={index}
|
||||||
|
className="flex items-center gap-2 px-3 py-2 hover:bg-muted border-b last:border-b-0"
|
||||||
|
>
|
||||||
|
<ExternalFavicon
|
||||||
|
url={toHttpsUrl(item)}
|
||||||
|
size={14}
|
||||||
|
className="shrink-0 opacity-70"
|
||||||
|
/>
|
||||||
|
<span className="flex-1 text-sm font-mono truncate">
|
||||||
|
{displayLabel(item)}
|
||||||
|
</span>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="icon"
|
||||||
|
className="h-6 w-6 shrink-0 text-muted-foreground hover:text-destructive"
|
||||||
|
onClick={() => handleRemove(index)}
|
||||||
|
aria-label={`Remove ${item}`}
|
||||||
|
>
|
||||||
|
<X className="h-3 w-3" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Add input */}
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Input
|
||||||
|
ref={inputRef}
|
||||||
|
value={inputValue}
|
||||||
|
onChange={(e) => setInputValue(e.target.value)}
|
||||||
|
onKeyDown={handleKeyDown}
|
||||||
|
placeholder={placeholder ?? (protocol === 'wss' ? 'relay.example.com' : 'server.example.com')}
|
||||||
|
className="font-mono text-sm"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="icon"
|
||||||
|
onClick={handleAdd}
|
||||||
|
disabled={!inputValue.trim()}
|
||||||
|
aria-label={`Add ${label}`}
|
||||||
|
>
|
||||||
|
<Plus className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -36,6 +36,9 @@ import { VercelAdapter } from '@/lib/deploy/VercelAdapter';
|
|||||||
import { CloudflareAdapter } from '@/lib/deploy/CloudflareAdapter';
|
import { CloudflareAdapter } from '@/lib/deploy/CloudflareAdapter';
|
||||||
import { DenoDeployAdapter } from '@/lib/deploy/DenoDeployAdapter';
|
import { DenoDeployAdapter } from '@/lib/deploy/DenoDeployAdapter';
|
||||||
import { RailwayAdapter } from '@/lib/deploy/RailwayAdapter';
|
import { RailwayAdapter } from '@/lib/deploy/RailwayAdapter';
|
||||||
|
import { readNsiteVfsConfig, writeNsiteVfsConfig } from '@/lib/nsiteConfig';
|
||||||
|
import type { NsiteVfsConfig } from '@/lib/nsiteConfig';
|
||||||
|
import { projectNameToDTag } from '@/lib/utils/nsite';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Normalize a URL string to ensure it has a protocol
|
* Normalize a URL string to ensure it has a protocol
|
||||||
@@ -85,7 +88,10 @@ interface ShakespeareFormData {
|
|||||||
}
|
}
|
||||||
|
|
||||||
interface NsiteFormData {
|
interface NsiteFormData {
|
||||||
nsec: string;
|
siteTitle: string;
|
||||||
|
siteDescription: string;
|
||||||
|
dTag: string;
|
||||||
|
siteType: 'named' | 'root';
|
||||||
}
|
}
|
||||||
|
|
||||||
interface NetlifyFormData {
|
interface NetlifyFormData {
|
||||||
@@ -132,12 +138,49 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
|||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [isShakespeareFormValid, setIsShakespeareFormValid] = useState(true);
|
const [isShakespeareFormValid, setIsShakespeareFormValid] = useState(true);
|
||||||
|
|
||||||
|
// .nsite/config.json state — loaded once on mount, used to skip config form on re-deploy
|
||||||
|
const [nsiteVfsConfig, setNsiteVfsConfig] = useState<NsiteVfsConfig | null>(null);
|
||||||
|
const [nsiteVfsConfigLoading, setNsiteVfsConfigLoading] = useState(true);
|
||||||
|
// When a .nsite/config.json already exists, hide the full form and show a summary instead.
|
||||||
|
// The user can click "Edit" to expand it.
|
||||||
|
const [nsiteShowFullForm, setNsiteShowFullForm] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!projectId) {
|
||||||
|
setNsiteVfsConfigLoading(false);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const projectPath = `${projectsPath}/${projectId}`;
|
||||||
|
readNsiteVfsConfig(fs, projectPath)
|
||||||
|
.then((cfg) => {
|
||||||
|
setNsiteVfsConfig(cfg);
|
||||||
|
// If a config already exists, seed the form from it and stay in summary mode.
|
||||||
|
// If not, show the full form so the user can configure for the first time.
|
||||||
|
if (cfg) {
|
||||||
|
const derivedSiteType = cfg.id === null ? 'root' : 'named';
|
||||||
|
setNsiteForm({
|
||||||
|
siteTitle: cfg.title ?? '',
|
||||||
|
siteDescription: cfg.description ?? '',
|
||||||
|
dTag: (cfg.id != null && cfg.id !== '') ? cfg.id : '',
|
||||||
|
siteType: derivedSiteType,
|
||||||
|
});
|
||||||
|
setNsiteShowFullForm(false);
|
||||||
|
} else {
|
||||||
|
setNsiteShowFullForm(true);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.finally(() => setNsiteVfsConfigLoading(false));
|
||||||
|
}, [fs, projectsPath, projectId]);
|
||||||
|
|
||||||
// Provider-specific form data
|
// Provider-specific form data
|
||||||
const [shakespeareForm, setShakespeareForm] = useState<ShakespeareFormData>({
|
const [shakespeareForm, setShakespeareForm] = useState<ShakespeareFormData>({
|
||||||
subdomain: projectId,
|
subdomain: projectId,
|
||||||
});
|
});
|
||||||
const [nsiteForm, setNsiteForm] = useState<NsiteFormData>({
|
const [nsiteForm, setNsiteForm] = useState<NsiteFormData>({
|
||||||
nsec: '',
|
siteTitle: '',
|
||||||
|
siteDescription: '',
|
||||||
|
dTag: '',
|
||||||
|
siteType: 'named',
|
||||||
});
|
});
|
||||||
const [netlifyForm, setNetlifyForm] = useState<NetlifyFormData>({
|
const [netlifyForm, setNetlifyForm] = useState<NetlifyFormData>({
|
||||||
siteId: '',
|
siteId: '',
|
||||||
@@ -205,17 +248,22 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
|||||||
} else if (selectedProvider.type === 'nsite') {
|
} else if (selectedProvider.type === 'nsite') {
|
||||||
const nsiteProvider = selectedProvider;
|
const nsiteProvider = selectedProvider;
|
||||||
|
|
||||||
if (!nsiteForm.nsec) {
|
if (!user) {
|
||||||
throw new Error('Site private key (nsec) is required');
|
throw new Error('You must be logged in to deploy to nsite.');
|
||||||
}
|
}
|
||||||
|
|
||||||
adapter = new NsiteAdapter({
|
adapter = new NsiteAdapter({
|
||||||
fs,
|
fs,
|
||||||
nostr,
|
nostr,
|
||||||
nsec: nsiteForm.nsec,
|
signer: user.signer,
|
||||||
gateway: nsiteProvider.gateway,
|
gateway: nsiteProvider.gateway,
|
||||||
relayUrls: nsiteProvider.relayUrls,
|
relayUrls: nsiteProvider.relayUrls,
|
||||||
blossomServers: nsiteProvider.blossomServers,
|
blossomServers: nsiteProvider.blossomServers,
|
||||||
|
siteTitle: nsiteForm.siteTitle || undefined,
|
||||||
|
siteDescription: nsiteForm.siteDescription || undefined,
|
||||||
|
siteIdentifier: nsiteForm.siteType === 'named' && nsiteForm.dTag
|
||||||
|
? nsiteForm.dTag
|
||||||
|
: undefined,
|
||||||
});
|
});
|
||||||
} else if (selectedProvider.type === 'netlify') {
|
} else if (selectedProvider.type === 'netlify') {
|
||||||
const netlifyProvider = selectedProvider;
|
const netlifyProvider = selectedProvider;
|
||||||
@@ -324,9 +372,29 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
|||||||
type: 'nsite',
|
type: 'nsite',
|
||||||
url: result.url,
|
url: result.url,
|
||||||
data: {
|
data: {
|
||||||
nsec: nsiteForm.nsec,
|
siteTitle: nsiteForm.siteTitle || undefined,
|
||||||
|
siteDescription: nsiteForm.siteDescription || undefined,
|
||||||
|
dTag: nsiteForm.dTag || undefined,
|
||||||
|
siteType: nsiteForm.siteType,
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// Write .nsite/config.json for nsyte CLI interoperability.
|
||||||
|
// This file is safe to commit — it never contains the nsec.
|
||||||
|
const nsiteProvider = selectedProvider;
|
||||||
|
const newNsiteVfsConfig: NsiteVfsConfig = {
|
||||||
|
relays: nsiteProvider.relayUrls,
|
||||||
|
servers: nsiteProvider.blossomServers,
|
||||||
|
id: nsiteForm.siteType === 'root' ? null : (nsiteForm.dTag || undefined),
|
||||||
|
title: nsiteForm.siteTitle || undefined,
|
||||||
|
description: nsiteForm.siteDescription || undefined,
|
||||||
|
fallback: '/index.html',
|
||||||
|
gatewayHostnames: [nsiteProvider.gateway],
|
||||||
|
};
|
||||||
|
await writeNsiteVfsConfig(fs, projectPath, newNsiteVfsConfig);
|
||||||
|
// Update in-memory state so summary view reflects new values immediately
|
||||||
|
setNsiteVfsConfig(newNsiteVfsConfig);
|
||||||
|
setNsiteShowFullForm(false);
|
||||||
} else if (selectedProvider.type === 'netlify') {
|
} else if (selectedProvider.type === 'netlify') {
|
||||||
await updateProjectSettings(selectedProviderId, {
|
await updateProjectSettings(selectedProviderId, {
|
||||||
type: 'netlify',
|
type: 'netlify',
|
||||||
@@ -434,12 +502,14 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
|||||||
setError(null);
|
setError(null);
|
||||||
// Reset forms
|
// Reset forms
|
||||||
setShakespeareForm({ subdomain: projectId });
|
setShakespeareForm({ subdomain: projectId });
|
||||||
setNsiteForm({ nsec: '' });
|
setNsiteForm({ siteTitle: '', siteDescription: '', dTag: '', siteType: 'named' });
|
||||||
setNetlifyForm({ siteId: '', siteName: '' });
|
setNetlifyForm({ siteId: '', siteName: '' });
|
||||||
setVercelForm({ projectName: projectName || projectId, teamId: '' });
|
setVercelForm({ projectName: projectName || projectId, teamId: '' });
|
||||||
setCloudflareForm({ projectName: projectName || projectId });
|
setCloudflareForm({ projectName: projectName || projectId });
|
||||||
setDenoDeployForm({ projectName: projectName || projectId });
|
setDenoDeployForm({ projectName: projectName || projectId });
|
||||||
setRailwayForm({ workspaceId: '', projectId: '', environmentId: '', serviceId: '', projectName: projectName || projectId });
|
setRailwayForm({ workspaceId: '', projectId: '', environmentId: '', serviceId: '', projectName: projectName || projectId });
|
||||||
|
// Return to summary mode so next open shows the compact view (if config exists)
|
||||||
|
setNsiteShowFullForm(false);
|
||||||
onClose();
|
onClose();
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -451,8 +521,21 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
|||||||
setIsShakespeareFormValid(isValid);
|
setIsShakespeareFormValid(isValid);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const handleNsiteNsecChange = useCallback((nsec: string) => {
|
const handleNsiteSiteTitleChange = useCallback((siteTitle: string) => {
|
||||||
setNsiteForm({ nsec });
|
setNsiteForm(prev => ({ ...prev, siteTitle }));
|
||||||
|
// Derive the dTag from the title so the user never has to think about it.
|
||||||
|
// Falls back to projectName when the title is blank.
|
||||||
|
projectNameToDTag(siteTitle || projectName).then(dTag => {
|
||||||
|
setNsiteForm(prev => ({ ...prev, dTag }));
|
||||||
|
});
|
||||||
|
}, [projectName]);
|
||||||
|
|
||||||
|
const handleNsiteSiteDescriptionChange = useCallback((siteDescription: string) => {
|
||||||
|
setNsiteForm(prev => ({ ...prev, siteDescription }));
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleNsiteSiteTypeChange = useCallback((siteType: 'named' | 'root') => {
|
||||||
|
setNsiteForm(prev => ({ ...prev, siteType }));
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
const handleNetlifySiteChange = useCallback((siteId: string, siteName: string) => {
|
const handleNetlifySiteChange = useCallback((siteId: string, siteName: string) => {
|
||||||
@@ -501,15 +584,87 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (selectedProvider.type === 'nsite') {
|
if (selectedProvider.type === 'nsite') {
|
||||||
|
// While the .nsite/config.json load is still in flight, render nothing to avoid flicker
|
||||||
|
if (nsiteVfsConfigLoading) return null;
|
||||||
|
|
||||||
|
// Summary view: shown when .nsite/config.json already exists and user hasn't clicked Edit
|
||||||
|
if (nsiteVfsConfig && !nsiteShowFullForm) {
|
||||||
|
const isRoot = nsiteVfsConfig.id === null;
|
||||||
|
const siteLabel = isRoot
|
||||||
|
? 'Root site'
|
||||||
|
: nsiteVfsConfig.id
|
||||||
|
? `Named site: ${nsiteVfsConfig.id}`
|
||||||
|
: 'Named site';
|
||||||
|
const relayCount = nsiteVfsConfig.relays?.length ?? 0;
|
||||||
|
const serverCount = nsiteVfsConfig.servers?.length ?? 0;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-3">
|
||||||
|
<div className="rounded-md border bg-muted/30 p-3 space-y-2 text-sm">
|
||||||
|
{nsiteVfsConfig.title && (
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<span className="text-muted-foreground">Title</span>
|
||||||
|
<span className="font-medium">{nsiteVfsConfig.title}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<span className="text-muted-foreground">Type</span>
|
||||||
|
<span className="font-medium">{siteLabel}</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<span className="text-muted-foreground">Relays</span>
|
||||||
|
<span className="font-medium">{relayCount} configured</span>
|
||||||
|
</div>
|
||||||
|
<div className="flex justify-between">
|
||||||
|
<span className="text-muted-foreground">Blossom servers</span>
|
||||||
|
<span className="font-medium">{serverCount} configured</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="text-xs text-muted-foreground underline hover:text-foreground transition-colors"
|
||||||
|
onClick={() => setNsiteShowFullForm(true)}
|
||||||
|
>
|
||||||
|
Edit site settings
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Full config form: shown on first deploy or when user clicks "Edit site settings"
|
||||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||||
const savedNsec = savedConfig?.type === 'nsite' ? savedConfig.data.nsec : undefined;
|
const legacy = savedConfig?.type === 'nsite' ? savedConfig.data : undefined;
|
||||||
|
|
||||||
|
// .nsite/config.json wins; .git/shakespeare/deploy.json is the legacy fallback
|
||||||
|
const savedSiteTitle = nsiteVfsConfig?.title ?? legacy?.siteTitle;
|
||||||
|
const savedSiteDescription = nsiteVfsConfig?.description ?? legacy?.siteDescription;
|
||||||
|
const savedSiteType = nsiteVfsConfig
|
||||||
|
? (nsiteVfsConfig.id === null ? 'root' : 'named')
|
||||||
|
: legacy?.siteType;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<NsiteDeployForm
|
<div className="space-y-3">
|
||||||
gateway={selectedProvider.gateway}
|
<NsiteDeployForm
|
||||||
savedNsec={savedNsec}
|
key={selectedProviderId}
|
||||||
onNsecChange={handleNsiteNsecChange}
|
projectName={projectName || projectId}
|
||||||
/>
|
savedNsec={legacy?.nsec}
|
||||||
|
savedSiteTitle={savedSiteTitle}
|
||||||
|
savedSiteDescription={savedSiteDescription}
|
||||||
|
savedSiteType={savedSiteType}
|
||||||
|
onSiteTitleChange={handleNsiteSiteTitleChange}
|
||||||
|
onSiteDescriptionChange={handleNsiteSiteDescriptionChange}
|
||||||
|
onSiteTypeChange={handleNsiteSiteTypeChange}
|
||||||
|
/>
|
||||||
|
{nsiteVfsConfig && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="text-xs text-muted-foreground underline hover:text-foreground transition-colors"
|
||||||
|
onClick={() => setNsiteShowFullForm(false)}
|
||||||
|
>
|
||||||
|
Back to summary
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -769,6 +924,22 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
|||||||
</Alert>
|
</Alert>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{selectedProvider?.type === 'nsite' && !user && (
|
||||||
|
<Alert>
|
||||||
|
<AlertCircle className="h-4 w-4" />
|
||||||
|
<AlertDescription>
|
||||||
|
You must be logged in with Nostr to deploy to nsite.{' '}
|
||||||
|
<Link
|
||||||
|
to="/settings/nostr"
|
||||||
|
className="underline hover:no-underline"
|
||||||
|
onClick={handleClose}
|
||||||
|
>
|
||||||
|
Go to Nostr Settings
|
||||||
|
</Link>
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
{error && (
|
{error && (
|
||||||
<Alert variant="destructive">
|
<Alert variant="destructive">
|
||||||
<AlertCircle className="h-4 w-4" />
|
<AlertCircle className="h-4 w-4" />
|
||||||
@@ -783,7 +954,8 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
|||||||
isDeploying ||
|
isDeploying ||
|
||||||
(selectedProvider.type === 'shakespeare' && !user) ||
|
(selectedProvider.type === 'shakespeare' && !user) ||
|
||||||
(selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) ||
|
(selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) ||
|
||||||
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
|
(selectedProvider.type === 'nsite' && !user) ||
|
||||||
|
(selectedProvider.type === 'nsite' && nsiteForm.siteType === 'named' && !nsiteForm.dTag) ||
|
||||||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
|
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
|
||||||
(selectedProvider.type === 'cloudflare' && !cloudflareForm.projectName) ||
|
(selectedProvider.type === 'cloudflare' && !cloudflareForm.projectName) ||
|
||||||
(selectedProvider.type === 'deno' && !denoDeployForm.projectName) ||
|
(selectedProvider.type === 'deno' && !denoDeployForm.projectName) ||
|
||||||
|
|||||||
@@ -1,107 +1,173 @@
|
|||||||
import { useState, useEffect, useRef } from 'react';
|
import { useState, useEffect, useRef } from 'react';
|
||||||
import { generateSecretKey, getPublicKey } from 'nostr-tools/pure';
|
import { AlertCircle, Globe, Tag } from 'lucide-react';
|
||||||
import { nip19 } from 'nostr-tools';
|
|
||||||
import { Label } from '@/components/ui/label';
|
import { Label } from '@/components/ui/label';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Input } from '@/components/ui/input';
|
||||||
import { PasswordInput } from '@/components/ui/password-input';
|
import { Textarea } from '@/components/ui/textarea';
|
||||||
import { RefreshCw } from 'lucide-react';
|
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||||
|
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
|
||||||
|
|
||||||
interface NsiteDeployFormProps {
|
interface NsiteDeployFormProps {
|
||||||
gateway: string;
|
/** Human-readable project name — used to default the title for named sites */
|
||||||
|
projectName: string;
|
||||||
|
/** Persisted values from a previous deployment */
|
||||||
|
savedSiteTitle?: string;
|
||||||
|
savedSiteDescription?: string;
|
||||||
|
savedSiteType?: 'named' | 'root';
|
||||||
|
/** Present only when the project was previously deployed with a dedicated keypair (v1) */
|
||||||
savedNsec?: string;
|
savedNsec?: string;
|
||||||
onNsecChange: (nsec: string) => void;
|
onSiteTitleChange: (title: string) => void;
|
||||||
|
onSiteDescriptionChange: (description: string) => void;
|
||||||
|
onSiteTypeChange: (type: 'named' | 'root') => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function NsiteDeployForm({
|
export function NsiteDeployForm({
|
||||||
gateway,
|
projectName,
|
||||||
|
savedSiteTitle,
|
||||||
|
savedSiteDescription,
|
||||||
|
savedSiteType,
|
||||||
savedNsec,
|
savedNsec,
|
||||||
onNsecChange,
|
onSiteTitleChange,
|
||||||
|
onSiteDescriptionChange,
|
||||||
|
onSiteTypeChange,
|
||||||
}: NsiteDeployFormProps) {
|
}: NsiteDeployFormProps) {
|
||||||
const [nsec, setNsec] = useState(savedNsec || '');
|
const [siteType, setSiteType] = useState<'named' | 'root'>(savedSiteType ?? 'named');
|
||||||
const [npub, setNpub] = useState('');
|
const [siteTitle, setSiteTitle] = useState(
|
||||||
const initialized = useRef(false);
|
savedSiteTitle ?? (savedSiteType === 'root' ? '' : projectName),
|
||||||
|
);
|
||||||
|
const [siteDescription, setSiteDescription] = useState(savedSiteDescription ?? '');
|
||||||
|
|
||||||
// Initialize nsec on mount
|
// On mount: sync all saved values to parent and set defaults.
|
||||||
|
// The component is keyed by selectedProviderId in DeploySteps, so this always
|
||||||
|
// runs with fresh props — no initialized guard needed.
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!initialized.current) {
|
if (savedSiteType) onSiteTypeChange(savedSiteType);
|
||||||
initialized.current = true;
|
if (savedSiteDescription) onSiteDescriptionChange(savedSiteDescription);
|
||||||
if (savedNsec) {
|
|
||||||
// If we have a saved nsec, notify parent immediately
|
|
||||||
onNsecChange(savedNsec);
|
|
||||||
} else if (!nsec) {
|
|
||||||
// Generate a new nsec if none exists
|
|
||||||
const sk = generateSecretKey();
|
|
||||||
const newNsec = nip19.nsecEncode(sk);
|
|
||||||
setNsec(newNsec);
|
|
||||||
onNsecChange(newNsec);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, [savedNsec, nsec, onNsecChange]);
|
|
||||||
|
|
||||||
// Update npub when nsec changes
|
const initialTitle = savedSiteTitle ?? (siteType === 'named' ? projectName : '');
|
||||||
|
if (initialTitle !== siteTitle) setSiteTitle(initialTitle);
|
||||||
|
onSiteTitleChange(initialTitle);
|
||||||
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
// When the user switches site type, update the title default only if
|
||||||
|
// the current title still matches the previous type's auto-fill value.
|
||||||
|
const prevSiteTypeRef = useRef(siteType);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (nsec) {
|
const prev = prevSiteTypeRef.current;
|
||||||
try {
|
prevSiteTypeRef.current = siteType;
|
||||||
const decoded = nip19.decode(nsec);
|
if (prev === siteType) return;
|
||||||
if (decoded.type === 'nsec') {
|
|
||||||
const pk = getPublicKey(decoded.data);
|
|
||||||
const npubEncoded = nip19.npubEncode(pk);
|
|
||||||
setNpub(npubEncoded);
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
setNpub('');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}, [nsec]);
|
|
||||||
|
|
||||||
const handleNsecChange = (value: string) => {
|
if (siteType === 'named' && siteTitle === '') {
|
||||||
setNsec(value);
|
setSiteTitle(projectName);
|
||||||
onNsecChange(value);
|
onSiteTitleChange(projectName);
|
||||||
|
} else if (siteType === 'root' && siteTitle === projectName) {
|
||||||
|
setSiteTitle('');
|
||||||
|
onSiteTitleChange('');
|
||||||
|
}
|
||||||
|
}, [siteType, siteTitle, projectName, onSiteTitleChange]);
|
||||||
|
|
||||||
|
const handleSiteTypeChange = (value: 'named' | 'root') => {
|
||||||
|
setSiteType(value);
|
||||||
|
onSiteTypeChange(value);
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleGenerateNew = () => {
|
const handleSiteTitleChange = (value: string) => {
|
||||||
const sk = generateSecretKey();
|
setSiteTitle(value);
|
||||||
const newNsec = nip19.nsecEncode(sk);
|
onSiteTitleChange(value);
|
||||||
setNsec(newNsec);
|
|
||||||
onNsecChange(newNsec);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
const fullDomain = npub ? `${npub}.${gateway}` : `npub1...${gateway}`;
|
const handleSiteDescriptionChange = (value: string) => {
|
||||||
|
setSiteDescription(value);
|
||||||
|
onSiteDescriptionChange(value);
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
|
|
||||||
|
{/* Migration notice */}
|
||||||
|
{savedNsec && (
|
||||||
|
<Alert>
|
||||||
|
<AlertCircle className="h-4 w-4" />
|
||||||
|
<AlertDescription>
|
||||||
|
<strong>Site identity is changing.</strong> This project was previously deployed with a
|
||||||
|
dedicated private key. Going forward, it will deploy under your Nostr identity. The old
|
||||||
|
site will remain at its original address until overwritten.
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Site type */}
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label>Site URL</Label>
|
<Label>Site Type</Label>
|
||||||
<p className="text-sm font-mono bg-muted p-2 rounded-md break-all">
|
<RadioGroup
|
||||||
{fullDomain}
|
value={siteType}
|
||||||
</p>
|
onValueChange={handleSiteTypeChange}
|
||||||
|
className="space-y-2"
|
||||||
|
>
|
||||||
|
<div className="flex items-start gap-3 p-3 rounded-md border cursor-pointer hover:bg-muted/50 transition-colors">
|
||||||
|
<RadioGroupItem value="named" id="nsite-type-named" className="mt-0.5" />
|
||||||
|
<label htmlFor="nsite-type-named" className="flex-1 cursor-pointer">
|
||||||
|
<div className="flex items-center gap-2 font-medium text-sm">
|
||||||
|
<Tag className="h-3.5 w-3.5" />
|
||||||
|
Named site
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground mt-0.5">
|
||||||
|
A site with a unique identifier. You can have many named sites.
|
||||||
|
</p>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-start gap-3 p-3 rounded-md border cursor-pointer hover:bg-muted/50 transition-colors">
|
||||||
|
<RadioGroupItem value="root" id="nsite-type-root" className="mt-0.5" />
|
||||||
|
<label htmlFor="nsite-type-root" className="flex-1 cursor-pointer">
|
||||||
|
<div className="flex items-center gap-2 font-medium text-sm">
|
||||||
|
<Globe className="h-3.5 w-3.5" />
|
||||||
|
Root site
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground mt-0.5">
|
||||||
|
Your personal site at your npub address. You can only have one.
|
||||||
|
</p>
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
</RadioGroup>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Root site warning */}
|
||||||
|
{siteType === 'root' && (
|
||||||
|
<Alert>
|
||||||
|
<AlertCircle className="h-4 w-4" />
|
||||||
|
<AlertDescription>
|
||||||
|
You only have one root site per Nostr identity. Deploying here will replace any
|
||||||
|
existing root site published under your key.
|
||||||
|
</AlertDescription>
|
||||||
|
</Alert>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Site title */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
<Label htmlFor="nsite-title">Site Title</Label>
|
||||||
|
<Input
|
||||||
|
id="nsite-title"
|
||||||
|
value={siteTitle}
|
||||||
|
onChange={(e) => handleSiteTitleChange(e.target.value)}
|
||||||
|
placeholder="My Nostr Site"
|
||||||
|
/>
|
||||||
<p className="text-xs text-muted-foreground">
|
<p className="text-xs text-muted-foreground">
|
||||||
Each site has a unique Nostr keypair
|
Shown by nsite gateways and directories. Included as a title tag in the manifest.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{/* Site description */}
|
||||||
<div className="space-y-2">
|
<div className="space-y-2">
|
||||||
<Label htmlFor="nsite-nsec">Site Private Key (nsec)</Label>
|
<Label htmlFor="nsite-description">Description <span className="text-muted-foreground font-normal">(optional)</span></Label>
|
||||||
<div className="flex gap-2">
|
<Textarea
|
||||||
<PasswordInput
|
id="nsite-description"
|
||||||
id="nsite-nsec"
|
value={siteDescription}
|
||||||
value={nsec}
|
onChange={(e) => handleSiteDescriptionChange(e.target.value)}
|
||||||
onChange={(e) => handleNsecChange(e.target.value)}
|
placeholder="A short description of this site…"
|
||||||
placeholder="nsec1..."
|
rows={3}
|
||||||
className="flex-1"
|
/>
|
||||||
/>
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
variant="outline"
|
|
||||||
size="icon"
|
|
||||||
onClick={handleGenerateNew}
|
|
||||||
title="Generate new key"
|
|
||||||
>
|
|
||||||
<RefreshCw className="h-4 w-4" />
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
<p className="text-xs text-muted-foreground">
|
<p className="text-xs text-muted-foreground">
|
||||||
Keep this private key secure. It's used to sign site metadata.
|
Included as a description tag in the manifest.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -15,7 +15,15 @@ const nsiteProjectConfigSchema = z.object({
|
|||||||
type: z.literal('nsite'),
|
type: z.literal('nsite'),
|
||||||
url: z.string(),
|
url: z.string(),
|
||||||
data: z.object({
|
data: z.object({
|
||||||
nsec: z.string(),
|
/** Kept optional — only present on configs created before the signer migration */
|
||||||
|
/** Kept optional — only present on configs created before the signer migration */
|
||||||
|
nsec: z.string().optional(),
|
||||||
|
siteTitle: z.string().optional(),
|
||||||
|
siteDescription: z.string().optional(),
|
||||||
|
/** Named-site dTag identifier (kind 35128). Absent → root site (kind 15128). */
|
||||||
|
dTag: z.string().optional(),
|
||||||
|
/** 'named' | 'root'. Absent on legacy configs — treated as 'named' by the form. */
|
||||||
|
siteType: z.enum(['named', 'root']).optional(),
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+315
-113
@@ -1,174 +1,376 @@
|
|||||||
import { BlossomUploader } from '@nostrify/nostrify/uploaders';
|
import type { NostrSigner, NPool } from '@nostrify/nostrify';
|
||||||
import { NSecSigner, NPool } from '@nostrify/nostrify';
|
|
||||||
import type { NostrEvent } from '@nostrify/nostrify';
|
|
||||||
import mime from 'mime';
|
import mime from 'mime';
|
||||||
import { nip19 } from 'nostr-tools';
|
import { nip19 } from 'nostr-tools';
|
||||||
import type { JSRuntimeFS } from '../JSRuntime';
|
import type { JSRuntimeFS } from '../JSRuntime';
|
||||||
import type { DeployAdapter, DeployOptions, DeployResult, NsiteDeployConfig } from './types';
|
import type { DeployAdapter, DeployOptions, DeployResult, NsiteDeployConfig } from './types';
|
||||||
|
import { buildNsiteUrl } from '../utils/nsite';
|
||||||
|
|
||||||
|
/** nsite v2 root-site kind (replaceable by pubkey+kind) */
|
||||||
|
const NSITE_ROOT_SITE_KIND = 15128;
|
||||||
|
|
||||||
|
/** nsite v2 named-site kind (addressable by pubkey+kind+d) */
|
||||||
|
const NSITE_NAMED_SITE_KIND = 35128;
|
||||||
|
|
||||||
|
/** BUD-02 Blossom authorization event kind */
|
||||||
|
const BLOSSOM_AUTH_KIND = 24242;
|
||||||
|
|
||||||
|
/** Max number of sha256 hashes covered by one batch auth event */
|
||||||
|
const UPLOAD_AUTH_BATCH_SIZE = 20;
|
||||||
|
|
||||||
|
/** Max concurrent uploads per Blossom server */
|
||||||
|
const UPLOAD_CONCURRENCY = 4;
|
||||||
|
|
||||||
|
/** Timeout for individual HTTP requests (ms) */
|
||||||
|
const FETCH_TIMEOUT_MS = 15_000;
|
||||||
|
|
||||||
|
interface FileEntry {
|
||||||
|
/** Absolute path in the manifest, e.g. "/index.html" */
|
||||||
|
path: string;
|
||||||
|
/** Raw file bytes as a concrete ArrayBuffer (for Web Crypto + File constructor compatibility) */
|
||||||
|
data: ArrayBuffer;
|
||||||
|
/** Lower-case hex SHA-256 of data */
|
||||||
|
sha256: string;
|
||||||
|
/** MIME type */
|
||||||
|
contentType: string;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Nsite Deploy Adapter
|
* Encode an ArrayBuffer / Uint8Array as a lower-case hex string.
|
||||||
* Deploys static sites to Nostr using kind 34128 events and Blossom file storage
|
*/
|
||||||
|
function encodeHex(bytes: Uint8Array): string {
|
||||||
|
return Array.from(bytes)
|
||||||
|
.map(b => b.toString(16).padStart(2, '0'))
|
||||||
|
.join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Compute the SHA-256 of a Uint8Array and return the hex digest.
|
||||||
|
* The Uint8Array must already be backed by a concrete ArrayBuffer
|
||||||
|
* (use raw.slice() before calling this to ensure no SharedArrayBuffer).
|
||||||
|
*/
|
||||||
|
async function sha256Hex(data: Uint8Array): Promise<string> {
|
||||||
|
const buf = await crypto.subtle.digest('SHA-256', data.buffer as ArrayBuffer);
|
||||||
|
return encodeHex(new Uint8Array(buf));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build a BUD-02 kind-24242 upload-auth event template covering multiple blobs.
|
||||||
|
* The signed event is base64-encoded and returned as the full Authorization header value.
|
||||||
|
*/
|
||||||
|
async function createBatchUploadAuth(
|
||||||
|
signer: NostrSigner,
|
||||||
|
sha256Hashes: string[],
|
||||||
|
): Promise<string> {
|
||||||
|
const now = Math.floor(Date.now() / 1000);
|
||||||
|
const template = {
|
||||||
|
kind: BLOSSOM_AUTH_KIND,
|
||||||
|
created_at: now,
|
||||||
|
tags: [
|
||||||
|
['t', 'upload'],
|
||||||
|
...sha256Hashes.map(h => ['x', h]),
|
||||||
|
['expiration', String(now + 3600)],
|
||||||
|
],
|
||||||
|
content: 'Upload blobs',
|
||||||
|
};
|
||||||
|
const signed = await signer.signEvent(template);
|
||||||
|
return `Nostr ${btoa(JSON.stringify(signed))}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check whether a blob already exists on a Blossom server.
|
||||||
|
* Returns true if the server responds 2xx to a HEAD request.
|
||||||
|
*/
|
||||||
|
async function blobExistsOnServer(serverBase: string, sha256: string): Promise<boolean> {
|
||||||
|
try {
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
||||||
|
try {
|
||||||
|
const resp = await fetch(`${serverBase}/${sha256}`, {
|
||||||
|
method: 'HEAD',
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
return resp.ok;
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timer);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Upload a single file to a single Blossom server using a pre-signed auth header.
|
||||||
|
* Skips the upload if the blob already exists on the server.
|
||||||
|
* Returns true on success or if already present.
|
||||||
|
*/
|
||||||
|
async function uploadToServer(
|
||||||
|
serverBase: string,
|
||||||
|
file: FileEntry,
|
||||||
|
authHeader: string,
|
||||||
|
): Promise<boolean> {
|
||||||
|
// Skip if already present
|
||||||
|
if (await blobExistsOnServer(serverBase, file.sha256)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
const blob = new File([file.data], file.path.split('/').pop() || 'file', {
|
||||||
|
type: file.contentType,
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
|
||||||
|
try {
|
||||||
|
const resp = await fetch(`${serverBase}/upload`, {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: {
|
||||||
|
Authorization: authHeader,
|
||||||
|
'Content-Type': file.contentType,
|
||||||
|
},
|
||||||
|
body: blob,
|
||||||
|
signal: controller.signal,
|
||||||
|
});
|
||||||
|
return resp.ok;
|
||||||
|
} finally {
|
||||||
|
clearTimeout(timer);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run an async task queue with a fixed concurrency limit.
|
||||||
|
*/
|
||||||
|
async function runConcurrent<T>(
|
||||||
|
items: T[],
|
||||||
|
limit: number,
|
||||||
|
fn: (item: T) => Promise<void>,
|
||||||
|
): Promise<void> {
|
||||||
|
let index = 0;
|
||||||
|
async function worker() {
|
||||||
|
while (index < items.length) {
|
||||||
|
const item = items[index++];
|
||||||
|
await fn(item);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const workers: Promise<void>[] = [];
|
||||||
|
for (let i = 0; i < Math.min(limit, items.length); i++) {
|
||||||
|
workers.push(worker());
|
||||||
|
}
|
||||||
|
await Promise.all(workers);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Nsite Deploy Adapter — v2 implementation
|
||||||
|
*
|
||||||
|
* Deploys a built project as a Nostr static site using the nsite v2 spec:
|
||||||
|
* - Uses the logged-in user's NostrSigner — no dedicated per-site keypair needed
|
||||||
|
* - Pre-hashes all files with SHA-256 (Web Crypto API)
|
||||||
|
* - Signs batched BUD-02 kind-24242 auth tokens (20 files per signing call)
|
||||||
|
* - HEAD-checks each file on each Blossom server before uploading
|
||||||
|
* - PUTs files to Blossom servers with pre-signed auth headers
|
||||||
|
* - Publishes a single kind-15128 (root) or kind-35128 (named) site manifest event
|
||||||
|
* containing all ["path", "/path", sha256] tags, ["server", url] Blossom hints,
|
||||||
|
* and ["relay", url] relay hints — no separate kind 10002 or kind 10063 published
|
||||||
|
*
|
||||||
|
* Named sites (kind 35128, siteIdentifier set):
|
||||||
|
* URL = https://{base36pubkey}{siteIdentifier}.{gateway}
|
||||||
|
* Root sites (kind 15128, no siteIdentifier):
|
||||||
|
* URL = https://{npub}.{gateway}
|
||||||
*/
|
*/
|
||||||
export class NsiteAdapter implements DeployAdapter {
|
export class NsiteAdapter implements DeployAdapter {
|
||||||
private fs: JSRuntimeFS;
|
private fs: JSRuntimeFS;
|
||||||
private nostr: NsiteDeployConfig['nostr'];
|
private nostr: NsiteDeployConfig['nostr'];
|
||||||
private nsec: string;
|
private signer: NostrSigner;
|
||||||
private gateway: string;
|
private gateway: string;
|
||||||
private relayUrls: string[];
|
private relayUrls: string[];
|
||||||
private blossomServers: string[];
|
private blossomServers: string[];
|
||||||
|
private siteTitle?: string;
|
||||||
|
private siteDescription?: string;
|
||||||
|
private siteIdentifier?: string;
|
||||||
|
|
||||||
constructor(config: NsiteDeployConfig) {
|
constructor(config: NsiteDeployConfig) {
|
||||||
this.fs = config.fs;
|
this.fs = config.fs;
|
||||||
this.nostr = config.nostr;
|
this.nostr = config.nostr;
|
||||||
this.nsec = config.nsec;
|
this.signer = config.signer;
|
||||||
this.gateway = config.gateway;
|
this.gateway = config.gateway;
|
||||||
this.relayUrls = config.relayUrls;
|
this.relayUrls = config.relayUrls;
|
||||||
this.blossomServers = config.blossomServers;
|
this.blossomServers = config.blossomServers;
|
||||||
|
this.siteTitle = config.siteTitle;
|
||||||
|
this.siteDescription = config.siteDescription;
|
||||||
|
this.siteIdentifier = config.siteIdentifier;
|
||||||
}
|
}
|
||||||
|
|
||||||
async deploy(options: DeployOptions): Promise<DeployResult> {
|
async deploy(options: DeployOptions): Promise<DeployResult> {
|
||||||
const { projectPath } = options;
|
const { projectPath } = options;
|
||||||
|
|
||||||
// Check if dist directory exists and contains index.html
|
|
||||||
const distPath = `${projectPath}/dist`;
|
const distPath = `${projectPath}/dist`;
|
||||||
|
|
||||||
|
// Verify build output exists
|
||||||
try {
|
try {
|
||||||
await this.fs.readFile(`${distPath}/index.html`, 'utf8');
|
await this.fs.readFile(`${distPath}/index.html`, 'utf8');
|
||||||
} catch {
|
} catch {
|
||||||
throw new Error('No index.html found in dist directory. Please build the project first.');
|
throw new Error('No index.html found in dist directory. Please build the project first.');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Decode nsec to get the private key and create signer
|
const pubkey = await this.signer.getPublicKey();
|
||||||
const decoded = nip19.decode(this.nsec);
|
const npub = nip19.npubEncode(pubkey);
|
||||||
if (decoded.type !== 'nsec') {
|
|
||||||
throw new Error('Invalid nsec format');
|
|
||||||
}
|
|
||||||
const signer = new NSecSigner(decoded.data);
|
|
||||||
const pubkey = await signer.getPublicKey();
|
|
||||||
|
|
||||||
// Create a grouped Nostr client for the configured relays
|
// Create grouped relay client
|
||||||
const relayClient = this.nostr.group(this.relayUrls);
|
const relayClient = this.nostr.group(this.relayUrls);
|
||||||
|
|
||||||
// Initialize Blossom uploader
|
// ── Step 1: Walk dist/ and read + hash all files ──────────────────────────
|
||||||
const uploader = new BlossomUploader({
|
const files: FileEntry[] = [];
|
||||||
servers: this.blossomServers,
|
await this.collectFiles(distPath, '', files);
|
||||||
signer,
|
|
||||||
|
if (files.length === 0) {
|
||||||
|
throw new Error('No files found in dist directory.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Step 2: Pre-sign batched BUD-02 auth tokens ───────────────────────────
|
||||||
|
// One kind-24242 event covers up to UPLOAD_AUTH_BATCH_SIZE sha256 hashes,
|
||||||
|
// dramatically reducing signer calls when using remote signers/bunkers.
|
||||||
|
const authTokenMap = new Map<string, string>();
|
||||||
|
for (let i = 0; i < files.length; i += UPLOAD_AUTH_BATCH_SIZE) {
|
||||||
|
const batch = files.slice(i, i + UPLOAD_AUTH_BATCH_SIZE);
|
||||||
|
const hashes = batch.map(f => f.sha256);
|
||||||
|
const authHeader = await createBatchUploadAuth(this.signer, hashes);
|
||||||
|
for (const hash of hashes) {
|
||||||
|
authTokenMap.set(hash, authHeader);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Step 3: Upload files to each Blossom server ───────────────────────────
|
||||||
|
// All servers upload concurrently; within each server, files are uploaded
|
||||||
|
// with limited concurrency to avoid overwhelming the server.
|
||||||
|
// Track which files land on at least one server — a file missing from every
|
||||||
|
// server means the manifest would point to an unreachable blob.
|
||||||
|
const serverBases = this.blossomServers.map(s => s.replace(/\/$/, ''));
|
||||||
|
|
||||||
|
// uploadedSha256s: set of sha256 hashes confirmed present on ≥1 server
|
||||||
|
const uploadedSha256s = new Set<string>();
|
||||||
|
|
||||||
|
await Promise.all(
|
||||||
|
serverBases.map(serverBase =>
|
||||||
|
runConcurrent(files, UPLOAD_CONCURRENCY, async (file) => {
|
||||||
|
const authHeader = authTokenMap.get(file.sha256);
|
||||||
|
if (!authHeader) return;
|
||||||
|
const ok = await uploadToServer(serverBase, file, authHeader);
|
||||||
|
if (ok) {
|
||||||
|
uploadedSha256s.add(file.sha256);
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
);
|
||||||
|
|
||||||
|
// Fail fast: any file unreachable on all servers means the deployed site
|
||||||
|
// would serve broken responses for those paths — abort before publishing.
|
||||||
|
const failedFiles = files.filter(f => !uploadedSha256s.has(f.sha256));
|
||||||
|
if (failedFiles.length > 0) {
|
||||||
|
const paths = failedFiles.map(f => f.path).join(', ');
|
||||||
|
throw new Error(
|
||||||
|
`Failed to upload ${failedFiles.length} file(s) to any Blossom server: ${paths}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Step 4: Build the site manifest event ────────────────────────────────
|
||||||
|
// kind 35128 for named sites (has siteIdentifier / d tag)
|
||||||
|
// kind 15128 for root site (no d tag)
|
||||||
|
const isNamedSite = Boolean(this.siteIdentifier);
|
||||||
|
const manifestKind = isNamedSite ? NSITE_NAMED_SITE_KIND : NSITE_ROOT_SITE_KIND;
|
||||||
|
|
||||||
|
const pathTags: string[][] = files.map(f => ['path', f.path, f.sha256]);
|
||||||
|
|
||||||
|
// SPA fallback: map /404.html to the same blob as /index.html so that
|
||||||
|
// React Router (and other SPAs) work correctly — the nsite host server
|
||||||
|
// serves /404.html when a path is not found, acting as a client-side router fallback.
|
||||||
|
const indexFile = files.find(f => f.path === '/index.html');
|
||||||
|
if (indexFile && !files.some(f => f.path === '/404.html')) {
|
||||||
|
pathTags.push(['path', '/404.html', indexFile.sha256]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const serverTags: string[][] = serverBases.map(url => ['server', url]);
|
||||||
|
const relayTags: string[][] = this.relayUrls.map(url => ['relay', url]);
|
||||||
|
|
||||||
|
const tags: string[][] = [];
|
||||||
|
|
||||||
|
// d tag must come first for addressable events (kind 35128)
|
||||||
|
if (isNamedSite && this.siteIdentifier) {
|
||||||
|
tags.push(['d', this.siteIdentifier]);
|
||||||
|
}
|
||||||
|
|
||||||
|
tags.push(...pathTags, ...serverTags, ...relayTags);
|
||||||
|
|
||||||
|
if (this.siteTitle) {
|
||||||
|
tags.push(['title', this.siteTitle]);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.siteDescription) {
|
||||||
|
tags.push(['description', this.siteDescription]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const manifestEvent = await this.signer.signEvent({
|
||||||
|
kind: manifestKind,
|
||||||
|
content: '',
|
||||||
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
|
tags,
|
||||||
});
|
});
|
||||||
|
|
||||||
// Collect all files and upload them
|
// ── Step 5: Publish manifest ──────────────────────────────────────────────
|
||||||
const fileEvents: NostrEvent[] = [];
|
// Relay and server hints are embedded as tags in the manifest itself —
|
||||||
await this.uploadDirectory(distPath, '', uploader, signer, fileEvents);
|
// no separate kind 10002 or kind 10063 events are published.
|
||||||
|
await relayClient.event(manifestEvent, { signal: AbortSignal.timeout(10_000) });
|
||||||
|
|
||||||
// Publish file events and other metadata to the relays
|
// Build the deployed URL
|
||||||
await Promise.all([
|
const siteUrl = buildNsiteUrl({
|
||||||
this.publishRelayList(signer, relayClient),
|
pubkeyHex: pubkey,
|
||||||
this.publishServerList(signer, relayClient),
|
npub,
|
||||||
...fileEvents.map(event => relayClient.event(event, { signal: AbortSignal.timeout(5000) })),
|
gateway: this.gateway,
|
||||||
]);
|
siteIdentifier: this.siteIdentifier,
|
||||||
|
});
|
||||||
// Generate npub subdomain
|
|
||||||
const npub = nip19.npubEncode(pubkey);
|
|
||||||
const siteUrl = `https://${npub}.${this.gateway}`;
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
url: siteUrl,
|
url: siteUrl,
|
||||||
metadata: {
|
metadata: {
|
||||||
pubkey,
|
pubkey,
|
||||||
npub,
|
npub,
|
||||||
filesPublished: fileEvents.length,
|
filesPublished: files.length,
|
||||||
provider: 'nsite',
|
provider: 'nsite',
|
||||||
|
siteIdentifier: this.siteIdentifier,
|
||||||
|
manifestKind,
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
private async uploadDirectory(
|
/**
|
||||||
|
* Recursively walk a directory in the VFS, reading every file and computing its SHA-256.
|
||||||
|
* Populates the provided `files` array with fully resolved FileEntry objects.
|
||||||
|
*/
|
||||||
|
private async collectFiles(
|
||||||
dirPath: string,
|
dirPath: string,
|
||||||
relativePath: string,
|
relativePrefix: string,
|
||||||
uploader: BlossomUploader,
|
files: FileEntry[],
|
||||||
signer: NSecSigner,
|
|
||||||
fileEvents: NostrEvent[]
|
|
||||||
): Promise<void> {
|
): Promise<void> {
|
||||||
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
|
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
|
||||||
|
|
||||||
for (const entry of entries) {
|
for (const entry of entries) {
|
||||||
const fullPath = `${dirPath}/${entry.name}`;
|
const fullPath = `${dirPath}/${entry.name}`;
|
||||||
const relPath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
|
const relPath = relativePrefix ? `${relativePrefix}/${entry.name}` : entry.name;
|
||||||
|
|
||||||
if (entry.isDirectory()) {
|
if (entry.isDirectory()) {
|
||||||
await this.uploadDirectory(fullPath, relPath, uploader, signer, fileEvents);
|
await this.collectFiles(fullPath, relPath, files);
|
||||||
} else if (entry.isFile()) {
|
} else if (entry.isFile()) {
|
||||||
await this.uploadFile(fullPath, relPath, uploader, signer, fileEvents);
|
const raw = await this.fs.readFile(fullPath) as Uint8Array;
|
||||||
|
// raw.slice() copies bytes into a new Uint8Array backed by a concrete ArrayBuffer,
|
||||||
|
// avoiding the SharedArrayBuffer variant that Web Crypto and File refuse.
|
||||||
|
const sliced = raw.slice();
|
||||||
|
const data: ArrayBuffer = sliced.buffer as ArrayBuffer;
|
||||||
|
const sha256 = await sha256Hex(sliced);
|
||||||
|
const absolutePath = `/${relPath}`;
|
||||||
|
const contentType = mime.getType(fullPath) || 'application/octet-stream';
|
||||||
|
|
||||||
|
files.push({ path: absolutePath, data, sha256, contentType });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private async uploadFile(
|
|
||||||
filePath: string,
|
|
||||||
relativePath: string,
|
|
||||||
uploader: BlossomUploader,
|
|
||||||
signer: NSecSigner,
|
|
||||||
fileEvents: NostrEvent[]
|
|
||||||
): Promise<void> {
|
|
||||||
try {
|
|
||||||
// Read file content
|
|
||||||
const content = await this.fs.readFile(filePath);
|
|
||||||
|
|
||||||
// Convert to File object for upload
|
|
||||||
const file = new File([content], relativePath.split('/').pop() || 'file', {
|
|
||||||
type: mime.getType(filePath) || undefined,
|
|
||||||
});
|
|
||||||
|
|
||||||
// Upload to Blossom and get tags
|
|
||||||
const tags = await uploader.upload(file);
|
|
||||||
|
|
||||||
// Extract sha256 hash from tags
|
|
||||||
// Tags format: [['url', 'https://...'], ['x', 'sha256hash'], ['size', '1234'], ...]
|
|
||||||
const xTag = tags.find(([name]) => name === 'x');
|
|
||||||
if (!xTag || !xTag[1]) {
|
|
||||||
throw new Error(`Failed to get sha256 hash for ${relativePath}`);
|
|
||||||
}
|
|
||||||
const sha256 = xTag[1];
|
|
||||||
|
|
||||||
// Create absolute path (must start with /)
|
|
||||||
const absolutePath = relativePath.startsWith('/') ? relativePath : `/${relativePath}`;
|
|
||||||
|
|
||||||
// Create kind 34128 event
|
|
||||||
const event = await signer.signEvent({
|
|
||||||
kind: 34128,
|
|
||||||
content: '',
|
|
||||||
created_at: Math.floor(Date.now() / 1000),
|
|
||||||
tags: [
|
|
||||||
['d', absolutePath],
|
|
||||||
['x', sha256],
|
|
||||||
],
|
|
||||||
});
|
|
||||||
|
|
||||||
fileEvents.push(event);
|
|
||||||
} catch (error) {
|
|
||||||
console.warn(`Failed to upload file ${filePath}:`, error);
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private async publishRelayList(signer: NSecSigner, relayClient: NPool): Promise<void> {
|
|
||||||
const relayListEvent = await signer.signEvent({
|
|
||||||
kind: 10002,
|
|
||||||
content: '',
|
|
||||||
created_at: Math.floor(Date.now() / 1000),
|
|
||||||
tags: this.relayUrls.map(url => ['r', url]),
|
|
||||||
});
|
|
||||||
|
|
||||||
await relayClient.event(relayListEvent, { signal: AbortSignal.timeout(5000) });
|
|
||||||
}
|
|
||||||
|
|
||||||
private async publishServerList(signer: NSecSigner, relayClient: NPool): Promise<void> {
|
|
||||||
const serverListEvent = await signer.signEvent({
|
|
||||||
kind: 10063,
|
|
||||||
content: '',
|
|
||||||
created_at: Math.floor(Date.now() / 1000),
|
|
||||||
tags: this.blossomServers.map(server => ['server', server]),
|
|
||||||
});
|
|
||||||
|
|
||||||
await relayClient.event(serverListEvent, { signal: AbortSignal.timeout(5000) });
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
+12
-1
@@ -49,10 +49,21 @@ export interface VercelDeployConfig {
|
|||||||
export interface NsiteDeployConfig {
|
export interface NsiteDeployConfig {
|
||||||
fs: JSRuntimeFS;
|
fs: JSRuntimeFS;
|
||||||
nostr: NPool;
|
nostr: NPool;
|
||||||
nsec: string;
|
/** Nostr signer for the logged-in user — used to sign auth events and the manifest */
|
||||||
|
signer: NostrSigner;
|
||||||
gateway: string;
|
gateway: string;
|
||||||
relayUrls: string[];
|
relayUrls: string[];
|
||||||
blossomServers: string[];
|
blossomServers: string[];
|
||||||
|
/** Optional site title included as a ["title", ...] tag in the manifest */
|
||||||
|
siteTitle?: string;
|
||||||
|
/** Optional site description included as a ["description", ...] tag in the manifest */
|
||||||
|
siteDescription?: string;
|
||||||
|
/**
|
||||||
|
* Optional named-site identifier (the `d` tag value).
|
||||||
|
* When set → publishes kind 35128 (named site), URL = {base36pubkey}{identifier}.{gateway}
|
||||||
|
* When absent → publishes kind 15128 (root site), URL = {npub}.{gateway}
|
||||||
|
*/
|
||||||
|
siteIdentifier?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface CloudflareDeployConfig {
|
export interface CloudflareDeployConfig {
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
/**
|
||||||
|
* Utilities for reading and writing the `.nsite/config.json` file in a project's VFS directory.
|
||||||
|
*
|
||||||
|
* NOTE: The site private key (nsec) is NEVER stored here. It lives only in
|
||||||
|
* `.git/shakespeare/deploy.json` (never committed). This file is safe to commit to git.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { z } from 'zod';
|
||||||
|
import type { JSRuntimeFS } from './JSRuntime';
|
||||||
|
|
||||||
|
/** Path of the nsite config directory relative to a project root */
|
||||||
|
const NSITE_CONFIG_DIR = '.nsite';
|
||||||
|
|
||||||
|
/** Path of the nsite config file relative to a project root */
|
||||||
|
const NSITE_CONFIG_FILE = '.nsite/config.json';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configuration for an nsite deployment, stored in `.nsite/config.json`.
|
||||||
|
* Unknown keys in an existing file are preserved on read and write.
|
||||||
|
*/
|
||||||
|
export interface NsiteVfsConfig {
|
||||||
|
/** Nostr relay WebSocket URLs (`wss://`) */
|
||||||
|
relays: string[];
|
||||||
|
/** Blossom server HTTPS URLs (`https://`) */
|
||||||
|
servers: string[];
|
||||||
|
/**
|
||||||
|
* Named-site d-tag identifier (kind 35128).
|
||||||
|
* `null` or absent → root site (kind 15128).
|
||||||
|
* Non-empty string → named site.
|
||||||
|
*/
|
||||||
|
id?: string | null;
|
||||||
|
/** Optional site title included in the manifest event */
|
||||||
|
title?: string;
|
||||||
|
/** Optional site description included in the manifest event */
|
||||||
|
description?: string;
|
||||||
|
/**
|
||||||
|
* HTML file served as the 404 fallback for client-side routing.
|
||||||
|
* Always `/index.html` for Shakespeare SPA projects.
|
||||||
|
*/
|
||||||
|
fallback?: string;
|
||||||
|
/** Gateway hostnames that serve this nsite */
|
||||||
|
gatewayHostnames?: string[];
|
||||||
|
}
|
||||||
|
|
||||||
|
const nsiteVfsConfigSchema = z
|
||||||
|
.object({
|
||||||
|
relays: z.array(z.string()),
|
||||||
|
servers: z.array(z.string()),
|
||||||
|
id: z.string().nullable().optional(),
|
||||||
|
title: z.string().optional(),
|
||||||
|
description: z.string().optional(),
|
||||||
|
fallback: z.string().optional(),
|
||||||
|
gatewayHostnames: z.array(z.string()).optional(),
|
||||||
|
})
|
||||||
|
.passthrough(); // preserve unknown keys in existing files
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read `.nsite/config.json` from the VFS for the given project path.
|
||||||
|
*
|
||||||
|
* Returns `null` if the file does not exist or cannot be parsed.
|
||||||
|
*/
|
||||||
|
export async function readNsiteVfsConfig(
|
||||||
|
fs: JSRuntimeFS,
|
||||||
|
projectPath: string,
|
||||||
|
): Promise<NsiteVfsConfig | null> {
|
||||||
|
const filePath = `${projectPath}/${NSITE_CONFIG_FILE}`;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const raw = await fs.readFile(filePath, 'utf8');
|
||||||
|
const parsed = JSON.parse(raw as string);
|
||||||
|
const validated = nsiteVfsConfigSchema.parse(parsed);
|
||||||
|
return validated as NsiteVfsConfig;
|
||||||
|
} catch (err) {
|
||||||
|
if (err instanceof Error && err.message.includes('ENOENT')) {
|
||||||
|
// File doesn't exist yet — not an error
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
console.warn('[nsiteConfig] Failed to read .nsite/config.json:', err);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Write `.nsite/config.json` to the VFS for the given project path.
|
||||||
|
*
|
||||||
|
* Merges with any existing file content so that unknown keys are not lost.
|
||||||
|
* Creates the `.nsite/` directory if it does not exist.
|
||||||
|
*/
|
||||||
|
export async function writeNsiteVfsConfig(
|
||||||
|
fs: JSRuntimeFS,
|
||||||
|
projectPath: string,
|
||||||
|
config: NsiteVfsConfig,
|
||||||
|
): Promise<void> {
|
||||||
|
const dirPath = `${projectPath}/${NSITE_CONFIG_DIR}`;
|
||||||
|
const filePath = `${projectPath}/${NSITE_CONFIG_FILE}`;
|
||||||
|
|
||||||
|
// Read existing file to preserve unknown keys
|
||||||
|
let existing: Record<string, unknown> = {};
|
||||||
|
try {
|
||||||
|
const raw = await fs.readFile(filePath, 'utf8');
|
||||||
|
existing = JSON.parse(raw as string);
|
||||||
|
} catch {
|
||||||
|
// File doesn't exist or is invalid — start fresh
|
||||||
|
}
|
||||||
|
|
||||||
|
// Merge: known fields overwrite, unknown keys are preserved
|
||||||
|
const merged: Record<string, unknown> = { ...existing, ...config };
|
||||||
|
|
||||||
|
// Remove undefined values so the JSON stays clean
|
||||||
|
for (const key of Object.keys(merged)) {
|
||||||
|
if (merged[key] === undefined) {
|
||||||
|
delete merged[key];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Ensure .nsite/ directory exists
|
||||||
|
try {
|
||||||
|
await fs.stat(dirPath);
|
||||||
|
} catch {
|
||||||
|
await fs.mkdir(dirPath, { recursive: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
await fs.writeFile(filePath, JSON.stringify(merged, null, 2), 'utf8');
|
||||||
|
}
|
||||||
@@ -0,0 +1,113 @@
|
|||||||
|
/**
|
||||||
|
* Utilities for the nsite v2 deployment spec.
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Max length of a valid nsite dTag — must fit as a DNS label component */
|
||||||
|
const DTAG_MAX_LENGTH = 13;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Valid nsite dTag pattern:
|
||||||
|
* - 1–13 lowercase alphanumeric characters or hyphens
|
||||||
|
* - Must start and end with an alphanumeric character (valid DNS label)
|
||||||
|
* - No consecutive hyphens
|
||||||
|
*
|
||||||
|
* Examples: "myblog", "my-blog", "site-2"
|
||||||
|
*/
|
||||||
|
const DTAG_REGEX = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?$/;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Convert a project name into a valid nsite dTag identifier.
|
||||||
|
*
|
||||||
|
* Strategy:
|
||||||
|
* 1. Lowercase, replace spaces/underscores/dots with hyphens, strip everything else.
|
||||||
|
* 2. Collapse consecutive hyphens, strip leading/trailing hyphens.
|
||||||
|
* 3. If the result is 1–13 chars and valid → use it directly.
|
||||||
|
* 4. If too long → truncate to 13, then strip any trailing hyphens.
|
||||||
|
* 5. If the result is empty (name had no alphanumeric content) →
|
||||||
|
* SHA-256 hash the original name and take the first 13 hex digits.
|
||||||
|
* This is fully deterministic: the same project name always produces the same dTag.
|
||||||
|
*
|
||||||
|
* The hash fallback produces lowercase hex (`[0-9a-f]`), which satisfies the dTag rules.
|
||||||
|
*/
|
||||||
|
export async function projectNameToDTag(name: string): Promise<string> {
|
||||||
|
const slug = name
|
||||||
|
.toLowerCase()
|
||||||
|
.replace(/[\s_./]+/g, '-') // spaces, underscores, dots → hyphens
|
||||||
|
.replace(/[^a-z0-9-]/g, '') // strip everything else
|
||||||
|
.replace(/-{2,}/g, '-') // collapse consecutive hyphens
|
||||||
|
.replace(/^-+|-+$/g, '') // strip leading/trailing hyphens
|
||||||
|
.slice(0, DTAG_MAX_LENGTH)
|
||||||
|
.replace(/-+$/g, ''); // re-strip trailing hyphens after truncation
|
||||||
|
|
||||||
|
if (slug.length >= 1) {
|
||||||
|
return slug;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Name had no usable alphanumeric content — hash for a short, stable identifier
|
||||||
|
const encoded = new TextEncoder().encode(name);
|
||||||
|
const buf = await crypto.subtle.digest('SHA-256', encoded);
|
||||||
|
const hex = Array.from(new Uint8Array(buf))
|
||||||
|
.map(b => b.toString(16).padStart(2, '0'))
|
||||||
|
.join('');
|
||||||
|
return hex.slice(0, DTAG_MAX_LENGTH);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validate that a string is an acceptable nsite dTag.
|
||||||
|
* - 1–13 characters
|
||||||
|
* - Lowercase alphanumeric and hyphens only
|
||||||
|
* - Must start and end with an alphanumeric character (valid DNS label)
|
||||||
|
*/
|
||||||
|
export function isValidDTag(value: string): boolean {
|
||||||
|
return value.length >= 1 && value.length <= DTAG_MAX_LENGTH && DTAG_REGEX.test(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Encode a 32-byte pubkey (as hex string) into a 50-character lowercase base36 string.
|
||||||
|
* Used to build named-site subdomain URLs: `{base36pubkey}{dTag}.{gateway}`
|
||||||
|
*
|
||||||
|
* Ported from nsite.run/apps/spa/src/lib/base36.js
|
||||||
|
*/
|
||||||
|
export function pubkeyToBase36(pubkeyHex: string): string {
|
||||||
|
// hex → Uint8Array
|
||||||
|
const bytes = new Uint8Array(32);
|
||||||
|
for (let i = 0; i < 32; i++) {
|
||||||
|
bytes[i] = parseInt(pubkeyHex.slice(i * 2, i * 2 + 2), 16);
|
||||||
|
}
|
||||||
|
|
||||||
|
const ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyz';
|
||||||
|
const BASE = 36n;
|
||||||
|
|
||||||
|
let value = 0n;
|
||||||
|
for (let i = 0; i < bytes.length; i++) {
|
||||||
|
value = (value << 8n) | BigInt(bytes[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const digits: string[] = [];
|
||||||
|
while (value > 0n) {
|
||||||
|
digits.push(ALPHABET[Number(value % BASE)]);
|
||||||
|
value = value / BASE;
|
||||||
|
}
|
||||||
|
|
||||||
|
return digits.reverse().join('').padStart(50, '0');
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build the deployed URL for an nsite.
|
||||||
|
*
|
||||||
|
* - Named site (kind 35128): `https://{base36pubkey}{dTag}.{gateway}`
|
||||||
|
* - Root site (kind 15128): `https://{npub}.{gateway}`
|
||||||
|
*/
|
||||||
|
export function buildNsiteUrl(opts: {
|
||||||
|
pubkeyHex: string;
|
||||||
|
npub: string;
|
||||||
|
gateway: string;
|
||||||
|
siteIdentifier?: string;
|
||||||
|
}): string {
|
||||||
|
const { pubkeyHex, npub, gateway, siteIdentifier } = opts;
|
||||||
|
if (siteIdentifier) {
|
||||||
|
const base36 = pubkeyToBase36(pubkeyHex);
|
||||||
|
return `https://${base36}${siteIdentifier}.${gateway}`;
|
||||||
|
}
|
||||||
|
return `https://${npub}.${gateway}`;
|
||||||
|
}
|
||||||
Reference in new issue
Block a user