mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Update nsite deployment
Add support for named sites under users key
This commit is contained in:
1 parent
c5ed881af0
commit
d51fee34e3
11 files changed
+1200
-262
No files matched your search
Generated
+20
@@ -4677,6 +4677,7 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4690,6 +4691,7 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4703,6 +4705,7 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4716,6 +4719,7 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4729,6 +4733,7 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4742,6 +4747,7 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4755,6 +4761,7 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4768,6 +4775,7 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4781,6 +4789,7 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4794,6 +4803,7 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4807,6 +4817,7 @@
|
||||
"cpu": [
|
||||
"loong64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4820,6 +4831,7 @@
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4833,6 +4845,7 @@
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4846,6 +4859,7 @@
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4859,6 +4873,7 @@
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4872,6 +4887,7 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4885,6 +4901,7 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4898,6 +4915,7 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4911,6 +4929,7 @@
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -4924,6 +4943,7 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Check } from 'lucide-react';
|
||||
import { UrlListEditor } from '@/components/UrlListEditor';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { PasswordInput } from '@/components/ui/password-input';
|
||||
@@ -63,8 +64,8 @@ export function AddCustomProviderDialog({
|
||||
const [customHost, setCustomHost] = useState('');
|
||||
const [customProxy, setCustomProxy] = useState(false);
|
||||
const [customGateway, setCustomGateway] = useState('');
|
||||
const [customRelayUrls, setCustomRelayUrls] = useState('');
|
||||
const [customBlossomServers, setCustomBlossomServers] = useState('');
|
||||
const [customRelayUrls, setCustomRelayUrls] = useState<string[]>([]);
|
||||
const [customBlossomServers, setCustomBlossomServers] = useState<string[]>([]);
|
||||
|
||||
const handleAdd = () => {
|
||||
if (!customProviderType || !customName.trim()) return;
|
||||
@@ -84,12 +85,8 @@ export function AddCustomProviderDialog({
|
||||
type: 'nsite',
|
||||
name: customName.trim(),
|
||||
gateway: customGateway.trim() || 'nsite.lol',
|
||||
relayUrls: customRelayUrls.trim()
|
||||
? customRelayUrls.split(',').map(s => s.trim()).filter(Boolean)
|
||||
: ['wss://relay.ditto.pub'],
|
||||
blossomServers: customBlossomServers.trim()
|
||||
? customBlossomServers.split(',').map(s => s.trim()).filter(Boolean)
|
||||
: ['https://blossom.primal.net/'],
|
||||
relayUrls: customRelayUrls.length > 0 ? customRelayUrls : ['wss://relay.ditto.pub'],
|
||||
blossomServers: customBlossomServers.length > 0 ? customBlossomServers : ['https://blossom.primal.net/'],
|
||||
};
|
||||
} else if (customProviderType === 'netlify') {
|
||||
if (!customApiKey.trim()) return;
|
||||
@@ -157,8 +154,8 @@ export function AddCustomProviderDialog({
|
||||
setCustomHost('');
|
||||
setCustomProxy(false);
|
||||
setCustomGateway('');
|
||||
setCustomRelayUrls('');
|
||||
setCustomBlossomServers('');
|
||||
setCustomRelayUrls([]);
|
||||
setCustomBlossomServers([]);
|
||||
|
||||
onOpenChange(false);
|
||||
};
|
||||
@@ -198,8 +195,8 @@ export function AddCustomProviderDialog({
|
||||
setCustomHost('');
|
||||
setCustomProxy(false);
|
||||
setCustomGateway('');
|
||||
setCustomRelayUrls('');
|
||||
setCustomBlossomServers('');
|
||||
setCustomRelayUrls([]);
|
||||
setCustomBlossomServers([]);
|
||||
}}
|
||||
>
|
||||
<SelectTrigger>
|
||||
@@ -249,7 +246,7 @@ export function AddCustomProviderDialog({
|
||||
) : customProviderType === 'nsite' ? (
|
||||
<>
|
||||
<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>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-gateway">Gateway</Label>
|
||||
@@ -260,24 +257,20 @@ export function AddCustomProviderDialog({
|
||||
onChange={(e) => setCustomGateway(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-relays">Relay URLs (comma-separated)</Label>
|
||||
<Input
|
||||
id="custom-relays"
|
||||
placeholder="wss://relay.ditto.pub, wss://relay.damus.io"
|
||||
value={customRelayUrls}
|
||||
onChange={(e) => setCustomRelayUrls(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-blossom">Blossom Servers (comma-separated)</Label>
|
||||
<Input
|
||||
id="custom-blossom"
|
||||
placeholder="https://blossom.primal.net/"
|
||||
value={customBlossomServers}
|
||||
onChange={(e) => setCustomBlossomServers(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<UrlListEditor
|
||||
label="Relay URLs"
|
||||
items={customRelayUrls}
|
||||
onChange={setCustomRelayUrls}
|
||||
protocol="wss"
|
||||
placeholder="relay.ditto.pub"
|
||||
/>
|
||||
<UrlListEditor
|
||||
label="Blossom Servers"
|
||||
items={customBlossomServers}
|
||||
onChange={setCustomBlossomServers}
|
||||
protocol="https"
|
||||
placeholder="blossom.primal.net"
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
||||
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { UrlListEditor } from '@/components/UrlListEditor';
|
||||
|
||||
interface ProviderConfigDialogProps {
|
||||
open: boolean;
|
||||
@@ -138,34 +139,22 @@ export function ProviderConfigDialog({
|
||||
onChange={(e) => setLocalProvider({ ...localProvider, gateway: e.target.value })}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-relays">
|
||||
Relay URLs (comma-separated) <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="provider-relays"
|
||||
placeholder="wss://relay.ditto.pub, wss://relay.damus.io"
|
||||
value={localProvider.relayUrls?.join(', ') || ''}
|
||||
onChange={(e) => setLocalProvider({
|
||||
...localProvider,
|
||||
relayUrls: e.target.value.split(',').map(s => s.trim()).filter(Boolean)
|
||||
})}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<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>
|
||||
<UrlListEditor
|
||||
label="Relay URLs"
|
||||
items={localProvider.relayUrls ?? []}
|
||||
onChange={(urls) => setLocalProvider({ ...localProvider, relayUrls: urls })}
|
||||
protocol="wss"
|
||||
placeholder="relay.ditto.pub"
|
||||
required
|
||||
/>
|
||||
<UrlListEditor
|
||||
label="Blossom Servers"
|
||||
items={localProvider.blossomServers ?? []}
|
||||
onChange={(servers) => setLocalProvider({ ...localProvider, blossomServers: servers })}
|
||||
protocol="https"
|
||||
placeholder="blossom.primal.net"
|
||||
required
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
|
||||
@@ -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,8 @@ import { VercelAdapter } from '@/lib/deploy/VercelAdapter';
|
||||
import { CloudflareAdapter } from '@/lib/deploy/CloudflareAdapter';
|
||||
import { DenoDeployAdapter } from '@/lib/deploy/DenoDeployAdapter';
|
||||
import { RailwayAdapter } from '@/lib/deploy/RailwayAdapter';
|
||||
import { readNsiteVfsConfig, writeNsiteVfsConfig } from '@/lib/nsiteConfig';
|
||||
import type { NsiteVfsConfig } from '@/lib/nsiteConfig';
|
||||
|
||||
/**
|
||||
* Normalize a URL string to ensure it has a protocol
|
||||
@@ -85,7 +87,10 @@ interface ShakespeareFormData {
|
||||
}
|
||||
|
||||
interface NsiteFormData {
|
||||
nsec: string;
|
||||
siteTitle: string;
|
||||
siteDescription: string;
|
||||
dTag: string;
|
||||
siteType: 'named' | 'root';
|
||||
}
|
||||
|
||||
interface NetlifyFormData {
|
||||
@@ -132,12 +137,49 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
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
|
||||
const [shakespeareForm, setShakespeareForm] = useState<ShakespeareFormData>({
|
||||
subdomain: projectId,
|
||||
});
|
||||
const [nsiteForm, setNsiteForm] = useState<NsiteFormData>({
|
||||
nsec: '',
|
||||
siteTitle: '',
|
||||
siteDescription: '',
|
||||
dTag: '',
|
||||
siteType: 'named',
|
||||
});
|
||||
const [netlifyForm, setNetlifyForm] = useState<NetlifyFormData>({
|
||||
siteId: '',
|
||||
@@ -205,17 +247,22 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
} else if (selectedProvider.type === 'nsite') {
|
||||
const nsiteProvider = selectedProvider;
|
||||
|
||||
if (!nsiteForm.nsec) {
|
||||
throw new Error('Site private key (nsec) is required');
|
||||
if (!user) {
|
||||
throw new Error('You must be logged in to deploy to nsite.');
|
||||
}
|
||||
|
||||
adapter = new NsiteAdapter({
|
||||
fs,
|
||||
nostr,
|
||||
nsec: nsiteForm.nsec,
|
||||
signer: user.signer,
|
||||
gateway: nsiteProvider.gateway,
|
||||
relayUrls: nsiteProvider.relayUrls,
|
||||
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') {
|
||||
const netlifyProvider = selectedProvider;
|
||||
@@ -324,9 +371,29 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
type: 'nsite',
|
||||
url: result.url,
|
||||
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') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'netlify',
|
||||
@@ -434,12 +501,14 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
setError(null);
|
||||
// Reset forms
|
||||
setShakespeareForm({ subdomain: projectId });
|
||||
setNsiteForm({ nsec: '' });
|
||||
setNsiteForm({ siteTitle: '', siteDescription: '', dTag: '', siteType: 'named' });
|
||||
setNetlifyForm({ siteId: '', siteName: '' });
|
||||
setVercelForm({ projectName: projectName || projectId, teamId: '' });
|
||||
setCloudflareForm({ projectName: projectName || projectId });
|
||||
setDenoDeployForm({ 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();
|
||||
};
|
||||
|
||||
@@ -451,8 +520,20 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
setIsShakespeareFormValid(isValid);
|
||||
}, []);
|
||||
|
||||
const handleNsiteNsecChange = useCallback((nsec: string) => {
|
||||
setNsiteForm({ nsec });
|
||||
const handleNsiteSiteTitleChange = useCallback((siteTitle: string) => {
|
||||
setNsiteForm(prev => ({ ...prev, siteTitle }));
|
||||
}, []);
|
||||
|
||||
const handleNsiteSiteDescriptionChange = useCallback((siteDescription: string) => {
|
||||
setNsiteForm(prev => ({ ...prev, siteDescription }));
|
||||
}, []);
|
||||
|
||||
const handleNsiteDTagChange = useCallback((dTag: string) => {
|
||||
setNsiteForm(prev => ({ ...prev, dTag }));
|
||||
}, []);
|
||||
|
||||
const handleNsiteSiteTypeChange = useCallback((siteType: 'named' | 'root') => {
|
||||
setNsiteForm(prev => ({ ...prev, siteType }));
|
||||
}, []);
|
||||
|
||||
const handleNetlifySiteChange = useCallback((siteId: string, siteName: string) => {
|
||||
@@ -501,15 +582,94 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
}
|
||||
|
||||
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 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 savedDTag = (nsiteVfsConfig?.id != null && nsiteVfsConfig.id !== '')
|
||||
? nsiteVfsConfig.id
|
||||
: legacy?.dTag;
|
||||
const savedSiteType = nsiteVfsConfig
|
||||
? (nsiteVfsConfig.id === null ? 'root' : 'named')
|
||||
: legacy?.siteType;
|
||||
|
||||
return (
|
||||
<NsiteDeployForm
|
||||
gateway={selectedProvider.gateway}
|
||||
savedNsec={savedNsec}
|
||||
onNsecChange={handleNsiteNsecChange}
|
||||
/>
|
||||
<div className="space-y-3">
|
||||
<NsiteDeployForm
|
||||
key={selectedProviderId}
|
||||
gateway={selectedProvider.gateway}
|
||||
projectName={projectName || projectId}
|
||||
userPubkey={user?.pubkey}
|
||||
savedNsec={legacy?.nsec}
|
||||
savedSiteTitle={savedSiteTitle}
|
||||
savedSiteDescription={savedSiteDescription}
|
||||
savedDTag={savedDTag}
|
||||
savedSiteType={savedSiteType}
|
||||
onSiteTitleChange={handleNsiteSiteTitleChange}
|
||||
onSiteDescriptionChange={handleNsiteSiteDescriptionChange}
|
||||
onDTagChange={handleNsiteDTagChange}
|
||||
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 +929,22 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
</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 && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
@@ -783,7 +959,8 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
isDeploying ||
|
||||
(selectedProvider.type === 'shakespeare' && !user) ||
|
||||
(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 === 'cloudflare' && !cloudflareForm.projectName) ||
|
||||
(selectedProvider.type === 'deno' && !denoDeployForm.projectName) ||
|
||||
|
||||
@@ -1,107 +1,261 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { generateSecretKey, getPublicKey } from 'nostr-tools/pure';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { AlertCircle, Globe, Tag } from 'lucide-react';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { PasswordInput } from '@/components/ui/password-input';
|
||||
import { RefreshCw } from 'lucide-react';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
|
||||
import { projectNameToDTag, isValidDTag, pubkeyToBase36 } from '@/lib/utils/nsite';
|
||||
|
||||
interface NsiteDeployFormProps {
|
||||
gateway: string;
|
||||
/** Human-readable project name — used to derive the default dTag and title */
|
||||
projectName: string;
|
||||
/** Hex pubkey of the logged-in user — used for URL preview */
|
||||
userPubkey?: string;
|
||||
/** Persisted values from a previous deployment */
|
||||
savedSiteTitle?: string;
|
||||
savedSiteDescription?: string;
|
||||
savedDTag?: string;
|
||||
savedSiteType?: 'named' | 'root';
|
||||
/** Present only when the project was previously deployed with a dedicated keypair (v1) */
|
||||
savedNsec?: string;
|
||||
onNsecChange: (nsec: string) => void;
|
||||
onSiteTitleChange: (title: string) => void;
|
||||
onSiteDescriptionChange: (description: string) => void;
|
||||
onDTagChange: (dTag: string) => void;
|
||||
onSiteTypeChange: (type: 'named' | 'root') => void;
|
||||
}
|
||||
|
||||
export function NsiteDeployForm({
|
||||
gateway,
|
||||
projectName,
|
||||
userPubkey,
|
||||
savedSiteTitle,
|
||||
savedSiteDescription,
|
||||
savedDTag,
|
||||
savedSiteType,
|
||||
savedNsec,
|
||||
onNsecChange,
|
||||
onSiteTitleChange,
|
||||
onSiteDescriptionChange,
|
||||
onDTagChange,
|
||||
onSiteTypeChange,
|
||||
}: NsiteDeployFormProps) {
|
||||
const [nsec, setNsec] = useState(savedNsec || '');
|
||||
const [npub, setNpub] = useState('');
|
||||
const initialized = useRef(false);
|
||||
const [siteType, setSiteType] = useState<'named' | 'root'>(savedSiteType ?? 'named');
|
||||
const [dTag, setDTag] = useState(savedDTag ?? '');
|
||||
const [siteTitle, setSiteTitle] = useState(
|
||||
savedSiteTitle ?? (savedSiteType === 'root' ? '' : projectName),
|
||||
);
|
||||
const [siteDescription, setSiteDescription] = useState(savedSiteDescription ?? '');
|
||||
const [previewUrl, setPreviewUrl] = useState('');
|
||||
|
||||
// Initialize nsec on mount
|
||||
// On mount: sync all saved values to parent; derive dTag and title defaults when absent.
|
||||
// The component is keyed by selectedProviderId in DeploySteps, so this effect always
|
||||
// runs with fresh props — no initialized guard needed.
|
||||
useEffect(() => {
|
||||
if (!initialized.current) {
|
||||
initialized.current = true;
|
||||
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]);
|
||||
if (savedSiteType) onSiteTypeChange(savedSiteType);
|
||||
if (savedSiteDescription) onSiteDescriptionChange(savedSiteDescription);
|
||||
|
||||
// Update npub when nsec changes
|
||||
// Title: use saved value, else default to projectName for named sites only
|
||||
const initialTitle = savedSiteTitle ?? (siteType === 'named' ? projectName : '');
|
||||
if (initialTitle !== siteTitle) setSiteTitle(initialTitle);
|
||||
onSiteTitleChange(initialTitle);
|
||||
|
||||
// dTag: use saved value, else derive from project name
|
||||
if (savedDTag) {
|
||||
onDTagChange(savedDTag);
|
||||
} else {
|
||||
projectNameToDTag(projectName).then(derived => {
|
||||
setDTag(derived);
|
||||
onDTagChange(derived);
|
||||
});
|
||||
}
|
||||
// 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(() => {
|
||||
if (nsec) {
|
||||
try {
|
||||
const decoded = nip19.decode(nsec);
|
||||
if (decoded.type === 'nsec') {
|
||||
const pk = getPublicKey(decoded.data);
|
||||
const npubEncoded = nip19.npubEncode(pk);
|
||||
setNpub(npubEncoded);
|
||||
}
|
||||
} catch {
|
||||
setNpub('');
|
||||
}
|
||||
}
|
||||
}, [nsec]);
|
||||
const prev = prevSiteTypeRef.current;
|
||||
prevSiteTypeRef.current = siteType;
|
||||
if (prev === siteType) return;
|
||||
|
||||
const handleNsecChange = (value: string) => {
|
||||
setNsec(value);
|
||||
onNsecChange(value);
|
||||
if (siteType === 'named' && siteTitle === '') {
|
||||
// Switching to named with a blank title → fill with project name
|
||||
setSiteTitle(projectName);
|
||||
onSiteTitleChange(projectName);
|
||||
} else if (siteType === 'root' && siteTitle === projectName) {
|
||||
// Switching to root and title is still the auto-filled project name → clear it
|
||||
setSiteTitle('');
|
||||
onSiteTitleChange('');
|
||||
}
|
||||
}, [siteType, siteTitle, projectName, onSiteTitleChange]);
|
||||
|
||||
// Recompute preview URL whenever relevant state changes
|
||||
useEffect(() => {
|
||||
if (!userPubkey) {
|
||||
setPreviewUrl('');
|
||||
return;
|
||||
}
|
||||
if (siteType === 'root') {
|
||||
const npub = nip19.npubEncode(userPubkey);
|
||||
setPreviewUrl(`https://${npub}.${gateway}`);
|
||||
} else if (dTag && isValidDTag(dTag)) {
|
||||
const base36 = pubkeyToBase36(userPubkey);
|
||||
setPreviewUrl(`https://${base36}${dTag}.${gateway}`);
|
||||
} else {
|
||||
setPreviewUrl('');
|
||||
}
|
||||
}, [userPubkey, siteType, dTag, gateway]);
|
||||
|
||||
const handleSiteTypeChange = (value: 'named' | 'root') => {
|
||||
setSiteType(value);
|
||||
onSiteTypeChange(value);
|
||||
};
|
||||
|
||||
const handleGenerateNew = () => {
|
||||
const sk = generateSecretKey();
|
||||
const newNsec = nip19.nsecEncode(sk);
|
||||
setNsec(newNsec);
|
||||
onNsecChange(newNsec);
|
||||
const handleDTagChange = (value: string) => {
|
||||
// Allow lowercase alphanumeric and hyphens; strip everything else.
|
||||
// Leading/trailing hyphens and consecutive hyphens are caught by isValidDTag
|
||||
// and shown as a validation error rather than silently removed while typing.
|
||||
const clean = value.toLowerCase().replace(/[^a-z0-9-]/g, '');
|
||||
setDTag(clean);
|
||||
onDTagChange(clean);
|
||||
};
|
||||
|
||||
const fullDomain = npub ? `${npub}.${gateway}` : `npub1...${gateway}`;
|
||||
const handleSiteTitleChange = (value: string) => {
|
||||
setSiteTitle(value);
|
||||
onSiteTitleChange(value);
|
||||
};
|
||||
|
||||
const handleSiteDescriptionChange = (value: string) => {
|
||||
setSiteDescription(value);
|
||||
onSiteDescriptionChange(value);
|
||||
};
|
||||
|
||||
const dTagInvalid = siteType === 'named' && dTag.length > 0 && !isValidDTag(dTag);
|
||||
|
||||
return (
|
||||
<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">
|
||||
<Label>Site URL</Label>
|
||||
<p className="text-sm font-mono bg-muted p-2 rounded-md break-all">
|
||||
{fullDomain}
|
||||
</p>
|
||||
<Label>Site Type</Label>
|
||||
<RadioGroup
|
||||
value={siteType}
|
||||
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 custom 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>
|
||||
|
||||
{/* Named site identifier */}
|
||||
{siteType === 'named' && (
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="nsite-dtag">Site Identifier</Label>
|
||||
<Input
|
||||
id="nsite-dtag"
|
||||
value={dTag}
|
||||
onChange={(e) => handleDTagChange(e.target.value)}
|
||||
placeholder="myblog"
|
||||
maxLength={13}
|
||||
className={dTagInvalid ? 'border-destructive' : ''}
|
||||
/>
|
||||
{dTagInvalid ? (
|
||||
<p className="text-xs text-destructive">
|
||||
Must be 1–13 lowercase letters, digits, or hyphens. Cannot start or end with a hyphen.
|
||||
</p>
|
||||
) : (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Lowercase letters, digits, and hyphens, max 13 characters.
|
||||
</p>
|
||||
)}
|
||||
</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>
|
||||
)}
|
||||
|
||||
{/* Live URL preview */}
|
||||
{previewUrl && (
|
||||
<div className="space-y-1">
|
||||
<Label>Site URL</Label>
|
||||
<p className="text-sm font-mono bg-muted p-2 rounded-md break-all">
|
||||
{previewUrl}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* 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">
|
||||
Each site has a unique Nostr keypair
|
||||
Shown by nsite gateways and directories. Included as a title tag in the manifest.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Site description */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="nsite-nsec">Site Private Key (nsec)</Label>
|
||||
<div className="flex gap-2">
|
||||
<PasswordInput
|
||||
id="nsite-nsec"
|
||||
value={nsec}
|
||||
onChange={(e) => handleNsecChange(e.target.value)}
|
||||
placeholder="nsec1..."
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={handleGenerateNew}
|
||||
title="Generate new key"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<Label htmlFor="nsite-description">Description <span className="text-muted-foreground font-normal">(optional)</span></Label>
|
||||
<Textarea
|
||||
id="nsite-description"
|
||||
value={siteDescription}
|
||||
onChange={(e) => handleSiteDescriptionChange(e.target.value)}
|
||||
placeholder="A short description of this site…"
|
||||
rows={3}
|
||||
/>
|
||||
<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>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -15,7 +15,15 @@ const nsiteProjectConfigSchema = z.object({
|
||||
type: z.literal('nsite'),
|
||||
url: z.string(),
|
||||
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 { NSecSigner, NPool } from '@nostrify/nostrify';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import type { NostrSigner, NPool } from '@nostrify/nostrify';
|
||||
import mime from 'mime';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
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
|
||||
* Deploys static sites to Nostr using kind 34128 events and Blossom file storage
|
||||
* Encode an ArrayBuffer / Uint8Array as a lower-case hex string.
|
||||
*/
|
||||
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 {
|
||||
private fs: JSRuntimeFS;
|
||||
private nostr: NsiteDeployConfig['nostr'];
|
||||
private nsec: string;
|
||||
private signer: NostrSigner;
|
||||
private gateway: string;
|
||||
private relayUrls: string[];
|
||||
private blossomServers: string[];
|
||||
private siteTitle?: string;
|
||||
private siteDescription?: string;
|
||||
private siteIdentifier?: string;
|
||||
|
||||
constructor(config: NsiteDeployConfig) {
|
||||
this.fs = config.fs;
|
||||
this.nostr = config.nostr;
|
||||
this.nsec = config.nsec;
|
||||
this.signer = config.signer;
|
||||
this.gateway = config.gateway;
|
||||
this.relayUrls = config.relayUrls;
|
||||
this.blossomServers = config.blossomServers;
|
||||
this.siteTitle = config.siteTitle;
|
||||
this.siteDescription = config.siteDescription;
|
||||
this.siteIdentifier = config.siteIdentifier;
|
||||
}
|
||||
|
||||
async deploy(options: DeployOptions): Promise<DeployResult> {
|
||||
const { projectPath } = options;
|
||||
|
||||
// Check if dist directory exists and contains index.html
|
||||
const distPath = `${projectPath}/dist`;
|
||||
|
||||
// Verify build output exists
|
||||
try {
|
||||
await this.fs.readFile(`${distPath}/index.html`, 'utf8');
|
||||
} catch {
|
||||
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 decoded = nip19.decode(this.nsec);
|
||||
if (decoded.type !== 'nsec') {
|
||||
throw new Error('Invalid nsec format');
|
||||
}
|
||||
const signer = new NSecSigner(decoded.data);
|
||||
const pubkey = await signer.getPublicKey();
|
||||
const pubkey = await this.signer.getPublicKey();
|
||||
const npub = nip19.npubEncode(pubkey);
|
||||
|
||||
// Create a grouped Nostr client for the configured relays
|
||||
// Create grouped relay client
|
||||
const relayClient = this.nostr.group(this.relayUrls);
|
||||
|
||||
// Initialize Blossom uploader
|
||||
const uploader = new BlossomUploader({
|
||||
servers: this.blossomServers,
|
||||
signer,
|
||||
// ── Step 1: Walk dist/ and read + hash all files ──────────────────────────
|
||||
const files: FileEntry[] = [];
|
||||
await this.collectFiles(distPath, '', files);
|
||||
|
||||
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
|
||||
const fileEvents: NostrEvent[] = [];
|
||||
await this.uploadDirectory(distPath, '', uploader, signer, fileEvents);
|
||||
// ── Step 5: Publish manifest ──────────────────────────────────────────────
|
||||
// Relay and server hints are embedded as tags in the manifest itself —
|
||||
// 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
|
||||
await Promise.all([
|
||||
this.publishRelayList(signer, relayClient),
|
||||
this.publishServerList(signer, relayClient),
|
||||
...fileEvents.map(event => relayClient.event(event, { signal: AbortSignal.timeout(5000) })),
|
||||
]);
|
||||
|
||||
// Generate npub subdomain
|
||||
const npub = nip19.npubEncode(pubkey);
|
||||
const siteUrl = `https://${npub}.${this.gateway}`;
|
||||
// Build the deployed URL
|
||||
const siteUrl = buildNsiteUrl({
|
||||
pubkeyHex: pubkey,
|
||||
npub,
|
||||
gateway: this.gateway,
|
||||
siteIdentifier: this.siteIdentifier,
|
||||
});
|
||||
|
||||
return {
|
||||
url: siteUrl,
|
||||
metadata: {
|
||||
pubkey,
|
||||
npub,
|
||||
filesPublished: fileEvents.length,
|
||||
filesPublished: files.length,
|
||||
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,
|
||||
relativePath: string,
|
||||
uploader: BlossomUploader,
|
||||
signer: NSecSigner,
|
||||
fileEvents: NostrEvent[]
|
||||
relativePrefix: string,
|
||||
files: FileEntry[],
|
||||
): Promise<void> {
|
||||
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullPath = `${dirPath}/${entry.name}`;
|
||||
const relPath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
|
||||
const relPath = relativePrefix ? `${relativePrefix}/${entry.name}` : entry.name;
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
await this.uploadDirectory(fullPath, relPath, uploader, signer, fileEvents);
|
||||
await this.collectFiles(fullPath, relPath, files);
|
||||
} 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 {
|
||||
fs: JSRuntimeFS;
|
||||
nostr: NPool;
|
||||
nsec: string;
|
||||
/** Nostr signer for the logged-in user — used to sign auth events and the manifest */
|
||||
signer: NostrSigner;
|
||||
gateway: string;
|
||||
relayUrls: 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 {
|
||||
|
||||
@@ -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