mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Deploy to the gateway that actually serves shakespeare.wtf now
Shakespeare Deploy uploaded a zip to a host that kept the files itself. That host has been replaced: those domains are served out of nsite manifests, so a deploy through the old API has been succeeding and changing nothing anyone can see. This replaces it. NpanelAdapter is NsiteAdapter plus a name. The site is an ordinary nsite under the user's own key — same event, readable by any nsite client, gateway or no gateway — and the second half of the deploy asks the gateway to point a hostname at it. Its predecessor claimed names implicitly, by watching relays and reserving whichever d tag it saw first; this one keeps an explicit row, which is what makes a name something its owner holds rather than something they won a race for. The hostname is asked about before it is claimed, because "nobody holds this", "I already hold this" and "somebody else holds this" are three different acts and creating-then-reading-the-409 cannot tell the last two apart. The name field checks availability as you type, against an endpoint that takes no credentials: somebody choosing a name has not decided to make an account yet. A name this project already deployed to is not reported as taken — it is theirs. An unreachable gateway reports available, because being wrong that way costs a clear error at deploy time, and being wrong the other way tells someone a free name is taken and they settle for worse. Also fixes readDeploySettings, which swallowed a missing file and an unreadable one alike and answered "no providers" to both. The default provider it was meant to hand new users had therefore never reached anybody: it was written, saved back as an empty list on the next render, and gone. The two cases are now distinct, because inventing defaults for a file that exists but will not parse would silently replace whatever the user had. Providers and per-project deploy records saved under the old type are migrated on load rather than dropped. The project file holds one record per provider a project ever deployed to, so rejecting one entry would take a Netlify site id and a Vercel project id with it. Verified end to end against the live gateway: a fresh key self-enrolled, uploaded a blob, published a manifest, claimed a name, and the site served publicly with the SPA fallback working on a deep path. The package-lock version bump is npm reconciling it with package.json, which had drifted before this work.
This commit is contained in:
19 files changed
+1083
-353
No files matched your search
Generated
+2
-27
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "shakespeare.diy",
|
||||
"version": "9.14.0",
|
||||
"version": "9.15.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "shakespeare.diy",
|
||||
"version": "9.14.0",
|
||||
"version": "9.15.0",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"dependencies": {
|
||||
"@capacitor/app": "^8.1.0",
|
||||
@@ -5052,7 +5052,6 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5066,7 +5065,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5080,7 +5078,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5094,7 +5091,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5108,7 +5104,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5122,7 +5117,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5136,7 +5130,6 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5150,7 +5143,6 @@
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5164,7 +5156,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5178,7 +5169,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5192,7 +5182,6 @@
|
||||
"cpu": [
|
||||
"loong64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5206,7 +5195,6 @@
|
||||
"cpu": [
|
||||
"loong64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5220,7 +5208,6 @@
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5234,7 +5221,6 @@
|
||||
"cpu": [
|
||||
"ppc64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5248,7 +5234,6 @@
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5262,7 +5247,6 @@
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5276,7 +5260,6 @@
|
||||
"cpu": [
|
||||
"s390x"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5290,7 +5273,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5304,7 +5286,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5318,7 +5299,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5332,7 +5312,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5346,7 +5325,6 @@
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5360,7 +5338,6 @@
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5374,7 +5351,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
@@ -5388,7 +5364,6 @@
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import type {
|
||||
ShakespeareDeployProvider,
|
||||
NpanelProvider,
|
||||
NetlifyProvider,
|
||||
VercelProvider,
|
||||
NsiteProvider,
|
||||
@@ -34,7 +34,7 @@ import type {
|
||||
|
||||
// Type for provider without the 'id' field (will be generated)
|
||||
type DeployProviderInput =
|
||||
| Omit<ShakespeareDeployProvider, 'id'>
|
||||
| Omit<NpanelProvider, 'id'>
|
||||
| Omit<NetlifyProvider, 'id'>
|
||||
| Omit<VercelProvider, 'id'>
|
||||
| Omit<NsiteProvider, 'id'>
|
||||
@@ -54,14 +54,14 @@ export function AddCustomProviderDialog({
|
||||
onAdd,
|
||||
}: AddCustomProviderDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway' | ''>('');
|
||||
const [customProviderType, setCustomProviderType] = useState<'npanel' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway' | ''>('');
|
||||
const [customName, setCustomName] = useState('');
|
||||
const [customApiKey, setCustomApiKey] = useState('');
|
||||
const [customAccountId, setCustomAccountId] = useState('');
|
||||
const [customOrganizationId, setCustomOrganizationId] = useState('');
|
||||
const [customBaseURL, setCustomBaseURL] = useState('');
|
||||
const [customBaseDomain, setCustomBaseDomain] = useState('');
|
||||
const [customHost, setCustomHost] = useState('');
|
||||
const [customDashboardHost, setCustomDashboardHost] = useState('');
|
||||
const [customProxy, setCustomProxy] = useState(false);
|
||||
const [customGateway, setCustomGateway] = useState('');
|
||||
const [customRelayUrls, setCustomRelayUrls] = useState<string[]>([]);
|
||||
@@ -73,12 +73,15 @@ export function AddCustomProviderDialog({
|
||||
// Build provider object based on type
|
||||
let provider: DeployProviderInput;
|
||||
|
||||
if (customProviderType === 'shakespeare') {
|
||||
if (customProviderType === 'npanel') {
|
||||
if (!customDashboardHost.trim() || !customGateway.trim()) return;
|
||||
provider = {
|
||||
type: 'shakespeare',
|
||||
type: 'npanel',
|
||||
name: customName.trim(),
|
||||
...(customHost?.trim() && { host: customHost.trim() }),
|
||||
...(customProxy && { proxy: true }),
|
||||
dashboardHost: customDashboardHost.trim(),
|
||||
domain: customGateway.trim(),
|
||||
relayUrls: customRelayUrls.length > 0 ? customRelayUrls : ['wss://relay.ditto.pub'],
|
||||
blossomServers: customBlossomServers.length > 0 ? customBlossomServers : ['https://blossom.ditto.pub/', 'https://blossom.dreamith.to/'],
|
||||
};
|
||||
} else if (customProviderType === 'nsite') {
|
||||
provider = {
|
||||
@@ -151,7 +154,7 @@ export function AddCustomProviderDialog({
|
||||
setCustomOrganizationId('');
|
||||
setCustomBaseURL('');
|
||||
setCustomBaseDomain('');
|
||||
setCustomHost('');
|
||||
setCustomDashboardHost('');
|
||||
setCustomProxy(false);
|
||||
setCustomGateway('');
|
||||
setCustomRelayUrls([]);
|
||||
@@ -160,12 +163,22 @@ export function AddCustomProviderDialog({
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const isValid = customProviderType && customName.trim() &&
|
||||
(customProviderType === 'shakespeare' || customProviderType === 'nsite' ||
|
||||
(customApiKey.trim() &&
|
||||
(customProviderType !== 'cloudflare' || customAccountId.trim()) &&
|
||||
(customProviderType !== 'deno' || customOrganizationId.trim()) &&
|
||||
(customProviderType !== 'railway' || true)));
|
||||
const hasRequiredFields = () => {
|
||||
// A gateway is named by two hosts and reached with a Nostr key, so there is
|
||||
// no API key to ask for — but it cannot be guessed at either.
|
||||
if (customProviderType === 'npanel') {
|
||||
return Boolean(customDashboardHost.trim() && customGateway.trim());
|
||||
}
|
||||
// Plain nsite needs nothing beyond a name: it has defaults for the rest.
|
||||
if (customProviderType === 'nsite') return true;
|
||||
|
||||
if (!customApiKey.trim()) return false;
|
||||
if (customProviderType === 'cloudflare') return Boolean(customAccountId.trim());
|
||||
if (customProviderType === 'deno') return Boolean(customOrganizationId.trim());
|
||||
return true;
|
||||
};
|
||||
|
||||
const isValid = Boolean(customProviderType && customName.trim() && hasRequiredFields());
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
@@ -184,7 +197,7 @@ export function AddCustomProviderDialog({
|
||||
</Label>
|
||||
<Select
|
||||
value={customProviderType}
|
||||
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway') => {
|
||||
onValueChange={(value: 'npanel' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway') => {
|
||||
setCustomProviderType(value);
|
||||
// Reset form when provider type changes
|
||||
setCustomApiKey('');
|
||||
@@ -192,7 +205,7 @@ export function AddCustomProviderDialog({
|
||||
setCustomOrganizationId('');
|
||||
setCustomBaseURL('');
|
||||
setCustomBaseDomain('');
|
||||
setCustomHost('');
|
||||
setCustomDashboardHost('');
|
||||
setCustomProxy(false);
|
||||
setCustomGateway('');
|
||||
setCustomRelayUrls([]);
|
||||
@@ -203,7 +216,7 @@ export function AddCustomProviderDialog({
|
||||
<SelectValue placeholder={t('selectProviderType')} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="shakespeare">Shakespeare Deploy</SelectItem>
|
||||
<SelectItem value="npanel">nsite gateway</SelectItem>
|
||||
<SelectItem value="nsite">nsite</SelectItem>
|
||||
<SelectItem value="netlify">Netlify</SelectItem>
|
||||
<SelectItem value="vercel">Vercel</SelectItem>
|
||||
@@ -228,20 +241,53 @@ export function AddCustomProviderDialog({
|
||||
/>
|
||||
</div>
|
||||
|
||||
{customProviderType === 'shakespeare' ? (
|
||||
{customProviderType === 'npanel' ? (
|
||||
<>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('shakespeareDeployNostrAuth')}
|
||||
</p>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-host">Host (Optional)</Label>
|
||||
<Label htmlFor="custom-domain">
|
||||
Domain <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="custom-host"
|
||||
id="custom-domain"
|
||||
placeholder="shakespeare.wtf"
|
||||
value={customHost}
|
||||
onChange={(e) => setCustomHost(e.target.value)}
|
||||
value={customGateway}
|
||||
onChange={(e) => setCustomGateway(e.target.value)}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Sites get a name under this domain.
|
||||
</p>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-dashboard-host">
|
||||
Gateway API <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="custom-dashboard-host"
|
||||
placeholder="npanel.shakespeare.to"
|
||||
value={customDashboardHost}
|
||||
onChange={(e) => setCustomDashboardHost(e.target.value)}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Where names are claimed. Usually a different host from the one above.
|
||||
</p>
|
||||
</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.ditto.pub"
|
||||
/>
|
||||
</>
|
||||
) : customProviderType === 'nsite' ? (
|
||||
<>
|
||||
|
||||
@@ -3,10 +3,10 @@ import { DeploySettingsContext, type DeploySettings, type DeployProvider } from
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { readDeploySettings, writeDeploySettings } from '@/lib/configUtils';
|
||||
import { DEFAULT_NSITE_PROVIDER } from '@/lib/deployProviderPresets';
|
||||
import { DEFAULT_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
|
||||
|
||||
const DEFAULT_SETTINGS: DeploySettings = {
|
||||
providers: [DEFAULT_NSITE_PROVIDER],
|
||||
providers: [...DEFAULT_DEPLOY_PROVIDERS],
|
||||
};
|
||||
|
||||
export function DeploySettingsProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
@@ -74,10 +74,8 @@ export function ProviderConfigDialog({
|
||||
// Use baseURL from configured provider, falling back to preset baseURL
|
||||
const baseURL = ('baseURL' in localProvider && localProvider.baseURL) || preset?.baseURL;
|
||||
|
||||
// For Shakespeare, special handling for host field
|
||||
const shakespeareUrl = localProvider.type === 'shakespeare' && 'host' in localProvider && localProvider.host
|
||||
? normalizeUrl(localProvider.host)
|
||||
: undefined;
|
||||
// A gateway is recognised by the domain it serves, not by its API origin
|
||||
const gatewayUrl = localProvider.type === 'npanel' ? normalizeUrl(localProvider.domain) : undefined;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
@@ -85,7 +83,7 @@ export function ProviderConfigDialog({
|
||||
<DialogHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<ExternalFavicon
|
||||
url={shakespeareUrl || baseURL}
|
||||
url={gatewayUrl || baseURL}
|
||||
size={20}
|
||||
fallback={<Rocket size={20} />}
|
||||
/>
|
||||
@@ -109,22 +107,55 @@ export function ProviderConfigDialog({
|
||||
/>
|
||||
</div>
|
||||
|
||||
{localProvider.type === 'shakespeare' ? (
|
||||
{localProvider.type === 'npanel' ? (
|
||||
<>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('shakespeareDeployNostrAuth')}
|
||||
</p>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-host">
|
||||
Host (Optional)
|
||||
<Label htmlFor="provider-domain">
|
||||
Domain <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="provider-host"
|
||||
id="provider-domain"
|
||||
placeholder="shakespeare.wtf"
|
||||
value={localProvider.host || ''}
|
||||
onChange={(e) => setLocalProvider({ ...localProvider, host: e.target.value })}
|
||||
value={localProvider.domain}
|
||||
onChange={(e) => setLocalProvider({ ...localProvider, domain: e.target.value })}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Sites get a name under this domain.
|
||||
</p>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-dashboard-host">
|
||||
Gateway API <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Input
|
||||
id="provider-dashboard-host"
|
||||
placeholder="npanel.shakespeare.to"
|
||||
value={localProvider.dashboardHost}
|
||||
onChange={(e) => setLocalProvider({ ...localProvider, dashboardHost: e.target.value })}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Where names are claimed. Usually a different host from the one above.
|
||||
</p>
|
||||
</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.ditto.pub"
|
||||
required
|
||||
/>
|
||||
</>
|
||||
) : localProvider.type === 'nsite' ? (
|
||||
<>
|
||||
|
||||
@@ -20,7 +20,7 @@ import { Link } from 'react-router-dom';
|
||||
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
||||
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
||||
import { PRESET_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
|
||||
import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm';
|
||||
import { NpanelDeployForm } from '@/components/deploy/NpanelDeployForm';
|
||||
import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm';
|
||||
import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
|
||||
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
|
||||
@@ -29,7 +29,7 @@ import { DenoDeployForm } from '@/components/deploy/DenoDeployForm';
|
||||
import { RailwayDeployForm } from '@/components/deploy/RailwayDeployForm';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { DeployAdapter } from '@/lib/deploy/types';
|
||||
import { ShakespeareAdapter } from '@/lib/deploy/ShakespeareAdapter';
|
||||
import { NpanelAdapter } from '@/lib/deploy/NpanelAdapter';
|
||||
import { NsiteAdapter } from '@/lib/deploy/NsiteAdapter';
|
||||
import { NetlifyAdapter } from '@/lib/deploy/NetlifyAdapter';
|
||||
import { VercelAdapter } from '@/lib/deploy/VercelAdapter';
|
||||
@@ -74,12 +74,11 @@ function renderProviderIcon(provider: DeployProvider, preset: PresetDeployProvid
|
||||
// Use baseURL from configured provider, falling back to preset baseURL
|
||||
const baseURL = ('baseURL' in provider && provider.baseURL) || preset?.baseURL;
|
||||
|
||||
// For Shakespeare, special handling for host field
|
||||
const shakespeareUrl = provider.type === 'shakespeare' && 'host' in provider && provider.host
|
||||
? normalizeUrl(provider.host)
|
||||
: undefined;
|
||||
// A gateway is recognised by the domain it serves, not by its API origin —
|
||||
// that is the name the user picked it for and the one with an icon.
|
||||
const gatewayUrl = provider.type === 'npanel' ? normalizeUrl(provider.domain) : undefined;
|
||||
|
||||
const url = shakespeareUrl || baseURL;
|
||||
const url = gatewayUrl || baseURL;
|
||||
|
||||
if (url) {
|
||||
return (
|
||||
@@ -100,8 +99,10 @@ interface DeployStepsProps {
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
interface ShakespeareFormData {
|
||||
interface NpanelFormData {
|
||||
subdomain: string;
|
||||
siteTitle: string;
|
||||
siteDescription: string;
|
||||
}
|
||||
|
||||
interface NsiteFormData {
|
||||
@@ -152,7 +153,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
const [isDeploying, setIsDeploying] = useState(false);
|
||||
const [deployResult, setDeployResult] = useState<{ url: string } | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isShakespeareFormValid, setIsShakespeareFormValid] = useState(true);
|
||||
const [isNpanelFormValid, setIsNpanelFormValid] = 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);
|
||||
@@ -187,8 +188,10 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
}, [fs, projectsPath, projectId]);
|
||||
|
||||
// Provider-specific form data
|
||||
const [shakespeareForm, setShakespeareForm] = useState<ShakespeareFormData>({
|
||||
const [npanelForm, setNpanelForm] = useState<NpanelFormData>({
|
||||
subdomain: projectId,
|
||||
siteTitle: projectName || projectId,
|
||||
siteDescription: '',
|
||||
});
|
||||
const [nsiteForm, setNsiteForm] = useState<NsiteFormData>({
|
||||
siteTitle: '',
|
||||
@@ -245,18 +248,36 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
|
||||
let adapter: DeployAdapter;
|
||||
|
||||
if (selectedProvider.type === 'shakespeare') {
|
||||
if (selectedProvider.type === 'npanel') {
|
||||
if (!user) {
|
||||
throw new Error('You must be logged in with Nostr to use Shakespeare Deploy');
|
||||
throw new Error('You must be logged in with Nostr to deploy here.');
|
||||
}
|
||||
|
||||
const shakespeareProvider = selectedProvider;
|
||||
adapter = new ShakespeareAdapter({
|
||||
const npanelProvider = selectedProvider;
|
||||
const subdomain = npanelForm.subdomain.trim();
|
||||
if (!subdomain) {
|
||||
throw new Error('Choose an address for this site.');
|
||||
}
|
||||
|
||||
const sourceUrl = await resolveNsiteSourceUrl(
|
||||
await git.getRemoteURL(projectPath, 'origin')
|
||||
);
|
||||
|
||||
adapter = new NpanelAdapter({
|
||||
fs,
|
||||
nostr,
|
||||
signer: user.signer,
|
||||
host: shakespeareProvider.host,
|
||||
subdomain: shakespeareForm.subdomain || undefined,
|
||||
corsProxy: shakespeareProvider.proxy ? config.corsProxy : undefined,
|
||||
dashboardHost: npanelProvider.dashboardHost,
|
||||
domain: npanelProvider.domain,
|
||||
subdomain,
|
||||
// The gateway serves the site, so it is also the gateway whose URL the
|
||||
// underlying nsite deploy reports.
|
||||
gateway: npanelProvider.domain,
|
||||
relayUrls: npanelProvider.relayUrls,
|
||||
blossomServers: npanelProvider.blossomServers,
|
||||
siteTitle: npanelForm.siteTitle || undefined,
|
||||
siteDescription: npanelForm.siteDescription || undefined,
|
||||
sourceUrl,
|
||||
});
|
||||
} else if (selectedProvider.type === 'nsite') {
|
||||
const nsiteProvider = selectedProvider;
|
||||
@@ -375,12 +396,14 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
});
|
||||
|
||||
// Save project-specific settings (updateSettings now automatically sets currentProvider)
|
||||
if (selectedProvider.type === 'shakespeare') {
|
||||
if (selectedProvider.type === 'npanel') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'shakespeare',
|
||||
type: 'npanel',
|
||||
url: result.url,
|
||||
data: {
|
||||
subdomain: shakespeareForm.subdomain || undefined,
|
||||
subdomain: npanelForm.subdomain.trim() || undefined,
|
||||
siteTitle: npanelForm.siteTitle || undefined,
|
||||
siteDescription: npanelForm.siteDescription || undefined,
|
||||
},
|
||||
});
|
||||
} else if (selectedProvider.type === 'nsite') {
|
||||
@@ -516,7 +539,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
setDeployResult(null);
|
||||
setError(null);
|
||||
// Reset forms
|
||||
setShakespeareForm({ subdomain: projectId });
|
||||
setNpanelForm({ subdomain: projectId, siteTitle: projectName || projectId, siteDescription: '' });
|
||||
setNsiteForm({ siteTitle: '', siteDescription: '', dTag: '' });
|
||||
setNetlifyForm({ siteId: '', siteName: '' });
|
||||
setVercelForm({ projectName: projectName || projectId, teamId: '' });
|
||||
@@ -528,12 +551,20 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
onClose();
|
||||
};
|
||||
|
||||
const handleShakespeareSubdomainChange = useCallback((subdomain: string) => {
|
||||
setShakespeareForm({ subdomain });
|
||||
const handleNpanelSubdomainChange = useCallback((subdomain: string) => {
|
||||
setNpanelForm(prev => ({ ...prev, subdomain }));
|
||||
}, []);
|
||||
|
||||
const handleShakespeareValidationChange = useCallback((isValid: boolean) => {
|
||||
setIsShakespeareFormValid(isValid);
|
||||
const handleNpanelSiteTitleChange = useCallback((siteTitle: string) => {
|
||||
setNpanelForm(prev => ({ ...prev, siteTitle }));
|
||||
}, []);
|
||||
|
||||
const handleNpanelSiteDescriptionChange = useCallback((siteDescription: string) => {
|
||||
setNpanelForm(prev => ({ ...prev, siteDescription }));
|
||||
}, []);
|
||||
|
||||
const handleNpanelValidationChange = useCallback((isValid: boolean) => {
|
||||
setIsNpanelFormValid(isValid);
|
||||
}, []);
|
||||
|
||||
const handleNsiteSiteTitleChange = useCallback((siteTitle: string) => {
|
||||
@@ -578,18 +609,24 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
const renderProviderFields = () => {
|
||||
if (!selectedProvider) return null;
|
||||
|
||||
if (selectedProvider.type === 'shakespeare') {
|
||||
const shakespeareProvider = selectedProvider;
|
||||
if (selectedProvider.type === 'npanel') {
|
||||
const npanelProvider = selectedProvider;
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const savedSubdomain = savedConfig?.type === 'shakespeare' ? savedConfig.data.subdomain : undefined;
|
||||
const saved = savedConfig?.type === 'npanel' ? savedConfig.data : undefined;
|
||||
|
||||
return (
|
||||
<ShakespeareDeployForm
|
||||
host={shakespeareProvider.host}
|
||||
<NpanelDeployForm
|
||||
dashboardHost={npanelProvider.dashboardHost}
|
||||
domain={npanelProvider.domain}
|
||||
projectId={projectId}
|
||||
savedSubdomain={savedSubdomain}
|
||||
onSubdomainChange={handleShakespeareSubdomainChange}
|
||||
onValidationChange={handleShakespeareValidationChange}
|
||||
projectName={projectName}
|
||||
savedSubdomain={saved?.subdomain}
|
||||
savedSiteTitle={saved?.siteTitle}
|
||||
savedSiteDescription={saved?.siteDescription}
|
||||
onSubdomainChange={handleNpanelSubdomainChange}
|
||||
onSiteTitleChange={handleNpanelSiteTitleChange}
|
||||
onSiteDescriptionChange={handleNpanelSiteDescriptionChange}
|
||||
onValidationChange={handleNpanelValidationChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -906,11 +943,11 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
|
||||
{selectedProvider && renderProviderFields()}
|
||||
|
||||
{selectedProvider?.type === 'shakespeare' && !user && (
|
||||
{selectedProvider?.type === 'npanel' && !user && (
|
||||
<Alert>
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
You must be logged in with Nostr to use Shakespeare Deploy.{' '}
|
||||
You must be logged in with Nostr to publish a site.{' '}
|
||||
<Link
|
||||
to="/settings/nostr"
|
||||
className="underline hover:no-underline"
|
||||
@@ -950,8 +987,8 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
onClick={handleDeploy}
|
||||
disabled={
|
||||
isDeploying ||
|
||||
(selectedProvider.type === 'shakespeare' && !user) ||
|
||||
(selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) ||
|
||||
(selectedProvider.type === 'npanel' && !user) ||
|
||||
(selectedProvider.type === 'npanel' && !isNpanelFormValid) ||
|
||||
(selectedProvider.type === 'nsite' && !user) ||
|
||||
(selectedProvider.type === 'nsite' && !nsiteForm.dTag) ||
|
||||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
import { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import { AlertCircle, Check, Loader2 } from 'lucide-react';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { checkNameAvailable, type NameAvailability } from '@/lib/deploy/NpanelAdapter';
|
||||
|
||||
/** How long typing has to stop before the gateway is asked about a name. */
|
||||
const AVAILABILITY_DEBOUNCE_MS = 400;
|
||||
|
||||
interface NpanelDeployFormProps {
|
||||
/** The gateway's API origin, e.g. `npanel.shakespeare.to`. */
|
||||
dashboardHost: string;
|
||||
/** The domain sites are served under, e.g. `shakespeare.wtf`. */
|
||||
domain: string;
|
||||
/** Falls back to the project id when nothing has been deployed yet. */
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
savedSubdomain?: string;
|
||||
savedSiteTitle?: string;
|
||||
savedSiteDescription?: string;
|
||||
onSubdomainChange: (subdomain: string) => void;
|
||||
onSiteTitleChange: (title: string) => void;
|
||||
onSiteDescriptionChange: (description: string) => void;
|
||||
onValidationChange?: (isValid: boolean) => void;
|
||||
}
|
||||
|
||||
/** What the field is currently saying about the name in it. */
|
||||
type NameState =
|
||||
| { kind: 'empty' }
|
||||
| { kind: 'mine' }
|
||||
| { kind: 'checking' }
|
||||
| { kind: 'free' }
|
||||
| { kind: 'unavailable'; message: string };
|
||||
|
||||
function describe(availability: NameAvailability, domain: string): NameState {
|
||||
if (availability.available) return { kind: 'free' };
|
||||
|
||||
if (availability.reason === 'taken') {
|
||||
return { kind: 'unavailable', message: `That name is taken on ${domain}. Try another.` };
|
||||
}
|
||||
|
||||
return { kind: 'unavailable', message: availability.error ?? 'That name cannot be used.' };
|
||||
}
|
||||
|
||||
export function NpanelDeployForm({
|
||||
dashboardHost,
|
||||
domain,
|
||||
projectId,
|
||||
projectName,
|
||||
savedSubdomain,
|
||||
savedSiteTitle,
|
||||
savedSiteDescription,
|
||||
onSubdomainChange,
|
||||
onSiteTitleChange,
|
||||
onSiteDescriptionChange,
|
||||
onValidationChange,
|
||||
}: NpanelDeployFormProps) {
|
||||
const [subdomain, setSubdomain] = useState(savedSubdomain || projectId);
|
||||
const [siteTitle, setSiteTitle] = useState(savedSiteTitle ?? projectName);
|
||||
const [siteDescription, setSiteDescription] = useState(savedSiteDescription ?? '');
|
||||
const [nameState, setNameState] = useState<NameState>({ kind: 'empty' });
|
||||
|
||||
// Keyed by provider id in DeploySteps, so this runs once with fresh props.
|
||||
const initializedRef = useRef(false);
|
||||
const syncToParent = useCallback(() => {
|
||||
if (initializedRef.current) return;
|
||||
initializedRef.current = true;
|
||||
|
||||
onSubdomainChange(savedSubdomain || projectId);
|
||||
onSiteTitleChange(savedSiteTitle ?? projectName);
|
||||
if (savedSiteDescription) onSiteDescriptionChange(savedSiteDescription);
|
||||
}, [
|
||||
savedSubdomain,
|
||||
savedSiteTitle,
|
||||
savedSiteDescription,
|
||||
projectId,
|
||||
projectName,
|
||||
onSubdomainChange,
|
||||
onSiteTitleChange,
|
||||
onSiteDescriptionChange,
|
||||
]);
|
||||
|
||||
useEffect(() => {
|
||||
syncToParent();
|
||||
}, [syncToParent]);
|
||||
|
||||
// The name this project already deployed to is not "taken" — it is theirs,
|
||||
// and asking the gateway would truthfully say taken and alarm them about
|
||||
// their own site.
|
||||
const isOwnName = Boolean(savedSubdomain) && subdomain === savedSubdomain;
|
||||
|
||||
useEffect(() => {
|
||||
const trimmed = subdomain.trim();
|
||||
|
||||
if (!trimmed) {
|
||||
setNameState({ kind: 'empty' });
|
||||
return;
|
||||
}
|
||||
if (isOwnName) {
|
||||
setNameState({ kind: 'mine' });
|
||||
return;
|
||||
}
|
||||
|
||||
setNameState({ kind: 'checking' });
|
||||
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(async () => {
|
||||
const availability = await checkNameAvailable(
|
||||
dashboardHost,
|
||||
`${trimmed}.${domain}`,
|
||||
controller.signal,
|
||||
);
|
||||
if (!controller.signal.aborted) setNameState(describe(availability, domain));
|
||||
}, AVAILABILITY_DEBOUNCE_MS);
|
||||
|
||||
return () => {
|
||||
controller.abort();
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [subdomain, isOwnName, dashboardHost, domain]);
|
||||
|
||||
// A name still being checked stays deployable: the gateway decides for real
|
||||
// when the deploy runs, and blocking the button on an in-flight request would
|
||||
// make the form feel stuck on a slow connection.
|
||||
const isValid = subdomain.trim() !== '' && nameState.kind !== 'unavailable';
|
||||
|
||||
useEffect(() => {
|
||||
onValidationChange?.(isValid);
|
||||
}, [isValid, onValidationChange]);
|
||||
|
||||
const handleSubdomainChange = (value: string) => {
|
||||
setSubdomain(value);
|
||||
onSubdomainChange(value);
|
||||
};
|
||||
|
||||
const handleSiteTitleChange = (value: string) => {
|
||||
setSiteTitle(value);
|
||||
onSiteTitleChange(value);
|
||||
};
|
||||
|
||||
const handleSiteDescriptionChange = (value: string) => {
|
||||
setSiteDescription(value);
|
||||
onSiteDescriptionChange(value);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="npanel-subdomain">Address</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
id="npanel-subdomain"
|
||||
value={subdomain}
|
||||
onChange={(e) => handleSubdomainChange(e.target.value)}
|
||||
placeholder={projectId}
|
||||
className={nameState.kind === 'unavailable' ? 'border-destructive' : ''}
|
||||
/>
|
||||
<span className="text-sm text-muted-foreground font-mono whitespace-nowrap">
|
||||
.{domain}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{nameState.kind === 'checking' && (
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
<span>Checking availability…</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{nameState.kind === 'free' && (
|
||||
<div className="flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<Check className="h-3 w-3" />
|
||||
<span>
|
||||
<span className="font-mono">{subdomain.trim()}.{domain}</span> is available.
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{nameState.kind === 'mine' && (
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Updating <span className="font-mono">{subdomain.trim()}.{domain}</span>.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{nameState.kind === 'unavailable' && (
|
||||
<div className="flex items-start gap-2 text-sm text-destructive">
|
||||
<AlertCircle className="h-4 w-4 mt-0.5 flex-shrink-0" />
|
||||
<span>{nameState.message}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="npanel-title">Site Title</Label>
|
||||
<Input
|
||||
id="npanel-title"
|
||||
value={siteTitle}
|
||||
onChange={(e) => handleSiteTitleChange(e.target.value)}
|
||||
placeholder="My Nostr Site"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="npanel-description">
|
||||
Description <span className="text-muted-foreground font-normal">(optional)</span>
|
||||
</Label>
|
||||
<Textarea
|
||||
id="npanel-description"
|
||||
value={siteDescription}
|
||||
onChange={(e) => handleSiteDescriptionChange(e.target.value)}
|
||||
placeholder="A short description of this site…"
|
||||
rows={3}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { AlertCircle } from 'lucide-react';
|
||||
|
||||
interface ShakespeareDeployFormProps {
|
||||
host?: string;
|
||||
projectId: string;
|
||||
savedSubdomain?: string;
|
||||
onSubdomainChange: (subdomain: string) => void;
|
||||
onValidationChange?: (isValid: boolean) => void;
|
||||
}
|
||||
|
||||
export function ShakespeareDeployForm({
|
||||
host = 'shakespeare.wtf',
|
||||
projectId,
|
||||
savedSubdomain,
|
||||
onSubdomainChange,
|
||||
onValidationChange,
|
||||
}: ShakespeareDeployFormProps) {
|
||||
const [subdomain, setSubdomain] = useState(savedSubdomain || projectId);
|
||||
|
||||
// Update subdomain when savedSubdomain changes (e.g., when switching providers)
|
||||
useEffect(() => {
|
||||
setSubdomain(savedSubdomain || projectId);
|
||||
}, [savedSubdomain, projectId]);
|
||||
|
||||
// Validate subdomain: no periods allowed (only single-level subdomains)
|
||||
const hasPeriod = subdomain.includes('.');
|
||||
const isValid = subdomain.trim() !== '' && !hasPeriod;
|
||||
|
||||
useEffect(() => {
|
||||
onSubdomainChange(subdomain);
|
||||
}, [subdomain, onSubdomainChange]);
|
||||
|
||||
useEffect(() => {
|
||||
onValidationChange?.(isValid);
|
||||
}, [isValid, onValidationChange]);
|
||||
|
||||
const fullDomain = subdomain ? `${subdomain}.${host}` : `${projectId}.${host}`;
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="shakespeare-subdomain">Subdomain</Label>
|
||||
<Input
|
||||
id="shakespeare-subdomain"
|
||||
value={subdomain}
|
||||
onChange={(e) => setSubdomain(e.target.value)}
|
||||
placeholder={projectId}
|
||||
className={hasPeriod ? 'border-destructive' : ''}
|
||||
/>
|
||||
{hasPeriod && (
|
||||
<div className="flex items-start gap-2 text-sm text-destructive">
|
||||
<AlertCircle className="h-4 w-4 mt-0.5 flex-shrink-0" />
|
||||
<span>Subdomain cannot contain periods. Use hyphens instead (e.g., "nostr-radar").</span>
|
||||
</div>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Will deploy to: <span className="font-mono">{fullDomain}</span>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -5,10 +5,20 @@ export interface BaseDeployProvider {
|
||||
name: string;
|
||||
}
|
||||
|
||||
export interface ShakespeareDeployProvider extends BaseDeployProvider {
|
||||
type: 'shakespeare';
|
||||
host?: string;
|
||||
proxy?: boolean;
|
||||
/**
|
||||
* A gateway that serves nsites under a domain it hands out names on.
|
||||
*
|
||||
* The site is an ordinary nsite under the user's own key; what the gateway adds
|
||||
* is the hostname, which it has to be asked for. `dashboardHost` is where that
|
||||
* asking happens and `domain` is what the site is served under — usually two
|
||||
* different names, and never assumed to be the same one.
|
||||
*/
|
||||
export interface NpanelProvider extends BaseDeployProvider {
|
||||
type: 'npanel';
|
||||
dashboardHost: string;
|
||||
domain: string;
|
||||
relayUrls: string[];
|
||||
blossomServers: string[];
|
||||
}
|
||||
|
||||
export interface NetlifyProvider extends BaseDeployProvider {
|
||||
@@ -57,7 +67,7 @@ export interface RailwayProvider extends BaseDeployProvider {
|
||||
proxy?: boolean;
|
||||
}
|
||||
|
||||
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider | RailwayProvider;
|
||||
export type DeployProvider = NpanelProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider | RailwayProvider;
|
||||
|
||||
export interface DeploySettings {
|
||||
providers: DeployProvider[];
|
||||
|
||||
@@ -3,11 +3,14 @@ import { z } from 'zod';
|
||||
import { useFS } from './useFS';
|
||||
import { useFSPaths } from './useFSPaths';
|
||||
|
||||
const shakespeareProjectConfigSchema = z.object({
|
||||
type: z.literal('shakespeare'),
|
||||
const npanelProjectConfigSchema = z.object({
|
||||
type: z.literal('npanel'),
|
||||
url: z.string(),
|
||||
data: z.object({
|
||||
/** The single label in front of the gateway's domain. */
|
||||
subdomain: z.string().optional(),
|
||||
siteTitle: z.string().optional(),
|
||||
siteDescription: z.string().optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -71,7 +74,7 @@ const railwayProjectConfigSchema = z.object({
|
||||
});
|
||||
|
||||
const projectProviderConfigSchema = z.discriminatedUnion('type', [
|
||||
shakespeareProjectConfigSchema,
|
||||
npanelProjectConfigSchema,
|
||||
nsiteProjectConfigSchema,
|
||||
netlifyProjectConfigSchema,
|
||||
vercelProjectConfigSchema,
|
||||
@@ -85,7 +88,7 @@ const projectDeploySettingsSchema = z.object({
|
||||
currentProvider: z.string().optional(),
|
||||
});
|
||||
|
||||
export type ShakespeareProjectConfig = z.infer<typeof shakespeareProjectConfigSchema>;
|
||||
export type NpanelProjectConfig = z.infer<typeof npanelProjectConfigSchema>;
|
||||
export type NsiteProjectConfig = z.infer<typeof nsiteProjectConfigSchema>;
|
||||
export type NetlifyProjectConfig = z.infer<typeof netlifyProjectConfigSchema>;
|
||||
export type VercelProjectConfig = z.infer<typeof vercelProjectConfigSchema>;
|
||||
@@ -95,6 +98,24 @@ export type RailwayProjectConfig = z.infer<typeof railwayProjectConfigSchema>;
|
||||
export type ProjectProviderConfig = z.infer<typeof projectProviderConfigSchema>;
|
||||
export type ProjectDeploySettings = z.infer<typeof projectDeploySettingsSchema>;
|
||||
|
||||
/**
|
||||
* Bring a record written by an older version up to date.
|
||||
*
|
||||
* `shakespeare` deploys became `npanel` ones against the same domain, and the
|
||||
* subdomain carries straight over. Worth doing rather than letting the schema
|
||||
* reject it: this file holds one record per provider a project has ever
|
||||
* deployed to, so a single unparseable entry would take a Netlify site id and a
|
||||
* Vercel project id down with it.
|
||||
*/
|
||||
function migrateProjectProviderConfig(config: unknown): unknown {
|
||||
if (typeof config !== 'object' || config === null) return config;
|
||||
|
||||
const candidate = config as Record<string, unknown>;
|
||||
if (candidate.type !== 'shakespeare') return config;
|
||||
|
||||
return { ...candidate, type: 'npanel' };
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to manage project-specific deployment settings
|
||||
* Stores settings in .git/shakespeare/deploy.json
|
||||
@@ -118,10 +139,20 @@ export function useProjectDeploySettings(projectId: string | null) {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const content = await fs.fs.readFile(settingsPath, 'utf8');
|
||||
const parsed = JSON.parse(content as string);
|
||||
const parsed = JSON.parse(content as string) as { providers?: Record<string, unknown> };
|
||||
|
||||
const migrated = {
|
||||
...parsed,
|
||||
providers: Object.fromEntries(
|
||||
Object.entries(parsed?.providers ?? {}).map(([id, config]) => [
|
||||
id,
|
||||
migrateProjectProviderConfig(config),
|
||||
]),
|
||||
),
|
||||
};
|
||||
|
||||
// Validate with Zod
|
||||
const validated = projectDeploySettingsSchema.parse(parsed);
|
||||
const validated = projectDeploySettingsSchema.parse(migrated);
|
||||
setSettings(validated);
|
||||
} catch (error) {
|
||||
// File doesn't exist, is invalid JSON, or doesn't match schema - use empty settings
|
||||
|
||||
@@ -11,6 +11,7 @@ import type { JSRuntimeFS } from './JSRuntime';
|
||||
import type { AISettings } from '@/contexts/AISettingsContext';
|
||||
import type { GitSettings } from '@/contexts/GitSettingsContext';
|
||||
import type { DeploySettings } from '@/contexts/DeploySettingsContext';
|
||||
import { DEFAULT_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
|
||||
|
||||
// Mock filesystem
|
||||
const createMockFS = (): JSRuntimeFS => ({
|
||||
@@ -278,7 +279,11 @@ describe('configUtils', () => {
|
||||
{
|
||||
id: 'provider-3',
|
||||
name: 'Shakespeare',
|
||||
type: 'shakespeare',
|
||||
type: 'npanel',
|
||||
dashboardHost: 'npanel.shakespeare.to',
|
||||
domain: 'shakespeare.wtf',
|
||||
relayUrls: ['wss://relay.ditto.pub'],
|
||||
blossomServers: ['https://blossom.ditto.pub'],
|
||||
},
|
||||
{
|
||||
id: 'provider-4',
|
||||
@@ -300,13 +305,38 @@ describe('configUtils', () => {
|
||||
expect(result).toEqual(sampleDeploySettings);
|
||||
});
|
||||
|
||||
it('should return default settings if file does not exist', async () => {
|
||||
it('should offer the default provider when no settings have been saved', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
|
||||
|
||||
const result = await readDeploySettings(mockFS);
|
||||
|
||||
expect(result).toEqual({
|
||||
providers: [],
|
||||
expect(result).toEqual({ providers: DEFAULT_DEPLOY_PROVIDERS });
|
||||
});
|
||||
|
||||
it('should keep nothing when a saved file cannot be read', async () => {
|
||||
// Distinct from having no file at all: handing back the defaults here
|
||||
// would quietly replace whatever the user had configured.
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue('{"providers": "not an array"}');
|
||||
|
||||
const result = await readDeploySettings(mockFS);
|
||||
|
||||
expect(result).toEqual({ providers: [] });
|
||||
});
|
||||
|
||||
it('should migrate a provider saved before the gateway existed', async () => {
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(
|
||||
JSON.stringify({
|
||||
providers: [{ id: 'shakespeare', name: 'Shakespeare Deploy', type: 'shakespeare', host: 'shakespeare.wtf' }],
|
||||
}),
|
||||
);
|
||||
|
||||
const result = await readDeploySettings(mockFS);
|
||||
|
||||
expect(result.providers).toHaveLength(1);
|
||||
expect(result.providers[0]).toMatchObject({
|
||||
id: 'shakespeare',
|
||||
type: 'npanel',
|
||||
domain: 'shakespeare.wtf',
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+36
-12
@@ -1,6 +1,7 @@
|
||||
import z from 'zod';
|
||||
import { filteredArray } from '@/lib/schema';
|
||||
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
|
||||
import { DEFAULT_DEPLOY_PROVIDERS, migrateDeployProvider } from '@/lib/deployProviderPresets';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import type { AISettings, MCPServer } from '@/contexts/AISettingsContext';
|
||||
import type { GitSettings, GitCredential } from '@/contexts/GitSettingsContext';
|
||||
@@ -90,9 +91,12 @@ const baseDeployProviderSchema = z.object({
|
||||
proxy: z.boolean().optional(),
|
||||
});
|
||||
|
||||
const shakespeareDeployProviderSchema = baseDeployProviderSchema.extend({
|
||||
type: z.literal('shakespeare'),
|
||||
host: z.string().optional(),
|
||||
const npanelProviderSchema = baseDeployProviderSchema.extend({
|
||||
type: z.literal('npanel'),
|
||||
dashboardHost: z.string(),
|
||||
domain: z.string(),
|
||||
relayUrls: z.array(z.string()),
|
||||
blossomServers: z.array(z.string()),
|
||||
});
|
||||
|
||||
const netlifyProviderSchema = baseDeployProviderSchema.extend({
|
||||
@@ -137,7 +141,7 @@ const railwayProviderSchema = baseDeployProviderSchema.extend({
|
||||
});
|
||||
|
||||
const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('type', [
|
||||
shakespeareDeployProviderSchema,
|
||||
npanelProviderSchema,
|
||||
netlifyProviderSchema,
|
||||
vercelProviderSchema,
|
||||
nsiteProviderSchema,
|
||||
@@ -314,24 +318,44 @@ export async function writeGitSettings(fs: JSRuntimeFS, settings: GitSettings, c
|
||||
|
||||
/**
|
||||
* Read Deploy settings from VFS
|
||||
*
|
||||
* A user with no settings file is not the same as a user who removed every
|
||||
* provider, and the difference is what a new user sees the first time they open
|
||||
* the deploy button: the default gateway, or an empty screen asking them to
|
||||
* choose a host. Both used to answer "no providers", so the default had never
|
||||
* actually reached anybody — it was written, saved back as an empty list on the
|
||||
* next render, and gone.
|
||||
*
|
||||
* @param fs - Filesystem instance
|
||||
* @param configPath - Custom config path (default: /config)
|
||||
*/
|
||||
export async function readDeploySettings(fs: JSRuntimeFS, configPath = '/config'): Promise<DeploySettings> {
|
||||
const defaultSettings: DeploySettings = {
|
||||
providers: [],
|
||||
};
|
||||
const deployConfigPath = getDeployConfigPath(configPath);
|
||||
|
||||
let content: string;
|
||||
try {
|
||||
content = await fs.readFile(deployConfigPath, 'utf8');
|
||||
} catch {
|
||||
// A copy, so the caller editing its providers can't reach back into the
|
||||
// module-level defaults every other caller will be handed.
|
||||
return { providers: [...DEFAULT_DEPLOY_PROVIDERS] };
|
||||
}
|
||||
|
||||
try {
|
||||
const deployConfigPath = getDeployConfigPath(configPath);
|
||||
const content = await fs.readFile(deployConfigPath, 'utf8');
|
||||
const data = JSON.parse(content);
|
||||
return deploySettingsSchema.parse(data);
|
||||
const data = JSON.parse(content) as { providers?: unknown };
|
||||
const migrated = {
|
||||
...data,
|
||||
providers: Array.isArray(data?.providers) ? data.providers.map(migrateDeployProvider) : data?.providers,
|
||||
};
|
||||
return deploySettingsSchema.parse(migrated);
|
||||
} catch (error) {
|
||||
// A file that exists and cannot be read is a different problem from one that
|
||||
// isn't there: handing back the defaults would silently replace whatever the
|
||||
// user had, so this keeps nothing rather than inventing something.
|
||||
if (error instanceof z.ZodError) {
|
||||
console.error('Deploy settings parsing error:', error.issues);
|
||||
}
|
||||
return defaultSettings;
|
||||
return { providers: [] };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,225 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { generateSecretKey, getPublicKey } from 'nostr-tools';
|
||||
import type { NostrEvent, NostrSigner } from '@nostrify/nostrify';
|
||||
import { NpanelAdapter, checkNameAvailable } from './NpanelAdapter';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
|
||||
const DASHBOARD_HOST = 'npanel.example.test';
|
||||
const DOMAIN = 'example.test';
|
||||
|
||||
const secretKey = generateSecretKey();
|
||||
const pubkey = getPublicKey(secretKey);
|
||||
|
||||
/**
|
||||
* A signer that fills in the fields a real one would, without signing.
|
||||
*
|
||||
* Not a shortcut around something worth testing: the adapter never verifies a
|
||||
* signature, it base64-encodes whatever it is handed, so what these tests are
|
||||
* about is which tags end up on the event and where it gets sent. Signing for
|
||||
* real is also not available here — jsdom's TextEncoder returns a Uint8Array
|
||||
* from its own realm, which fails the `instanceof` check inside @noble/hashes,
|
||||
* so nostr-tools cannot hash an event under this test environment at all.
|
||||
*/
|
||||
const signer: NostrSigner = {
|
||||
getPublicKey: async () => pubkey,
|
||||
signEvent: async (template) => ({
|
||||
...template,
|
||||
id: 'f'.repeat(64),
|
||||
pubkey,
|
||||
sig: '0'.repeat(128),
|
||||
}),
|
||||
} as NostrSigner;
|
||||
|
||||
/** Requests the adapter made, so a test can assert what it asked the gateway. */
|
||||
interface Call {
|
||||
method: string;
|
||||
path: string;
|
||||
body?: unknown;
|
||||
auth: NostrEvent;
|
||||
}
|
||||
|
||||
let calls: Call[] = [];
|
||||
let fetchMock: ReturnType<typeof vi.fn>;
|
||||
|
||||
/**
|
||||
* An adapter whose nsite half is stubbed out.
|
||||
*
|
||||
* Publishing the site is {@link NsiteAdapter}'s job and is covered where it
|
||||
* lives; what is worth pinning down here is the second half — which requests
|
||||
* the gateway gets, and what happens when it says no.
|
||||
*/
|
||||
function adapterWithStubbedSite(subdomain: string): NpanelAdapter {
|
||||
const adapter = new NpanelAdapter({
|
||||
fs: {} as JSRuntimeFS,
|
||||
nostr: {} as never,
|
||||
signer,
|
||||
dashboardHost: DASHBOARD_HOST,
|
||||
domain: DOMAIN,
|
||||
subdomain,
|
||||
gateway: DOMAIN,
|
||||
relayUrls: [],
|
||||
blossomServers: [],
|
||||
});
|
||||
|
||||
const inner = (adapter as unknown as { nsite: { deploy: unknown } }).nsite;
|
||||
inner.deploy = vi.fn(async () => ({
|
||||
url: `https://base36.${DOMAIN}`,
|
||||
metadata: { canonicalUrl: `https://base36.${DOMAIN}`, filesPublished: 3 },
|
||||
}));
|
||||
|
||||
return adapter;
|
||||
}
|
||||
|
||||
/** Respond to the adapter's requests in the order it makes them. */
|
||||
function respondWith(...responses: Array<{ status: number; body?: unknown }>): void {
|
||||
let index = 0;
|
||||
|
||||
fetchMock.mockImplementation(async (request: Request) => {
|
||||
const header = request.headers.get('Authorization') ?? '';
|
||||
const auth = JSON.parse(atob(header.replace(/^Nostr /, ''))) as NostrEvent;
|
||||
const body = request.body ? await request.clone().json() : undefined;
|
||||
|
||||
calls.push({ method: request.method, path: new URL(request.url).pathname, body, auth });
|
||||
|
||||
const next = responses[index++] ?? { status: 500 };
|
||||
return new Response(next.body === undefined ? null : JSON.stringify(next.body), {
|
||||
status: next.status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
calls = [];
|
||||
fetchMock = vi.fn();
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe('NpanelAdapter', () => {
|
||||
it('claims an unused name and returns the hostname it got', async () => {
|
||||
respondWith({ status: 404, body: { error: 'Host not found.' } }, { status: 201, body: { host: {} } });
|
||||
|
||||
const result = await adapterWithStubbedSite('mysite').deploy({
|
||||
projectId: 'p',
|
||||
projectPath: '/projects/p',
|
||||
});
|
||||
|
||||
expect(result.url).toBe(`https://mysite.${DOMAIN}`);
|
||||
expect(calls.map((c) => `${c.method} ${c.path}`)).toEqual([
|
||||
`GET /api/hosts/mysite.${DOMAIN}`,
|
||||
'POST /api/hosts',
|
||||
]);
|
||||
|
||||
// The site is served from a manifest that may not have every path, so the
|
||||
// gateway has to be told to fall back to the shell rather than 404.
|
||||
expect(calls[1].body).toMatchObject({
|
||||
hostname: `mysite.${DOMAIN}`,
|
||||
address: `35128:${pubkey}:mysite`,
|
||||
spa: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('signs each request for the URL it is sent to', async () => {
|
||||
respondWith({ status: 404 }, { status: 201, body: { host: {} } });
|
||||
|
||||
await adapterWithStubbedSite('mysite').deploy({ projectId: 'p', projectPath: '/projects/p' });
|
||||
|
||||
for (const call of calls) {
|
||||
const tag = (name: string) => call.auth.tags.find(([k]) => k === name)?.[1];
|
||||
|
||||
expect(call.auth.kind).toBe(27235);
|
||||
expect(call.auth.pubkey).toBe(pubkey);
|
||||
expect(tag('method')).toBe(call.method);
|
||||
expect(tag('u')).toBe(`https://${DASHBOARD_HOST}${call.path}`);
|
||||
}
|
||||
});
|
||||
|
||||
it('leaves a name alone when it already points at this site', async () => {
|
||||
respondWith({
|
||||
status: 200,
|
||||
body: { host: { address: `35128:${pubkey}:mysite` } },
|
||||
});
|
||||
|
||||
await adapterWithStubbedSite('mysite').deploy({ projectId: 'p', projectPath: '/projects/p' });
|
||||
|
||||
// A redeploy is the common case; it should cost one read and no write.
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0].method).toBe('GET');
|
||||
});
|
||||
|
||||
it('repoints a name it holds that points somewhere else', async () => {
|
||||
respondWith(
|
||||
{ status: 200, body: { host: { address: '35128:someoneelse:mysite' } } },
|
||||
{ status: 200, body: { host: {} } },
|
||||
);
|
||||
|
||||
await adapterWithStubbedSite('mysite').deploy({ projectId: 'p', projectPath: '/projects/p' });
|
||||
|
||||
expect(calls[1].method).toBe('PATCH');
|
||||
expect(calls[1].body).toEqual({ address: `35128:${pubkey}:mysite` });
|
||||
});
|
||||
|
||||
it('says plainly when a name belongs to someone else', async () => {
|
||||
respondWith({ status: 403, body: { error: "You don't have access to this host." } });
|
||||
|
||||
await expect(
|
||||
adapterWithStubbedSite('taken').deploy({ projectId: 'p', projectPath: '/projects/p' }),
|
||||
).rejects.toThrow(/belongs to someone else/);
|
||||
});
|
||||
|
||||
it('says plainly when a name is claimed between the check and the claim', async () => {
|
||||
respondWith({ status: 404 }, { status: 409, body: { error: 'already configured.' } });
|
||||
|
||||
await expect(
|
||||
adapterWithStubbedSite('racy').deploy({ projectId: 'p', projectPath: '/projects/p' }),
|
||||
).rejects.toThrow(/was just taken/);
|
||||
});
|
||||
|
||||
it("passes on the gateway's own explanation of a refusal", async () => {
|
||||
respondWith(
|
||||
{ status: 404 },
|
||||
{ status: 403, body: { error: 'You already have 25 sites here, which is the limit.' } },
|
||||
);
|
||||
|
||||
await expect(
|
||||
adapterWithStubbedSite('over-quota').deploy({ projectId: 'p', projectPath: '/projects/p' }),
|
||||
).rejects.toThrow(/25 sites here/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkNameAvailable', () => {
|
||||
it('reports what the gateway says', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(JSON.stringify({ hostname: `x.${DOMAIN}`, available: false, reason: 'taken' })),
|
||||
);
|
||||
|
||||
await expect(checkNameAvailable(DASHBOARD_HOST, `x.${DOMAIN}`)).resolves.toMatchObject({
|
||||
available: false,
|
||||
reason: 'taken',
|
||||
});
|
||||
});
|
||||
|
||||
it('asks without credentials', async () => {
|
||||
fetchMock.mockResolvedValue(new Response(JSON.stringify({ hostname: 'x', available: true })));
|
||||
|
||||
await checkNameAvailable(DASHBOARD_HOST, `x.${DOMAIN}`);
|
||||
|
||||
const [url, init] = fetchMock.mock.calls[0];
|
||||
expect(String(url)).toBe(`https://${DASHBOARD_HOST}/api/hosts/x.${DOMAIN}/available`);
|
||||
expect((init as RequestInit | undefined)?.headers).toBeUndefined();
|
||||
});
|
||||
|
||||
it('treats an unreachable gateway as available', async () => {
|
||||
// Being wrong this way costs a clear error at deploy time. Being wrong the
|
||||
// other way tells somebody a free name is taken and they settle for worse.
|
||||
fetchMock.mockRejectedValue(new Error('offline'));
|
||||
|
||||
await expect(checkNameAvailable(DASHBOARD_HOST, `x.${DOMAIN}`)).resolves.toMatchObject({
|
||||
available: true,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,182 @@
|
||||
import { NIP98 } from '@nostrify/nostrify';
|
||||
import { N64 } from '@nostrify/nostrify/utils';
|
||||
import type { NostrSigner } from '@nostrify/nostrify';
|
||||
import type { DeployAdapter, DeployOptions, DeployResult, NpanelDeployConfig } from './types';
|
||||
import { NsiteAdapter } from './NsiteAdapter';
|
||||
|
||||
/** nsite named-site kind. An npanel host always points at one of these. */
|
||||
const NAMED_SITE_KIND = 35128;
|
||||
|
||||
/** Timeout for a single API call (ms). */
|
||||
const FETCH_TIMEOUT_MS = 15_000;
|
||||
|
||||
/** What `GET /api/hosts/:hostname/available` answers. */
|
||||
export interface NameAvailability {
|
||||
hostname: string;
|
||||
available: boolean;
|
||||
reason?: 'taken' | 'invalid';
|
||||
/** Present when `reason` is `invalid`; written to be shown to whoever typed it. */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask whether a name can still be claimed.
|
||||
*
|
||||
* Unauthenticated, and deliberately so: someone choosing a name has not decided
|
||||
* to make an account yet, and making them prove who they are to find out their
|
||||
* first choice is taken would be a strange order to do things in.
|
||||
*
|
||||
* A network failure answers `available: true` rather than blocking the person.
|
||||
* Being wrong that way costs a clear error at deploy time; being wrong the other
|
||||
* way tells someone a free name is taken and they pick a worse one.
|
||||
*/
|
||||
export async function checkNameAvailable(
|
||||
dashboardHost: string,
|
||||
hostname: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<NameAvailability> {
|
||||
const url = `https://${dashboardHost}/api/hosts/${encodeURIComponent(hostname)}/available`;
|
||||
|
||||
try {
|
||||
const response = await fetch(url, { signal: signal ?? AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
if (!response.ok) return { hostname, available: true };
|
||||
return (await response.json()) as NameAvailability;
|
||||
} catch {
|
||||
return { hostname, available: true };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deploy to an npanel gateway: publish an nsite, then point a hostname at it.
|
||||
*
|
||||
* The site itself is an ordinary nsite published under the user's own key — this
|
||||
* adapter delegates all of that to {@link NsiteAdapter} rather than reimplementing
|
||||
* it, so a site deployed here is the same site, readable by any nsite client,
|
||||
* with or without this gateway.
|
||||
*
|
||||
* What npanel adds is the name. Its predecessor claimed one implicitly, by
|
||||
* watching relays for a manifest and reserving whatever `d` tag it saw first;
|
||||
* npanel instead keeps an explicit hostname → nsite row, which is what makes a
|
||||
* name something its owner holds rather than something they won a race for.
|
||||
* That row has to be asked for, which is the second half of this deploy.
|
||||
*/
|
||||
export class NpanelAdapter implements DeployAdapter {
|
||||
private readonly nsite: NsiteAdapter;
|
||||
private readonly signer: NostrSigner;
|
||||
private readonly dashboardHost: string;
|
||||
private readonly hostname: string;
|
||||
private readonly subdomain: string;
|
||||
|
||||
constructor(config: NpanelDeployConfig) {
|
||||
this.signer = config.signer;
|
||||
this.dashboardHost = config.dashboardHost;
|
||||
this.subdomain = config.subdomain;
|
||||
this.hostname = `${config.subdomain}.${config.domain}`;
|
||||
|
||||
// The identifier is the subdomain, so a site's name and its address agree
|
||||
// and a second gateway asked to serve it lands on the same name.
|
||||
this.nsite = new NsiteAdapter({ ...config, siteIdentifier: config.subdomain });
|
||||
}
|
||||
|
||||
async deploy(options: DeployOptions): Promise<DeployResult> {
|
||||
const result = await this.nsite.deploy(options);
|
||||
|
||||
const pubkey = await this.signer.getPublicKey();
|
||||
const address = `${NAMED_SITE_KIND}:${pubkey}:${this.subdomain}`;
|
||||
|
||||
await this.bindHostname(address);
|
||||
|
||||
return {
|
||||
url: `https://${this.hostname}`,
|
||||
metadata: {
|
||||
...result.metadata,
|
||||
provider: 'npanel',
|
||||
hostname: this.hostname,
|
||||
address,
|
||||
/** The URL any nsite gateway serves this at, gateway or no gateway. */
|
||||
canonicalUrl: result.metadata?.canonicalUrl ?? result.url,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Point {@link hostname} at `address`, whether or not it already exists.
|
||||
*
|
||||
* Asked about before being claimed, because the three outcomes are different
|
||||
* acts: a name nobody holds is created, a name this user already holds is
|
||||
* repointed — that is what a redeploy under a new key or a renamed site looks
|
||||
* like — and a name somebody else holds is refused. Creating first and reading
|
||||
* the 409 could not tell the last two apart.
|
||||
*/
|
||||
private async bindHostname(address: string): Promise<void> {
|
||||
const existing = await this.request('GET', `/api/hosts/${encodeURIComponent(this.hostname)}`);
|
||||
|
||||
if (existing.status === 200) {
|
||||
const { host } = (await existing.json()) as { host: { address: string } };
|
||||
if (host.address === address) return;
|
||||
|
||||
const patched = await this.request(
|
||||
'PATCH',
|
||||
`/api/hosts/${encodeURIComponent(this.hostname)}`,
|
||||
{ address },
|
||||
);
|
||||
if (!patched.ok) throw await this.error(patched, `Could not update ${this.hostname}`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (existing.status === 403) {
|
||||
throw new Error(
|
||||
`${this.hostname} belongs to someone else. Choose a different name for this site.`,
|
||||
);
|
||||
}
|
||||
|
||||
if (existing.status !== 404) {
|
||||
throw await this.error(existing, `Could not check whether ${this.hostname} is free`);
|
||||
}
|
||||
|
||||
const created = await this.request('POST', '/api/hosts', { hostname: this.hostname, address, spa: true });
|
||||
if (created.ok) return;
|
||||
|
||||
// Between the check and the claim, somebody else took it.
|
||||
if (created.status === 409) {
|
||||
throw new Error(`${this.hostname} was just taken. Choose a different name for this site.`);
|
||||
}
|
||||
|
||||
throw await this.error(created, `Could not claim ${this.hostname}`);
|
||||
}
|
||||
|
||||
/** A NIP-98 request to the gateway's API. */
|
||||
private async request(method: string, path: string, body?: unknown): Promise<Response> {
|
||||
const url = `https://${this.dashboardHost}${path}`;
|
||||
|
||||
let request = new Request(url, {
|
||||
method,
|
||||
...(body === undefined
|
||||
? {}
|
||||
: { body: JSON.stringify(body), headers: { 'Content-Type': 'application/json' } }),
|
||||
});
|
||||
|
||||
// Signed against the URL being requested, so the token authorizes this call
|
||||
// and no other. No CORS proxy: npanel answers browsers directly, and a proxy
|
||||
// would rewrite the URL out from under the signature.
|
||||
const template = await NIP98.template(request);
|
||||
const event = await this.signer.signEvent(template);
|
||||
|
||||
const headers = new Headers(request.headers);
|
||||
headers.set('Authorization', `Nostr ${N64.encodeEvent(event)}`);
|
||||
request = new Request(request, { headers, signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
|
||||
return await fetch(request);
|
||||
}
|
||||
|
||||
/** The gateway's own sentence about a failure, which is written to be read. */
|
||||
private async error(response: Response, fallback: string): Promise<Error> {
|
||||
const body = await response.json().catch(() => null) as { error?: string } | null;
|
||||
|
||||
if (response.status === 403 && !body?.error) {
|
||||
return new Error(`${fallback}: this gateway is not accepting new sites right now.`);
|
||||
}
|
||||
|
||||
return new Error(body?.error ?? `${fallback} (HTTP ${response.status}).`);
|
||||
}
|
||||
}
|
||||
@@ -1,122 +0,0 @@
|
||||
import JSZip from 'jszip';
|
||||
import { NIP98 } from '@nostrify/nostrify';
|
||||
import { N64 } from '@nostrify/nostrify/utils';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
import type { DeployAdapter, DeployOptions, DeployResult, ShakespeareDeployConfig } from './types';
|
||||
import { proxyUrl } from '../proxyUrl';
|
||||
|
||||
/**
|
||||
* Shakespeare Deploy Adapter
|
||||
* Uses NIP-98 authentication with Nostr signer
|
||||
*/
|
||||
export class ShakespeareAdapter implements DeployAdapter {
|
||||
private fs: JSRuntimeFS;
|
||||
private signer: ShakespeareDeployConfig['signer'];
|
||||
private host: string;
|
||||
private subdomain?: string;
|
||||
private corsProxy?: string;
|
||||
|
||||
constructor(config: ShakespeareDeployConfig) {
|
||||
this.fs = config.fs;
|
||||
this.signer = config.signer;
|
||||
this.host = config.host || 'shakespeare.wtf';
|
||||
this.subdomain = config.subdomain;
|
||||
this.corsProxy = config.corsProxy;
|
||||
}
|
||||
|
||||
async deploy(options: DeployOptions): Promise<DeployResult> {
|
||||
const { projectId, projectPath } = options;
|
||||
|
||||
// Use custom subdomain if provided, otherwise construct from projectId
|
||||
const hostname = this.subdomain
|
||||
? `${this.subdomain}.${this.host}`
|
||||
: `${projectId}.${this.host}`;
|
||||
const deployUrl = `https://${this.host}/deploy`;
|
||||
const siteUrl = `https://${hostname}`;
|
||||
|
||||
// Check if dist directory exists and contains index.html
|
||||
const distPath = `${projectPath}/dist`;
|
||||
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.');
|
||||
}
|
||||
|
||||
// Create ZIP of dist directory
|
||||
const zip = new JSZip();
|
||||
await this.addDirectoryToZip(distPath, zip);
|
||||
|
||||
// Generate ZIP blob
|
||||
const zipBlob = await zip.generateAsync({ type: 'blob' });
|
||||
|
||||
// Create FormData
|
||||
const formData = new FormData();
|
||||
formData.append('hostname', hostname);
|
||||
formData.append('file', zipBlob, `${projectId}.zip`);
|
||||
|
||||
// Create the request
|
||||
let request = new Request(deployUrl, {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
});
|
||||
|
||||
// Create NIP-98 token for authentication
|
||||
const template = await NIP98.template(request);
|
||||
const event = await this.signer.signEvent(template);
|
||||
const token = N64.encodeEvent(event);
|
||||
|
||||
// Add the Authorization header
|
||||
const headers = new Headers(request.headers);
|
||||
headers.set('Authorization', `Nostr ${token}`);
|
||||
request = new Request(request, { headers });
|
||||
|
||||
// Apply proxy if configured
|
||||
if (this.corsProxy) {
|
||||
request = new Request(proxyUrl({ template: this.corsProxy, url: request.url }), request);
|
||||
}
|
||||
|
||||
// Deploy
|
||||
const response = await fetch(request);
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text().catch(() => 'Unknown error');
|
||||
throw new Error(`Deployment failed: ${response.status} ${response.statusText}. ${errorText}`);
|
||||
}
|
||||
|
||||
return {
|
||||
url: siteUrl,
|
||||
metadata: {
|
||||
hostname,
|
||||
provider: 'shakespeare',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
private async addDirectoryToZip(dirPath: string, zip: JSZip): Promise<void> {
|
||||
try {
|
||||
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullPath = `${dirPath}/${entry.name}`;
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
// Create folder in zip and recursively add its contents
|
||||
const folder = zip.folder(entry.name);
|
||||
if (folder) {
|
||||
await this.addDirectoryToZip(fullPath, folder);
|
||||
}
|
||||
} else if (entry.isFile()) {
|
||||
// Add file to zip
|
||||
try {
|
||||
const fileContent = await this.fs.readFile(fullPath);
|
||||
zip.file(entry.name, fileContent);
|
||||
} catch {
|
||||
console.warn(`Failed to read file ${fullPath}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
console.warn(`Failed to read directory ${dirPath}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
export * from './types';
|
||||
export * from './ShakespeareAdapter';
|
||||
export * from './NpanelAdapter';
|
||||
export * from './NetlifyAdapter';
|
||||
export * from './VercelAdapter';
|
||||
export * from './NsiteAdapter';
|
||||
|
||||
+21
-9
@@ -20,14 +20,6 @@ export interface DeployAdapter {
|
||||
deploy(options: DeployOptions): Promise<DeployResult>;
|
||||
}
|
||||
|
||||
export interface ShakespeareDeployConfig {
|
||||
fs: JSRuntimeFS;
|
||||
signer: NostrSigner;
|
||||
host?: string;
|
||||
subdomain?: string;
|
||||
corsProxy?: string;
|
||||
}
|
||||
|
||||
export interface NetlifyDeployConfig {
|
||||
fs: JSRuntimeFS;
|
||||
apiKey: string;
|
||||
@@ -68,6 +60,26 @@ export interface NsiteDeployConfig {
|
||||
siteIdentifier?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A gateway that serves an nsite under a name it holds for you.
|
||||
*
|
||||
* `siteIdentifier` is not configurable: the gateway's hostname and the site's
|
||||
* `d` tag are the same label, so that a second gateway asked to serve the site
|
||||
* lands on the same name.
|
||||
*/
|
||||
export interface NpanelDeployConfig extends Omit<NsiteDeployConfig, 'siteIdentifier'> {
|
||||
/**
|
||||
* The gateway's dashboard hostname, which is also its API origin — the `u`
|
||||
* tag of every NIP-98 request has to name it, so it is not interchangeable
|
||||
* with the domain sites are served under.
|
||||
*/
|
||||
dashboardHost: string;
|
||||
/** The domain the site is served under, e.g. `shakespeare.wtf`. */
|
||||
domain: string;
|
||||
/** The single label in front of {@link domain}, and the site's `d` tag. */
|
||||
subdomain: string;
|
||||
}
|
||||
|
||||
export interface CloudflareDeployConfig {
|
||||
fs: JSRuntimeFS;
|
||||
apiKey: string;
|
||||
@@ -103,7 +115,7 @@ export interface RailwayDeployConfig {
|
||||
|
||||
export interface PresetDeployProvider {
|
||||
id: string;
|
||||
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway';
|
||||
type: 'npanel' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway';
|
||||
name: string;
|
||||
description: string;
|
||||
baseURL?: string;
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { DEFAULT_NPANEL_PROVIDER, migrateDeployProvider } from './deployProviderPresets';
|
||||
|
||||
describe('migrateDeployProvider', () => {
|
||||
it('turns a Shakespeare Deploy provider into a gateway on the same domain', () => {
|
||||
// That host serves those same names out of nsite manifests now, so the
|
||||
// deploy button keeps working and lands where it always did.
|
||||
const migrated = migrateDeployProvider({
|
||||
id: 'shakespeare',
|
||||
name: 'Shakespeare Deploy',
|
||||
type: 'shakespeare',
|
||||
host: 'shakespeare.wtf',
|
||||
});
|
||||
|
||||
expect(migrated).toMatchObject({
|
||||
id: 'shakespeare',
|
||||
name: 'Shakespeare Deploy',
|
||||
type: 'npanel',
|
||||
domain: 'shakespeare.wtf',
|
||||
dashboardHost: DEFAULT_NPANEL_PROVIDER.dashboardHost,
|
||||
});
|
||||
});
|
||||
|
||||
it('keeps the provider id, so a project still finds its saved deployment', () => {
|
||||
const migrated = migrateDeployProvider({ id: 'custom-123', name: 'Mine', type: 'shakespeare' });
|
||||
|
||||
expect(migrated).toMatchObject({ id: 'custom-123', name: 'Mine' });
|
||||
});
|
||||
|
||||
it('assumes the default domain when none was saved', () => {
|
||||
// `host` was optional and the adapter defaulted it, so an entry without one
|
||||
// was never pointing at nothing.
|
||||
expect(migrateDeployProvider({ id: 'shakespeare', name: 'Shakespeare', type: 'shakespeare' }))
|
||||
.toMatchObject({ domain: 'shakespeare.wtf' });
|
||||
});
|
||||
|
||||
it('leaves every other provider exactly as it found it', () => {
|
||||
const netlify = { id: 'netlify', name: 'Netlify', type: 'netlify', apiKey: 'token' };
|
||||
|
||||
expect(migrateDeployProvider(netlify)).toBe(netlify);
|
||||
});
|
||||
|
||||
it('passes through anything that is not a provider at all', () => {
|
||||
// It runs over whatever is in the file, which may be nothing of the sort.
|
||||
expect(migrateDeployProvider(null)).toBe(null);
|
||||
expect(migrateDeployProvider('nonsense')).toBe('nonsense');
|
||||
});
|
||||
});
|
||||
@@ -1,33 +1,86 @@
|
||||
import type { NsiteProvider } from '@/contexts/DeploySettingsContext';
|
||||
import type { DeployProvider, NpanelProvider, NsiteProvider } from '@/contexts/DeploySettingsContext';
|
||||
import type { PresetDeployProvider } from './deploy/types';
|
||||
|
||||
/** Default nsite provider configuration, pre-configured for new users. */
|
||||
const DEFAULT_RELAYS = [
|
||||
'wss://relay.ditto.pub',
|
||||
'wss://relay.dreamith.to',
|
||||
'wss://relay.nsite.lol',
|
||||
'wss://relay.nosto.re',
|
||||
'wss://relay.primal.net',
|
||||
];
|
||||
|
||||
const DEFAULT_BLOSSOM_SERVERS = [
|
||||
'https://blossom.ditto.pub',
|
||||
'https://blossom.dreamith.to',
|
||||
'https://blossom.primal.net',
|
||||
'https://cdn.sovbit.host',
|
||||
];
|
||||
|
||||
/**
|
||||
* Shakespeare's own gateway, which every new user starts with.
|
||||
*
|
||||
* It serves an ordinary nsite — the site is published under the user's key and
|
||||
* readable without this gateway — and adds a name under `shakespeare.wtf`.
|
||||
*/
|
||||
export const DEFAULT_NPANEL_PROVIDER: NpanelProvider = {
|
||||
id: 'npanel',
|
||||
name: 'Shakespeare',
|
||||
type: 'npanel',
|
||||
dashboardHost: 'npanel.shakespeare.to',
|
||||
domain: 'shakespeare.wtf',
|
||||
relayUrls: DEFAULT_RELAYS,
|
||||
blossomServers: DEFAULT_BLOSSOM_SERVERS,
|
||||
};
|
||||
|
||||
/** Plain nsite, for publishing without any gateway holding a name for you. */
|
||||
export const DEFAULT_NSITE_PROVIDER: NsiteProvider = {
|
||||
id: 'nsite',
|
||||
name: 'nsite',
|
||||
type: 'nsite',
|
||||
gateway: 'shakespeare.to',
|
||||
relayUrls: [
|
||||
'wss://relay.ditto.pub',
|
||||
'wss://relay.dreamith.to',
|
||||
'wss://relay.nsite.lol',
|
||||
'wss://relay.nosto.re',
|
||||
'wss://relay.primal.net',
|
||||
],
|
||||
blossomServers: [
|
||||
'https://blossom.ditto.pub',
|
||||
'https://blossom.dreamith.to',
|
||||
'https://blossom.primal.net',
|
||||
'https://cdn.sovbit.host',
|
||||
],
|
||||
relayUrls: DEFAULT_RELAYS,
|
||||
blossomServers: DEFAULT_BLOSSOM_SERVERS,
|
||||
};
|
||||
|
||||
/** What a user who has never opened the deploy settings gets. */
|
||||
export const DEFAULT_DEPLOY_PROVIDERS: DeployProvider[] = [DEFAULT_NPANEL_PROVIDER];
|
||||
|
||||
/**
|
||||
* Bring a provider saved by an older version up to date.
|
||||
*
|
||||
* `shakespeare` was a zip upload to a host that kept the files itself. That host
|
||||
* now serves those same domains out of nsite manifests, so the type it maps to
|
||||
* is the gateway one — same domain, same name, and the deploy button keeps
|
||||
* working without anyone being asked to reconfigure anything.
|
||||
*
|
||||
* Returns the provider unchanged when there is nothing to do, so this is safe to
|
||||
* run over every provider on every load.
|
||||
*/
|
||||
export function migrateDeployProvider(provider: unknown): unknown {
|
||||
if (typeof provider !== 'object' || provider === null) return provider;
|
||||
|
||||
const candidate = provider as Record<string, unknown>;
|
||||
if (candidate.type !== 'shakespeare') return provider;
|
||||
|
||||
const host = typeof candidate.host === 'string' && candidate.host ? candidate.host : 'shakespeare.wtf';
|
||||
|
||||
return {
|
||||
id: typeof candidate.id === 'string' ? candidate.id : DEFAULT_NPANEL_PROVIDER.id,
|
||||
name: typeof candidate.name === 'string' ? candidate.name : DEFAULT_NPANEL_PROVIDER.name,
|
||||
type: 'npanel',
|
||||
dashboardHost: DEFAULT_NPANEL_PROVIDER.dashboardHost,
|
||||
domain: host,
|
||||
relayUrls: DEFAULT_RELAYS,
|
||||
blossomServers: DEFAULT_BLOSSOM_SERVERS,
|
||||
};
|
||||
}
|
||||
|
||||
export const PRESET_DEPLOY_PROVIDERS: PresetDeployProvider[] = [
|
||||
{
|
||||
id: 'shakespeare',
|
||||
type: 'shakespeare',
|
||||
name: 'Shakespeare Deploy',
|
||||
description: 'Deploy to Shakespeare hosting with Nostr authentication',
|
||||
id: 'npanel',
|
||||
type: 'npanel',
|
||||
name: 'Shakespeare',
|
||||
description: 'Publish to Nostr and get a shakespeare.wtf address',
|
||||
baseURL: 'https://shakespeare.diy',
|
||||
requiresNostr: true,
|
||||
},
|
||||
|
||||
@@ -9,7 +9,7 @@ import { useVercelOAuth } from '@/hooks/useVercelOAuth';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
||||
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
||||
import { PRESET_DEPLOY_PROVIDERS, DEFAULT_NSITE_PROVIDER } from '@/lib/deployProviderPresets';
|
||||
import { PRESET_DEPLOY_PROVIDERS, DEFAULT_NPANEL_PROVIDER, DEFAULT_NSITE_PROVIDER } from '@/lib/deployProviderPresets';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { ProviderConfigDialog } from '@/components/ProviderConfigDialog';
|
||||
import { AddDeployProviderDialog } from '@/components/AddDeployProviderDialog';
|
||||
@@ -182,25 +182,20 @@ export function DeploySettings() {
|
||||
};
|
||||
|
||||
const handleAddPresetProvider = (preset: PresetDeployProvider, apiKey: string, accountId?: string, organizationId?: string) => {
|
||||
// For Shakespeare, just check if user is logged in
|
||||
// Nostr-authenticated providers need a login rather than a key
|
||||
if (preset.requiresNostr && !user) {
|
||||
return;
|
||||
}
|
||||
|
||||
// For non-Shakespeare/non-nsite providers, require API key
|
||||
// Everything else is reached with an API key, except plain nsite
|
||||
if (!preset.requiresNostr && preset.type !== 'nsite' && !apiKey?.trim()) {
|
||||
return;
|
||||
}
|
||||
|
||||
let newProvider: DeployProvider;
|
||||
|
||||
if (preset.type === 'shakespeare') {
|
||||
newProvider = {
|
||||
id: preset.id, // Use preset ID for presets
|
||||
name: preset.name,
|
||||
type: 'shakespeare',
|
||||
...(preset.proxy && { proxy: true }),
|
||||
};
|
||||
if (preset.type === 'npanel') {
|
||||
newProvider = { ...DEFAULT_NPANEL_PROVIDER, id: preset.id, name: preset.name };
|
||||
} else if (preset.type === 'nsite') {
|
||||
newProvider = { ...DEFAULT_NSITE_PROVIDER };
|
||||
} else if (preset.type === 'netlify') {
|
||||
|
||||
Reference in new issue
Block a user