Implement new relay handler, rough out relay list/detail
This commit is contained in:
@@ -0,0 +1,2 @@
|
||||
CREATE UNIQUE INDEX IF NOT EXISTS relays_subdomain_unique
|
||||
ON relays (subdomain);
|
||||
+28
-3
@@ -76,6 +76,19 @@ fn not_found() -> Response {
|
||||
(StatusCode::NOT_FOUND, Json(ApiError { error: "not found".into() })).into_response()
|
||||
}
|
||||
|
||||
fn is_unique_subdomain_violation(err: &anyhow::Error) -> bool {
|
||||
let Some(sqlx_err) = err.downcast_ref::<sqlx::Error>() else {
|
||||
return false;
|
||||
};
|
||||
|
||||
let sqlx::Error::Database(db_err) = sqlx_err else {
|
||||
return false;
|
||||
};
|
||||
|
||||
db_err.message().contains("relays.subdomain")
|
||||
|| db_err.message().contains("relays_subdomain_unique")
|
||||
}
|
||||
|
||||
fn extract_auth_pubkey(headers: &HeaderMap, method: &Method, uri: &Uri) -> Result<String> {
|
||||
let auth_header = headers
|
||||
.get(axum::http::header::AUTHORIZATION)
|
||||
@@ -189,7 +202,11 @@ async fn create_tenant_relay(
|
||||
status: "pending".to_string(),
|
||||
};
|
||||
|
||||
if let Err(_) = state.repo.create_relay(&relay).await {
|
||||
if let Err(err) = state.repo.create_relay(&relay).await {
|
||||
if is_unique_subdomain_violation(&err) {
|
||||
return (StatusCode::CONFLICT, Json(ApiError { error: "subdomain already exists".into() })).into_response();
|
||||
}
|
||||
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiError { error: "failed to create relay".into() })).into_response();
|
||||
}
|
||||
|
||||
@@ -261,7 +278,11 @@ async fn update_tenant_relay(
|
||||
status: existing.status,
|
||||
};
|
||||
|
||||
if let Err(_) = state.repo.update_relay(&updated).await {
|
||||
if let Err(err) = state.repo.update_relay(&updated).await {
|
||||
if is_unique_subdomain_violation(&err) {
|
||||
return (StatusCode::CONFLICT, Json(ApiError { error: "subdomain already exists".into() })).into_response();
|
||||
}
|
||||
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiError { error: "failed to update relay".into() })).into_response();
|
||||
}
|
||||
|
||||
@@ -535,7 +556,11 @@ async fn admin_update_relay(
|
||||
status: existing.status,
|
||||
};
|
||||
|
||||
if let Err(_) = state.repo.update_relay(&updated).await {
|
||||
if let Err(err) = state.repo.update_relay(&updated).await {
|
||||
if is_unique_subdomain_violation(&err) {
|
||||
return (StatusCode::CONFLICT, Json(ApiError { error: "subdomain already exists".into() })).into_response();
|
||||
}
|
||||
|
||||
return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiError { error: "failed to update relay".into() })).into_response();
|
||||
}
|
||||
|
||||
|
||||
@@ -54,7 +54,7 @@ impl Provisioner {
|
||||
if !res.status().is_success() {
|
||||
let status = res.status();
|
||||
let body = res.text().await.unwrap_or_default();
|
||||
return Err(anyhow!("zooid provisioning failed: {} {}", status, body));
|
||||
return Err(anyhow!("zooid provisioning failed for {}: {} {}", url, status, body));
|
||||
}
|
||||
|
||||
Ok(())
|
||||
|
||||
@@ -80,7 +80,6 @@ Super admin dashboard:
|
||||
## Todos
|
||||
|
||||
- [ ] Marketing page (`/`) with value props, features, and CTA
|
||||
- [ ] Login page (`/login`) via nonboard
|
||||
- [ ] Tenant dashboard auth via NIP-98
|
||||
- [ ] Relays list (`/relays`) with search/filter and add relay CTA
|
||||
- [ ] Relay detail (`/relays/:id`) with edit + deactivate actions
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
import { accounts, API_URL } from "./nostr"
|
||||
|
||||
type NostrTag = string[]
|
||||
|
||||
type UnsignedEvent = {
|
||||
kind: number
|
||||
content: string
|
||||
created_at: number
|
||||
tags: NostrTag[]
|
||||
}
|
||||
|
||||
type SignedEvent = UnsignedEvent & {
|
||||
id: string
|
||||
pubkey: string
|
||||
sig: string
|
||||
}
|
||||
|
||||
type EventSigner = {
|
||||
signEvent(event: UnsignedEvent): Promise<SignedEvent>
|
||||
}
|
||||
|
||||
export class ApiError extends Error {
|
||||
status: number
|
||||
|
||||
constructor(message: string, status: number) {
|
||||
super(message)
|
||||
this.name = "ApiError"
|
||||
this.status = status
|
||||
}
|
||||
}
|
||||
|
||||
function getActiveSigner(): EventSigner {
|
||||
const account = accounts.getActive() as { signer?: EventSigner } | undefined
|
||||
if (!account?.signer) throw new Error("Not logged in")
|
||||
return account.signer
|
||||
}
|
||||
|
||||
async function createNip98Header(url: string, method: string): Promise<string> {
|
||||
const signer = getActiveSigner()
|
||||
const event = await signer.signEvent({
|
||||
kind: 27235,
|
||||
content: "",
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
tags: [
|
||||
["u", url],
|
||||
["method", method.toUpperCase()],
|
||||
],
|
||||
})
|
||||
|
||||
const encoded = btoa(JSON.stringify(event))
|
||||
return `Nostr ${encoded}`
|
||||
}
|
||||
|
||||
async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||
const method = (init?.method ?? "GET").toUpperCase()
|
||||
const url = new URL(path, API_URL).toString()
|
||||
const auth = await createNip98Header(url, method)
|
||||
|
||||
const response = await fetch(url, {
|
||||
...init,
|
||||
method,
|
||||
headers: {
|
||||
...(init?.headers ?? {}),
|
||||
Authorization: auth,
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
let message = `Request failed (${response.status})`
|
||||
try {
|
||||
const body = await response.json() as { error?: string }
|
||||
if (body.error) message = body.error
|
||||
} catch {
|
||||
// ignored
|
||||
}
|
||||
throw new ApiError(message, response.status)
|
||||
}
|
||||
|
||||
if (response.status === 204) {
|
||||
return undefined as T
|
||||
}
|
||||
|
||||
return response.json() as Promise<T>
|
||||
}
|
||||
|
||||
export type Relay = {
|
||||
id: string
|
||||
tenant: string
|
||||
name: string
|
||||
subdomain: string
|
||||
schema: string
|
||||
icon: string
|
||||
description: string
|
||||
plan: string
|
||||
status: string
|
||||
}
|
||||
|
||||
export function listTenantRelays() {
|
||||
return request<Relay[]>("/tenant/relays")
|
||||
}
|
||||
|
||||
export type CreateRelayInput = {
|
||||
name: string
|
||||
subdomain: string
|
||||
icon: string
|
||||
description: string
|
||||
plan: string
|
||||
}
|
||||
|
||||
export function createTenantRelay(input: CreateRelayInput) {
|
||||
return request<Relay>("/tenant/relays", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(input),
|
||||
})
|
||||
}
|
||||
|
||||
export function getTenantRelay(id: string) {
|
||||
return request<Relay>(`/tenant/relays/${id}`)
|
||||
}
|
||||
@@ -29,8 +29,8 @@ export function restoreAccounts() {
|
||||
try {
|
||||
const saved = JSON.parse(raw) as SerializedAccount[]
|
||||
accounts.fromJSON(saved, true)
|
||||
} catch (error) {
|
||||
console.warn("Failed to restore accounts", error)
|
||||
} catch {
|
||||
// ignore corrupted local state
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -68,7 +68,6 @@ export default function Login() {
|
||||
try {
|
||||
await completeLogin(await ExtensionAccount.fromExtension())
|
||||
} catch (e) {
|
||||
console.error("NIP-07 login failed", e)
|
||||
setError(e instanceof Error ? e.message : "Failed to login with extension")
|
||||
} finally {
|
||||
setLoading(false)
|
||||
|
||||
@@ -1,14 +1,37 @@
|
||||
import { useParams, A } from "@solidjs/router"
|
||||
import { createResource, Show } from "solid-js"
|
||||
import { getTenantRelay } from "../../lib/api"
|
||||
|
||||
export default function RelayDetail() {
|
||||
const params = useParams()
|
||||
const [relay] = createResource(() => params.id, getTenantRelay)
|
||||
|
||||
return (
|
||||
<div class="max-w-4xl mx-auto px-4 py-8">
|
||||
<div class="flex items-center gap-2 mb-6">
|
||||
<A href="/relays" class="text-gray-500 hover:text-gray-700">← Relays</A>
|
||||
</div>
|
||||
<h1 class="text-2xl font-bold text-gray-900 mb-4">Relay {params.id}</h1>
|
||||
|
||||
<Show when={relay.loading}>
|
||||
<p class="text-gray-500 mb-4">Loading relay...</p>
|
||||
</Show>
|
||||
|
||||
<Show when={relay.error && !relay.loading}>
|
||||
<p class="text-red-600 mb-4">Failed to load relay.</p>
|
||||
</Show>
|
||||
|
||||
<Show when={relay()}>
|
||||
{(loadedRelay) => (
|
||||
<div class="mb-6">
|
||||
<h1 class="text-2xl font-bold text-gray-900">{loadedRelay().name}</h1>
|
||||
<p class="mt-1 text-sm text-gray-500">https://{loadedRelay().subdomain}.spaces.coracle.social</p>
|
||||
<Show when={loadedRelay().description.trim()}>
|
||||
<p class="mt-3 text-gray-700">{loadedRelay().description}</p>
|
||||
</Show>
|
||||
</div>
|
||||
)}
|
||||
</Show>
|
||||
|
||||
<div class="flex gap-3">
|
||||
<A
|
||||
href={`/relays/${params.id}/edit`}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
import { A } from "@solidjs/router"
|
||||
import { createResource, For, Show } from "solid-js"
|
||||
import { listTenantRelays } from "../../lib/api"
|
||||
|
||||
export default function RelayList() {
|
||||
const [relays] = createResource(listTenantRelays)
|
||||
|
||||
return (
|
||||
<div class="max-w-4xl mx-auto px-4 py-8">
|
||||
<div class="flex items-center justify-between mb-6">
|
||||
@@ -12,7 +16,37 @@ export default function RelayList() {
|
||||
Add Relay
|
||||
</A>
|
||||
</div>
|
||||
<p class="text-gray-500">No relays yet. Create one to get started.</p>
|
||||
|
||||
<Show when={relays.loading}>
|
||||
<p class="text-gray-500">Loading relays...</p>
|
||||
</Show>
|
||||
|
||||
<Show when={relays.error && !relays.loading}>
|
||||
<p class="text-red-600">Failed to load relays.</p>
|
||||
</Show>
|
||||
|
||||
<Show when={(relays()?.length ?? 0) > 0} fallback={<p class="text-gray-500">No relays yet. Create one to get started.</p>}>
|
||||
<ul class="space-y-3">
|
||||
<For each={relays()}>
|
||||
{(relay) => (
|
||||
<li>
|
||||
<A
|
||||
href={`/relays/${relay.id}`}
|
||||
class="block rounded-lg border border-gray-200 bg-white p-4 hover:border-gray-300"
|
||||
>
|
||||
<div class="flex items-center justify-between">
|
||||
<div>
|
||||
<p class="font-medium text-gray-900">{relay.name}</p>
|
||||
<p class="text-sm text-gray-500">{relay.subdomain}</p>
|
||||
</div>
|
||||
<p class="text-xs uppercase tracking-wide text-gray-500">{relay.status}</p>
|
||||
</div>
|
||||
</A>
|
||||
</li>
|
||||
)}
|
||||
</For>
|
||||
</ul>
|
||||
</Show>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { createSignal } from "solid-js"
|
||||
import { useNavigate } from "@solidjs/router"
|
||||
import { createTenantRelay, listTenantRelays } from "../../lib/api"
|
||||
|
||||
const PLANS = [
|
||||
{ id: "free", label: "Free", price: 0, members: "Up to 10", blossom: false, livekit: false },
|
||||
@@ -26,22 +27,54 @@ export default function RelayNew() {
|
||||
const [icon, setIcon] = createSignal("")
|
||||
const [description, setDescription] = createSignal("")
|
||||
const [plan, setPlan] = createSignal<PlanId>("free")
|
||||
const [submitting, setSubmitting] = createSignal(false)
|
||||
const [error, setError] = createSignal("")
|
||||
|
||||
function handleNameInput(value: string) {
|
||||
setName(value)
|
||||
setSubdomain(slugify(value))
|
||||
}
|
||||
|
||||
function handleSubmit(e: Event) {
|
||||
async function handleSubmit(e: Event) {
|
||||
e.preventDefault()
|
||||
// TODO: submit to backend, handle invoice flow
|
||||
navigate("/relays")
|
||||
|
||||
setError("")
|
||||
setSubmitting(true)
|
||||
|
||||
try {
|
||||
const normalizedSubdomain = slugify(subdomain())
|
||||
const existingRelays = await listTenantRelays()
|
||||
const hasDuplicate = existingRelays.some(relay => relay.subdomain.toLowerCase() === normalizedSubdomain.toLowerCase())
|
||||
|
||||
if (hasDuplicate) {
|
||||
throw new Error("You already have a relay with this subdomain")
|
||||
}
|
||||
|
||||
const relay = await createTenantRelay({
|
||||
name: name().trim(),
|
||||
subdomain: normalizedSubdomain,
|
||||
icon: icon().trim(),
|
||||
description: description().trim(),
|
||||
plan: plan(),
|
||||
})
|
||||
navigate(`/relays/${relay.id}`)
|
||||
} catch (e) {
|
||||
setError(e instanceof Error ? e.message : "Failed to create relay")
|
||||
} finally {
|
||||
setSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div class="max-w-2xl mx-auto px-4 py-8">
|
||||
<h1 class="text-2xl font-bold text-gray-900 mb-6">New Relay</h1>
|
||||
<form onSubmit={handleSubmit} class="space-y-6">
|
||||
{error() && (
|
||||
<div class="rounded-lg border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
|
||||
{error()}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div>
|
||||
<label class="block text-sm font-medium text-gray-700 mb-1">Relay Name</label>
|
||||
<input
|
||||
@@ -118,9 +151,10 @@ export default function RelayNew() {
|
||||
|
||||
<button
|
||||
type="submit"
|
||||
disabled={submitting()}
|
||||
class="w-full py-3 bg-blue-600 text-white font-semibold rounded-lg hover:bg-blue-700 transition-colors"
|
||||
>
|
||||
Create Relay
|
||||
{submitting() ? "Creating..." : "Create Relay"}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
Reference in New Issue
Block a user