feat(amy): nsite/napplet serve (local preview); drop standalone publish.sh

Add `amy nsite serve` and `amy napplet serve <author> [--d ID] [--port N]`:
fetch the manifest and serve its content over a local HTTP server, resolving
each request through quartz StaticSiteResolver (blob downloaded from Blossom
and sha256-verified per request, same as the device host) with SPA fallback to
index.html. Lets you open a published site/napplet in a browser to confirm it
loads and routes. (Static content only — a napplet's window.napplet.* runtime
still needs the Amethyst host; documented in the command + harness README.)

Implemented as thin cli glue (StaticSiteServe) over the resolver + commons
BlossomClient + the JDK HTTP server.

Also retire tools/napplet-test/publish.sh now that `amy napplet publish` is the
single source of truth; the harness README documents publish + serve via amy.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016ncMHuBBVHEf7spAoSssde
This commit is contained in:
Claude
2026-06-22 15:35:14 +00:00
parent ece1f43975
commit 7bc95d836c
5 changed files with 209 additions and 129 deletions
@@ -57,13 +57,50 @@ object NappletCommands {
route(
"napplet",
tail,
"napplet <fetch|publish> …",
"napplet <fetch|publish|serve> …",
mapOf(
"fetch" to { rest -> fetch(dataDir, rest) },
"publish" to { rest -> publish(dataDir, rest) },
"serve" to { rest -> serve(dataDir, rest) },
),
)
/**
* `amy napplet serve <author> [--d ID] [--port N]` — fetch + aggregate-verify the manifest and
* serve its static content over a local HTTP server. NOTE: the napplet's window.napplet.* runtime
* needs the Amethyst host; this serves the files only, for inspecting that they load/route.
*/
private suspend fun serve(
dataDir: DataDir,
rest: Array<String>,
): Int {
val args = Args(rest)
val author = args.positionalOrNull(0) ?: return Output.error("bad_args", "napplet serve <author> [--d ID] [--port N] [--server S] [--relay R]")
val identifier = args.flag("d")
val port = args.intFlag("port", 8080)
val extraServers = StaticSiteFetch.commaList(args.flag("server"))
val extraRelays = StaticSiteFetch.commaList(args.flag("relay"))
val timeoutSecs = args.longFlag("timeout", 8L)
Context.open(dataDir).use { ctx ->
ctx.prepare()
val authorHex = ctx.requireUserHex(author)
val relays =
extraRelays
.mapNotNull { RelayUrlNormalizer.normalizeOrNull(it) }
.toSet()
.ifEmpty { ctx.bootstrapRelays() }
val event =
fetchByAuthor(ctx, authorHex, identifier, relays, timeoutSecs * 1000)
?: return Output.error("not_found", "no napplet manifest found", mapOf("pubkey" to authorHex, "d" to identifier))
val manifest = event as NappletManifest
if (!manifest.verifyAggregate()) {
return Output.error("aggregate_mismatch", "manifest x aggregate does not match its path tags")
}
return StaticSiteServe.serve(manifest.paths(), (manifest.servers() + extraServers).distinct(), port)
}
}
/**
* `amy napplet publish <dir> --server <blossom> [--requires identity,relay,…] [--d ID] [--relay …]`
* — upload a napplet directory to Blossom and broadcast its NIP-5D manifest (kind 15129 root, or
@@ -57,13 +57,49 @@ object NsiteCommands {
route(
"nsite",
tail,
"nsite <fetch|publish> …",
"nsite <fetch|publish|serve> …",
mapOf(
"fetch" to { rest -> fetch(dataDir, rest) },
"publish" to { rest -> publish(dataDir, rest) },
"serve" to { rest -> serve(dataDir, rest) },
),
)
/**
* `amy nsite serve <author> [--d ID] [--port N]` — fetch the manifest and serve it over a local
* HTTP server (sha256-verified per request) so you can open it in a browser.
*/
private suspend fun serve(
dataDir: DataDir,
rest: Array<String>,
): Int {
val args = Args(rest)
val author = args.positionalOrNull(0) ?: return Output.error("bad_args", "nsite serve <author> [--d ID] [--port N] [--server S] [--relay R]")
val identifier = args.flag("d")
val port = args.intFlag("port", 8080)
val extraServers = StaticSiteFetch.commaList(args.flag("server"))
val extraRelays = StaticSiteFetch.commaList(args.flag("relay"))
val timeoutSecs = args.longFlag("timeout", 8L)
Context.open(dataDir).use { ctx ->
ctx.prepare()
val authorHex = ctx.requireUserHex(author)
val relays =
extraRelays
.mapNotNull { RelayUrlNormalizer.normalizeOrNull(it) }
.toSet()
.ifEmpty { ctx.bootstrapRelays() }
val manifest =
fetchManifest(ctx, authorHex, identifier, relays, timeoutSecs * 1000)
?: return Output.error(
"not_found",
"no static-website manifest for this author",
mapOf("pubkey" to authorHex, "d" to identifier),
)
return StaticSiteServe.serve(manifest.paths, (manifest.servers + extraServers).distinct(), port)
}
}
/**
* `amy nsite publish <dir> --server <blossom> [--d ID] [--relay …] [--title …]` — upload a static
* site directory to Blossom and broadcast its NIP-5A manifest (kind 15128 root, or 35128 named
@@ -0,0 +1,115 @@
/*
* Copyright (c) 2025 Vitor Pamplona
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
* Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.vitorpamplona.amethyst.cli.commands
import com.sun.net.httpserver.HttpExchange
import com.sun.net.httpserver.HttpServer
import com.vitorpamplona.amethyst.cli.Output
import com.vitorpamplona.amethyst.commons.service.upload.BlossomClient
import com.vitorpamplona.quartz.nip5aStaticWebsites.resolver.StaticSiteResolution
import com.vitorpamplona.quartz.nip5aStaticWebsites.resolver.StaticSiteResolver
import com.vitorpamplona.quartz.nip5aStaticWebsites.tags.PathTag
import kotlinx.coroutines.runBlocking
import java.net.InetSocketAddress
import java.util.concurrent.CountDownLatch
/**
* Serves a resolved NIP-5A/5D manifest over a local HTTP server so you can open it in a browser. Each
* request is resolved through quartz's [StaticSiteResolver] — the blob is downloaded from the
* manifest's Blossom servers and **sha256-verified** against the pin before it is served, exactly as
* the on-device host does. SPA fallback to `index.html` mirrors the host's behavior.
*
* Thin assembly over the resolver + commons [BlossomClient] + the JDK HTTP server. NOTE: this serves
* the **static content** only — a napplet's `window.napplet.*` runtime needs the Android/desktop shell
* + broker, which this does not provide; use it to inspect that the files load and route correctly.
*/
internal object StaticSiteServe {
suspend fun serve(
paths: List<PathTag>,
servers: List<String>,
port: Int,
): Int {
if (servers.isEmpty()) return Output.error("no_servers", "manifest lists no Blossom servers; pass --server URL")
val blossom = BlossomClient()
val server = HttpServer.create(InetSocketAddress("127.0.0.1", port), 0)
server.createContext("/") { exchange -> handle(exchange, paths, servers, blossom) }
server.executor = null // default per-request executor — fine for a single-user dev server
server.start()
val actualPort = server.address.port
Output.emit(
mapOf(
"serving" to "http://127.0.0.1:$actualPort/",
"port" to actualPort,
"paths" to paths.size,
"servers" to servers,
"note" to "static content only; napplet runtime APIs need the Amethyst host. Ctrl+C to stop.",
),
)
// Block until the process is interrupted (Ctrl+C), then stop cleanly.
val done = CountDownLatch(1)
Runtime.getRuntime().addShutdownHook(
Thread {
server.stop(0)
done.countDown()
},
)
runCatching { done.await() }
return 0
}
private fun handle(
exchange: HttpExchange,
paths: List<PathTag>,
servers: List<String>,
blossom: BlossomClient,
) {
exchange.use {
if (!exchange.requestMethod.equals("GET", ignoreCase = true)) {
exchange.sendResponseHeaders(405, -1)
return@use
}
val requestPath = exchange.requestURI.path
val fetch: suspend (String) -> ByteArray? = { url -> blossom.download(url) }
var resolution = runBlocking { StaticSiteResolver.resolve(requestPath, paths, servers, fetch) }
// SPA fallback: an unknown route falls back to the verified index.html (browsers send Accept: text/html).
if (resolution !is StaticSiteResolution.Resolved && requestPath != "/" && acceptsHtml(exchange)) {
resolution = runBlocking { StaticSiteResolver.resolve("/", paths, servers, fetch) }
}
if (resolution is StaticSiteResolution.Resolved) {
exchange.responseHeaders.set("Content-Type", resolution.contentType)
exchange.sendResponseHeaders(200, resolution.bytes.size.toLong())
exchange.responseBody.use { it.write(resolution.bytes) }
} else {
val body = "Not found: $requestPath".encodeToByteArray()
exchange.responseHeaders.set("Content-Type", "text/plain")
exchange.sendResponseHeaders(404, body.size.toLong())
exchange.responseBody.use { it.write(body) }
}
}
}
private fun acceptsHtml(exchange: HttpExchange): Boolean = exchange.requestHeaders.getFirst("Accept")?.contains("text/html", ignoreCase = true) == true
}