mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Compare commits
1
Commits
main
..
typechecking
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a72eec2966 |
No files matched your search
@@ -28,6 +28,24 @@ test:
|
||||
- npm run build
|
||||
- npm run test
|
||||
|
||||
deploy:
|
||||
stage: deploy
|
||||
rules:
|
||||
- if: $CI_COMMIT_TAG
|
||||
when: never
|
||||
- if: $CI_COMMIT_REF_NAME == $CI_DEFAULT_BRANCH && $DEPLOY_SSH_KEY && $DEPLOY_TARGET
|
||||
script:
|
||||
- npm ci
|
||||
- npm run build
|
||||
- cp dist/index.html dist/404.html
|
||||
- apt-get update -qq && apt-get install -y --no-install-recommends rsync openssh-client >/dev/null
|
||||
- mkdir -p ~/.ssh && chmod 700 ~/.ssh
|
||||
- echo "$DEPLOY_SSH_KEY" | tr -d '\r' > ~/.ssh/id_ed25519 && chmod 600 ~/.ssh/id_ed25519
|
||||
- ssh-keyscan -H "${DEPLOY_TARGET##*@}" >> ~/.ssh/known_hosts 2>/dev/null
|
||||
- rsync -av --exclude=/sw.js --exclude=/index.html -e "ssh -i ~/.ssh/id_ed25519" dist/ "${DEPLOY_TARGET}:/"
|
||||
- rsync -av -e "ssh -i ~/.ssh/id_ed25519" dist/index.html "${DEPLOY_TARGET}:/"
|
||||
- rsync -av -e "ssh -i ~/.ssh/id_ed25519" dist/sw.js "${DEPLOY_TARGET}:/"
|
||||
|
||||
deploy-nsite:
|
||||
stage: deploy
|
||||
timeout: 10 minutes
|
||||
|
||||
@@ -1,137 +0,0 @@
|
||||
name: Deploy nsite
|
||||
|
||||
# Builds dist/ and publishes it as the named nsite "shakespeare" (NIP-5A kind
|
||||
# 35128) described by .nsite/config.json: the files become Blossom blobs, the
|
||||
# manifest mapping path -> sha256 goes to relays, and npanel on venus serves
|
||||
# shakespeare.diy from it. Runs on pushes to the default branch, alongside
|
||||
# Test.
|
||||
#
|
||||
# Replaces the GitLab `deploy-nsite` job, which published the same site under a
|
||||
# PERSONAL npub with nsyte 0.24.1. The signing pubkey IS the site address, so
|
||||
# this one lives in the Team Soapbox namespace instead.
|
||||
#
|
||||
# Secrets are provisioned by the ngit-ci operator as
|
||||
# NGIT_CI_SECRET_<ALIAS>__<NAME> (note the double underscore) and injected ONLY
|
||||
# on maintainer-authored triggers, which a push to a watched repo always is.
|
||||
# This job needs one:
|
||||
# NSYTE_BUNKER nbunksec1... -- a pre-established NIP-46 session, the form
|
||||
# nsyte documents for CI.
|
||||
# An empty NSYTE_BUNKER fails the job rather than skipping quietly: this is the
|
||||
# only workflow that publishes the client anywhere, so a skipped run would
|
||||
# leave the nsite silently pinned to an older build.
|
||||
#
|
||||
# NOTE: *.shakespeare.diy is NOT served from here. The wildcard keeps its own
|
||||
# Caddy vhost and /var/www tree on venus, because the nsite catch-all issues
|
||||
# certificates on demand over HTTP-01 and cannot get a wildcard.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
|
||||
# Ahead of the build, so a config nsyte will not accept costs seconds
|
||||
# rather than failing at the end of a green-looking run.
|
||||
- name: Install nsyte and validate the config
|
||||
env:
|
||||
NSYTE_BUNKER: ${{ secrets.NSYTE_BUNKER }}
|
||||
run: |
|
||||
set -eu
|
||||
: "${NSYTE_BUNKER:?NSYTE_BUNKER is not set; ask the ngit-ci operator to provision it for this repo alias.}"
|
||||
|
||||
# Pin the binary as a FLOOR, not an exact version. An unversioned
|
||||
# install has been observed pulling 0.10.1, which emits legacy
|
||||
# kind-34128 events that every current gateway ignores while still
|
||||
# reporting a successful deploy. 0.28.0 is the floor because it is the
|
||||
# first release whose nostr-tools will encrypt a NIP-44 payload larger
|
||||
# than 64 KiB; under it, signing a large site manifest through the
|
||||
# bunker fails outright.
|
||||
#
|
||||
# nsyte is baked into the coordinator's CI image alongside zsp
|
||||
# (armada's .ngit/ci-image/Dockerfile). Comparing its VERSION rather
|
||||
# than just `command -v` is deliberate: a stale baked binary silently
|
||||
# outranked this pin, which is how deploys kept running 0.27.2 long
|
||||
# after the pin moved. Accepting anything NEWER than the floor lets
|
||||
# the image move ahead of these files without sending every job back
|
||||
# to the download.
|
||||
#
|
||||
# That download is the fallback for a coordinator whose image lacks
|
||||
# nsyte, and is exactly what kept failing here: the ~129 MB release
|
||||
# asset broke mid-transfer with "SSL_read: decryption failed or bad
|
||||
# record mac", identically on every attempt within a run, taking
|
||||
# deploy-nsite down across every repo. Hence the loop, HTTP/1.1, and
|
||||
# running the binary before trusting it.
|
||||
NSYTE_MIN_VERSION=0.28.0
|
||||
# nsyte colours its version output with ANSI escapes even when piped.
|
||||
baked="$(NO_COLOR=1 nsyte --version 2>/dev/null \
|
||||
| sed 's/\x1b\[[0-9;]*m//g' | awk 'NR == 1 { print $2 }')"
|
||||
oldest="$(printf '%s\n%s\n' "$NSYTE_MIN_VERSION" "$baked" | sort -V | head -1)"
|
||||
if [ -n "$baked" ] && [ "$oldest" = "$NSYTE_MIN_VERSION" ]; then
|
||||
echo "using the nsyte baked into the runner image ($baked)"
|
||||
else
|
||||
test -z "$baked" || echo "baked nsyte $baked is below $NSYTE_MIN_VERSION; downloading"
|
||||
NSYTE_URL="https://github.com/sandwichfarm/nsyte/releases/download/v${NSYTE_MIN_VERSION}/nsyte-linux-${NSYTE_MIN_VERSION}"
|
||||
ok=""
|
||||
for attempt in 1 2 3 4 5; do
|
||||
if curl -fsSL --http1.1 --retry 2 --retry-delay 5 --retry-all-errors \
|
||||
--connect-timeout 20 --max-time 900 -o /usr/local/bin/nsyte "$NSYTE_URL" \
|
||||
&& chmod +x /usr/local/bin/nsyte \
|
||||
&& nsyte --version >/dev/null; then
|
||||
ok=yes
|
||||
break
|
||||
fi
|
||||
echo "nsyte download attempt $attempt failed; retrying in 10s"
|
||||
sleep 10
|
||||
done
|
||||
test -n "$ok" || { echo "could not download a working nsyte after 5 attempts"; exit 1; }
|
||||
fi
|
||||
nsyte --version
|
||||
|
||||
nsyte validate
|
||||
|
||||
- run: npm ci
|
||||
|
||||
# Builds dist/ and copies index.html -> 404.html, the path NIP-5A host
|
||||
# servers fall back to.
|
||||
- run: npm run build
|
||||
|
||||
# Sourcemaps are ~290 files and 30 MB of blobs nobody fetches, and they
|
||||
# near-double the manifest. The GitLab job dropped them too.
|
||||
- run: find dist -name '*.map' -delete
|
||||
|
||||
- name: Publish to Blossom + relays
|
||||
env:
|
||||
NSYTE_BUNKER: ${{ secrets.NSYTE_BUNKER }}
|
||||
run: |
|
||||
set -eu
|
||||
|
||||
# Relays, servers and the site id all come from .nsite/config.json,
|
||||
# so they are versioned with the client rather than split across this
|
||||
# file. The secrets scan is skipped because it prompts on false
|
||||
# positives in our own bundle (pubkeys, bunker:// parsing code), and
|
||||
# a prompt is unanswerable here -- with -i it defaults to N and
|
||||
# aborts.
|
||||
set +e
|
||||
nsyte deploy dist \
|
||||
--sec "$NSYTE_BUNKER" \
|
||||
--concurrency 2 \
|
||||
--non-interactive \
|
||||
--skip-secrets-scan 2>&1 | tee /tmp/nsyte-deploy.log
|
||||
status="${PIPESTATUS[0]}"
|
||||
set -e
|
||||
|
||||
# A deploy that changes no file exits NON-ZERO with "No new files to
|
||||
# upload". That is success: the manifest already on the relays
|
||||
# describes exactly this build.
|
||||
if [ "$status" -ne 0 ] && ! grep -q "No new files to upload" /tmp/nsyte-deploy.log; then
|
||||
exit "$status"
|
||||
fi
|
||||
@@ -1,31 +0,0 @@
|
||||
name: Test
|
||||
|
||||
# Typecheck / lint / unit tests / production build for the Shakespeare client.
|
||||
# ngit-ci watches .ngit/act/workflows/ and runs each job with `act` (GitHub
|
||||
# Actions-compatible syntax) in a Linux container. Runs on every push and on
|
||||
# every Nostr PR.
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["**"]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version: 22
|
||||
|
||||
- run: npm ci
|
||||
|
||||
# package.json splits these: "typecheck" is tsc --noEmit and "test" is
|
||||
# eslint + vitest. The GitLab job ran typecheck, build and test; keep all
|
||||
# three so a type error still fails CI.
|
||||
- run: npm run typecheck
|
||||
- run: npm run build
|
||||
- run: npm run test
|
||||
@@ -1,20 +0,0 @@
|
||||
{
|
||||
"$schema": "https://nsyte.run/schemas/config.schema.json",
|
||||
"relays": [
|
||||
"wss://relay.ditto.pub",
|
||||
"wss://relay.dreamith.to",
|
||||
"wss://relay.primal.net"
|
||||
],
|
||||
"id": "shakespeare",
|
||||
"servers": [
|
||||
"https://blossom.ditto.pub",
|
||||
"https://blossom.dreamith.to",
|
||||
"https://blossom.primal.net"
|
||||
],
|
||||
"fallback": "/index.html",
|
||||
"publishRelayList": false,
|
||||
"publishServerList": false,
|
||||
"title": "Shakespeare",
|
||||
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment.",
|
||||
"source": "https://gitworkshop.dev/soapbox.pub/relay.ngit.dev/shakespeare"
|
||||
}
|
||||
@@ -42,6 +42,7 @@ Shakespeare provides AI agents with specialized tools for project development (n
|
||||
- **TextEditorWriteTool**: Create or overwrite files with new content
|
||||
- **TextEditorStrReplaceTool**: Replace strings in files
|
||||
- **BuildProjectTool**: Build and compile projects
|
||||
- **TypecheckProjectTool**: Typecheck projects with the TypeScript compiler, similar to `tsc --noEmit`
|
||||
- **NpmAddPackageTool**: Add npm packages to projects
|
||||
- **NpmRemovePackageTool**: Remove npm packages from projects
|
||||
- **GitCommitTool**: Commit changes to Git repositories
|
||||
@@ -271,7 +272,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
||||
- Unix-style commands: `cat`, `cd`, `cp`, `find`, `grep`, `ls`, `mkdir`, `mv`, `rm`, etc.
|
||||
- `/src/lib/tools/`: AI tool implementations for project development
|
||||
- File operations: `TextEditorViewTool`, `TextEditorWriteTool`, `TextEditorStrReplaceTool`
|
||||
- Project tools: `BuildProjectTool`
|
||||
- Project tools: `BuildProjectTool`, `TypecheckProjectTool`
|
||||
- Package management: `NpmAddPackageTool`, `NpmRemovePackageTool`
|
||||
- Git integration: `GitCommitTool`
|
||||
- Shell access: `ShellTool`
|
||||
|
||||
@@ -1,57 +1,5 @@
|
||||
# Changelog
|
||||
|
||||
## [9.16.4] - 2026-09-16
|
||||
|
||||
### Changed
|
||||
- Published sites carry only the tags the nsite spec defines — the relay hints Shakespeare used to attach were read by nothing, and taking a site back no longer rewrites them
|
||||
|
||||
## [9.16.3] - 2026-09-14
|
||||
|
||||
### Added
|
||||
- Take back your sites one at a time — every name waiting for you now has its own Publish, Show, and Delete buttons, so you can keep the few you want and clear out the rest
|
||||
- Show opens a site by its Nostr address before you decide about it, so you can look at names that never loaded in a browser
|
||||
|
||||
### Changed
|
||||
- Deleting a name only gives it up on shakespeare.wtf — anything published to Nostr stays yours
|
||||
- Names that couldn't be taken back safely can now be cleared out, instead of only explaining why they were stuck
|
||||
|
||||
## [9.16.2] - 2026-09-13
|
||||
|
||||
### Changed
|
||||
- Deploy settings now says how many of your names are waiting to be taken back, and stays quiet when there are none
|
||||
|
||||
### Fixed
|
||||
- Names you published before shakespeare.wtf changed hands are recognized as yours as you type them — the Deploy screen offers to hand them back instead of reporting them taken by somebody else
|
||||
|
||||
## [9.16.1] - 2026-09-13
|
||||
|
||||
### Fixed
|
||||
- Deploying to a name you already own works again — names you took back in the migration were reported as taken by somebody else, and the Deploy button refused to publish to your own site
|
||||
|
||||
## [9.16.0] - 2026-09-13
|
||||
|
||||
### Added
|
||||
- Take back the sites you published before shakespeare.wtf changed hands — Deploy settings now lists every name that's waiting for you and hands them all back at once, republished under your own key
|
||||
- Deploys report which relays accepted your site, and can fill in any that missed it without republishing
|
||||
|
||||
### Changed
|
||||
- Deploying to Shakespeare now publishes your site to Nostr under your own key, so it stays readable by any Nostr site viewer with or without shakespeare.wtf
|
||||
- Recovered sites are titled whatever they call themselves rather than after their web address
|
||||
|
||||
### Fixed
|
||||
- Deploying to Shakespeare works again — it had been reporting success while changing nothing, because the host it uploaded to no longer serves those addresses
|
||||
- New accounts start with Shakespeare set up as a deployment target instead of an empty screen
|
||||
- Deployment provider settings now scroll, so Save is always reachable
|
||||
|
||||
## [9.15.0] - 2026-08-19
|
||||
|
||||
### Added
|
||||
- Connect to Meridian as an AI provider — available as a one-click preset with streamlined setup
|
||||
- Optimize Repository action in the project menu that consolidates git history to reclaim space and repair bloated repositories
|
||||
|
||||
### Fixed
|
||||
- Zaps now verify the invoice amount before paying, so you're never charged more than you approved
|
||||
|
||||
## [9.14.0] - 2026-06-05
|
||||
|
||||
### Added
|
||||
|
||||
Generated
+129
-160
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "shakespeare.diy",
|
||||
"version": "9.16.4",
|
||||
"version": "9.14.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "shakespeare.diy",
|
||||
"version": "9.16.4",
|
||||
"version": "9.14.0",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"dependencies": {
|
||||
"@capacitor/app": "^8.1.0",
|
||||
@@ -21,8 +21,8 @@
|
||||
"@isomorphic-git/lightning-fs": "^4.6.2",
|
||||
"@modelcontextprotocol/sdk": "^1.22.0",
|
||||
"@mozilla/readability": "^0.6.0",
|
||||
"@nostrify/nostrify": "^0.54.1",
|
||||
"@nostrify/react": "^0.6.6",
|
||||
"@nostrify/nostrify": "^0.51.1",
|
||||
"@nostrify/react": "^0.4.1",
|
||||
"@opensecret/react": "^1.5.4",
|
||||
"@plausible-analytics/tracker": "^0.4.4",
|
||||
"@radix-ui/react-accordion": "^1.2.0",
|
||||
@@ -55,6 +55,7 @@
|
||||
"@sentry/react": "^10.22.0",
|
||||
"@std/encoding": "npm:@jsr/std__encoding@^1.0.10",
|
||||
"@tanstack/react-query": "^5.56.2",
|
||||
"@typescript/ata": "^0.9.8",
|
||||
"@unhead/addons": "^2.0.10",
|
||||
"@unhead/react": "^2.0.10",
|
||||
"acorn": "^8.16.0",
|
||||
@@ -97,6 +98,7 @@
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"tailwindcss-safe-area": "^0.8.0",
|
||||
"turndown": "^7.2.1",
|
||||
"typescript": "^5.8.3",
|
||||
"uri-templates": "^0.2.0",
|
||||
"use-stick-to-bottom": "^1.1.1",
|
||||
"vaul": "^0.9.3",
|
||||
@@ -134,7 +136,6 @@
|
||||
"jsdom": "^26.1.0",
|
||||
"postcss": "^8.4.47",
|
||||
"tailwindcss": "^3.4.11",
|
||||
"typescript": "^5.5.3",
|
||||
"typescript-eslint": "^8.0.1",
|
||||
"vite": "^6.3.5",
|
||||
"vite-plugin-pwa": "^1.1.0",
|
||||
@@ -190,9 +191,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/compat-data": {
|
||||
"version": "7.29.7",
|
||||
"resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz",
|
||||
"integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==",
|
||||
"version": "7.29.0",
|
||||
"resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.0.tgz",
|
||||
"integrity": "sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
@@ -200,21 +201,21 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/core": {
|
||||
"version": "7.29.7",
|
||||
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz",
|
||||
"integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",
|
||||
"version": "7.29.0",
|
||||
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.0.tgz",
|
||||
"integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/code-frame": "^7.29.7",
|
||||
"@babel/generator": "^7.29.7",
|
||||
"@babel/helper-compilation-targets": "^7.29.7",
|
||||
"@babel/helper-module-transforms": "^7.29.7",
|
||||
"@babel/helpers": "^7.29.7",
|
||||
"@babel/parser": "^7.29.7",
|
||||
"@babel/template": "^7.29.7",
|
||||
"@babel/traverse": "^7.29.7",
|
||||
"@babel/types": "^7.29.7",
|
||||
"@babel/code-frame": "^7.29.0",
|
||||
"@babel/generator": "^7.29.0",
|
||||
"@babel/helper-compilation-targets": "^7.28.6",
|
||||
"@babel/helper-module-transforms": "^7.28.6",
|
||||
"@babel/helpers": "^7.28.6",
|
||||
"@babel/parser": "^7.29.0",
|
||||
"@babel/template": "^7.28.6",
|
||||
"@babel/traverse": "^7.29.0",
|
||||
"@babel/types": "^7.29.0",
|
||||
"@jridgewell/remapping": "^2.3.5",
|
||||
"convert-source-map": "^2.0.0",
|
||||
"debug": "^4.1.0",
|
||||
@@ -270,14 +271,14 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/helper-compilation-targets": {
|
||||
"version": "7.29.7",
|
||||
"resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz",
|
||||
"integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==",
|
||||
"version": "7.28.6",
|
||||
"resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.28.6.tgz",
|
||||
"integrity": "sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/compat-data": "^7.29.7",
|
||||
"@babel/helper-validator-option": "^7.29.7",
|
||||
"@babel/compat-data": "^7.28.6",
|
||||
"@babel/helper-validator-option": "^7.27.1",
|
||||
"browserslist": "^4.24.0",
|
||||
"lru-cache": "^5.1.1",
|
||||
"semver": "^6.3.1"
|
||||
@@ -531,9 +532,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/helper-validator-option": {
|
||||
"version": "7.29.7",
|
||||
"resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz",
|
||||
"integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==",
|
||||
"version": "7.27.1",
|
||||
"resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.27.1.tgz",
|
||||
"integrity": "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
@@ -556,14 +557,14 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@babel/helpers": {
|
||||
"version": "7.29.7",
|
||||
"resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz",
|
||||
"integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==",
|
||||
"version": "7.29.2",
|
||||
"resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.2.tgz",
|
||||
"integrity": "sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@babel/template": "^7.29.7",
|
||||
"@babel/types": "^7.29.7"
|
||||
"@babel/template": "^7.28.6",
|
||||
"@babel/types": "^7.29.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=6.9.0"
|
||||
@@ -2682,9 +2683,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@hono/node-server": {
|
||||
"version": "1.19.17",
|
||||
"resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.17.tgz",
|
||||
"integrity": "sha512-dSneS5qhiauZWGDCeK4o695Xd9nUNjviSZCMQrj10eetr8Uln1ucn6bbphOM6UynAMMtNIzZNSpL9vnASJwrPQ==",
|
||||
"version": "1.19.14",
|
||||
"resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.14.tgz",
|
||||
"integrity": "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18.14.1"
|
||||
@@ -3293,11 +3294,11 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@nostrify/nostrify": {
|
||||
"version": "0.54.1",
|
||||
"resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.54.1.tgz",
|
||||
"integrity": "sha512-/iMRPBZdz+74pPXKHbQ7RsMwQtEXbJ/M21iNp1kbAMMvRh30hFjdV3ROU93rxGIDsOMSOpzeXXWT4Z+gXZW8Bg==",
|
||||
"version": "0.51.1",
|
||||
"resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.51.1.tgz",
|
||||
"integrity": "sha512-oPJhUiO1TlV5sGYizqAP4GvLijib34Uwh48wxlFimR/2MoCuSmab4AppcztGPNwxQoTKkJbLJwsSpl42V+WIXA==",
|
||||
"dependencies": {
|
||||
"@nostrify/types": "0.37.0",
|
||||
"@nostrify/types": "0.36.9",
|
||||
"@scure/base": "^2.0.0",
|
||||
"@smithy/util-base64": "^4.3.0",
|
||||
"@smithy/util-hex-encoding": "^4.2.0",
|
||||
@@ -3334,12 +3335,12 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@nostrify/react": {
|
||||
"version": "0.6.6",
|
||||
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.6.6.tgz",
|
||||
"integrity": "sha512-WTWTT3dtw0BF5bZsFgOob9S3J9rWKOsPQ2LLKDsDhx3PxbjIFKSVqSQLw7jiN6LoVGom9OuVOG/PB6p9hAWDjQ==",
|
||||
"version": "0.4.1",
|
||||
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.4.1.tgz",
|
||||
"integrity": "sha512-2JXxEl4e6FIFhbi96Dwv2knu5qAACYulo1a0oVell/aS8KCWsBTPd1+v0EUra0yqiUA3Q1nVLrk8mx7kQYH/yQ==",
|
||||
"dependencies": {
|
||||
"@nostrify/nostrify": "0.54.1",
|
||||
"@nostrify/types": "0.37.0"
|
||||
"@nostrify/nostrify": "0.51.1",
|
||||
"@nostrify/types": "0.36.9"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@tanstack/react-query": "^5.69.0",
|
||||
@@ -3349,9 +3350,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@nostrify/types": {
|
||||
"version": "0.37.0",
|
||||
"resolved": "https://registry.npmjs.org/@nostrify/types/-/types-0.37.0.tgz",
|
||||
"integrity": "sha512-P0AKR+qcNeBBTA5UDnJM6SxLAQbgud2+ZcdVyheoP37XGQvi7rUncQUDKwebG+Ui5kswp/IPEmvqNtCMQpwRoA=="
|
||||
"version": "0.36.9",
|
||||
"resolved": "https://registry.npmjs.org/@nostrify/types/-/types-0.36.9.tgz",
|
||||
"integrity": "sha512-tMx/r0W+QoVRRgs8d6ltaSgrftasOXuFsi33kW8WirswCy2b3UR1tqRgc0iBU9zRa9XR0nlej/wJZW+6wUFi+Q=="
|
||||
},
|
||||
"node_modules/@opensecret/react": {
|
||||
"version": "1.5.4",
|
||||
@@ -4900,9 +4901,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@remix-run/router": {
|
||||
"version": "1.23.4",
|
||||
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.4.tgz",
|
||||
"integrity": "sha512-q7j5geK7xs3UJSdm9/iytUNclBnLmYx1EnSeCFXHPeutdqgIMeFeHtUZgS3EhlKxdBEAu8OwtJCwmLrEzpSs7Q==",
|
||||
"version": "1.23.3",
|
||||
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.3.tgz",
|
||||
"integrity": "sha512-4An71tdz9X8+3sI4Qqqd2LWd9vS39J7sqd9EU4Scw7TJE/qB10Flv/UuqbPVgfQV9XoK8Np6jNquZitnZq5i+Q==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
@@ -6604,9 +6605,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": {
|
||||
"version": "2.1.4",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz",
|
||||
"integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==",
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.2.tgz",
|
||||
"integrity": "sha512-w5JZcKgdhDOgOwm8H+KgbosopHMuGcl6qbulwjtz3SM7I7P3yW1eAjzMPLrIE+NQ9vjgANKHWeMHnrT0OXW1oA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -6671,6 +6672,15 @@
|
||||
"url": "https://opencollective.com/typescript-eslint"
|
||||
}
|
||||
},
|
||||
"node_modules/@typescript/ata": {
|
||||
"version": "0.9.8",
|
||||
"resolved": "https://registry.npmjs.org/@typescript/ata/-/ata-0.9.8.tgz",
|
||||
"integrity": "sha512-+M815CeDRJS5H5ciWfhFCKp25nNfF+LFWawWAaBhNlquFb2wS5IIMDI+2bKWN3GuU6mpj+FzySsOD29M4nG8Xg==",
|
||||
"license": "MIT",
|
||||
"peerDependencies": {
|
||||
"typescript": ">=4.4.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@ungap/structured-clone": {
|
||||
"version": "1.3.0",
|
||||
"resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz",
|
||||
@@ -7335,20 +7345,20 @@
|
||||
}
|
||||
},
|
||||
"node_modules/body-parser": {
|
||||
"version": "2.3.0",
|
||||
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz",
|
||||
"integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==",
|
||||
"version": "2.2.2",
|
||||
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz",
|
||||
"integrity": "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"bytes": "^3.1.2",
|
||||
"content-type": "^2.0.0",
|
||||
"content-type": "^1.0.5",
|
||||
"debug": "^4.4.3",
|
||||
"http-errors": "^2.0.1",
|
||||
"iconv-lite": "^0.7.2",
|
||||
"http-errors": "^2.0.0",
|
||||
"iconv-lite": "^0.7.0",
|
||||
"on-finished": "^2.4.1",
|
||||
"qs": "^6.15.2",
|
||||
"raw-body": "^3.0.2",
|
||||
"type-is": "^2.1.0"
|
||||
"qs": "^6.14.1",
|
||||
"raw-body": "^3.0.1",
|
||||
"type-is": "^2.0.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
@@ -7358,19 +7368,6 @@
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/body-parser/node_modules/content-type": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz",
|
||||
"integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/body-parser/node_modules/iconv-lite": {
|
||||
"version": "0.7.2",
|
||||
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz",
|
||||
@@ -7401,9 +7398,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/brace-expansion": {
|
||||
"version": "1.1.18",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz",
|
||||
"integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==",
|
||||
"version": "1.1.13",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.13.tgz",
|
||||
"integrity": "sha512-9ZLprWS6EENmhEOpjCYW2c8VkmOvckIJZfkr7rBW6dObmfgJ/L1GpSYW5Hpo9lDz4D1+n0Ckz8rU7FwHDQiG/w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -9224,9 +9221,9 @@
|
||||
"license": "Apache-2.0"
|
||||
},
|
||||
"node_modules/fast-uri": {
|
||||
"version": "3.1.5",
|
||||
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz",
|
||||
"integrity": "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==",
|
||||
"version": "3.1.2",
|
||||
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz",
|
||||
"integrity": "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
@@ -9282,9 +9279,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/filelist/node_modules/brace-expansion": {
|
||||
"version": "2.1.4",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz",
|
||||
"integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==",
|
||||
"version": "2.1.1",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.1.tgz",
|
||||
"integrity": "sha512-WR1cURNjuvBLMZBMbqM0UoE+WAfdUcEV1ccD8PVBVOI+Z3ND4+SZbN8RsfT2bMuG1qwz5RFvPukSZm5fF2D5eA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -9641,9 +9638,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/glob/node_modules/brace-expansion": {
|
||||
"version": "2.1.4",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz",
|
||||
"integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==",
|
||||
"version": "2.0.3",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.3.tgz",
|
||||
"integrity": "sha512-MCV/fYJEbqx68aE58kv2cA/kiky1G8vux3OR6/jbS+jIMe/6fJWa0DTzJU7dqijOWYwHi1t29FlfYI9uytqlpA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"balanced-match": "^1.0.0"
|
||||
@@ -9745,9 +9742,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/gray-matter/node_modules/js-yaml": {
|
||||
"version": "3.15.1",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.1.tgz",
|
||||
"integrity": "sha512-S99WuO3HlhO3XN41EtYUNl9zzXjoJx7QvmipxsJVxtCBT0YHEFy+iOJhjSvrmV12nYhWpZaM8lPHkJm0yUMbag==",
|
||||
"version": "3.14.2",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz",
|
||||
"integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"argparse": "^1.0.7",
|
||||
@@ -10070,9 +10067,9 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/hono": {
|
||||
"version": "4.13.3",
|
||||
"resolved": "https://registry.npmjs.org/hono/-/hono-4.13.3.tgz",
|
||||
"integrity": "sha512-r8AO2mYHoLxSHkgafNeC/BXyb2vWRxD3jem4Ts+ptav8oTG5FIRifAjuJEmZI4bSvvc2ns0GxmIYiZnHqN3mMw==",
|
||||
"version": "4.12.23",
|
||||
"resolved": "https://registry.npmjs.org/hono/-/hono-4.12.23.tgz",
|
||||
"integrity": "sha512-eIaZ9qDgu7XV0pxOCrg7/WhnQ6Ivm22UcxhXx/A3dcbqbbYgBEkc6e/J/s7j2tS96zoB0S9VBdLwQNCWwUo4LA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=16.9.0"
|
||||
@@ -10354,9 +10351,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/ip-address": {
|
||||
"version": "10.5.0",
|
||||
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.5.0.tgz",
|
||||
"integrity": "sha512-R5SnVLJmgYYvf2F2ZgwSBnelz5G4q5AxIC277GDfUaNbrZKNANcBC7RHqYYePlszf4kBolVkJauG0ZjHHFh55g==",
|
||||
"version": "10.2.0",
|
||||
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz",
|
||||
"integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 12"
|
||||
@@ -11004,20 +11001,10 @@
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/js-yaml": {
|
||||
"version": "4.3.1",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.1.tgz",
|
||||
"integrity": "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==",
|
||||
"version": "4.1.1",
|
||||
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
|
||||
"integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/puzrin"
|
||||
},
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/nodeca"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"argparse": "^2.0.1"
|
||||
@@ -12639,9 +12626,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/nanoid": {
|
||||
"version": "3.3.18",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",
|
||||
"integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==",
|
||||
"version": "3.3.12",
|
||||
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz",
|
||||
"integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
@@ -13228,9 +13215,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/postcss": {
|
||||
"version": "8.5.26",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz",
|
||||
"integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==",
|
||||
"version": "8.5.15",
|
||||
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz",
|
||||
"integrity": "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "opencollective",
|
||||
@@ -13247,7 +13234,7 @@
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"nanoid": "^3.3.17",
|
||||
"nanoid": "^3.3.12",
|
||||
"picocolors": "^1.1.1",
|
||||
"source-map-js": "^1.2.1"
|
||||
},
|
||||
@@ -13839,12 +13826,12 @@
|
||||
}
|
||||
},
|
||||
"node_modules/react-router": {
|
||||
"version": "6.30.6",
|
||||
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.6.tgz",
|
||||
"integrity": "sha512-5HfK7k5im7LTOB0EqCQmfvy4C13G92Ssj1VTmouTK3AJvyjKTnFuCV0vcMAD/JS+JC4DvDIBRrlAeJIFjh5VWg==",
|
||||
"version": "6.30.4",
|
||||
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.4.tgz",
|
||||
"integrity": "sha512-SVUsDe+DybHM/WmYKIVYhZh1o5Dcuf16yM6WjG02Q9XVFMZIJyHYhwrr6bFBXZkVP6z69kNkMyBCujt8FaFLJA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@remix-run/router": "1.23.4"
|
||||
"@remix-run/router": "1.23.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
@@ -13854,13 +13841,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/react-router-dom": {
|
||||
"version": "6.30.6",
|
||||
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.6.tgz",
|
||||
"integrity": "sha512-0RHKZz7wwffvkU+2MFVT2NnjK44ssLEV+m0CAJaS2Ksmorrwj7WxH00jO0SOCW26/tINUnJHToXblDs33I38YQ==",
|
||||
"version": "6.30.4",
|
||||
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.4.tgz",
|
||||
"integrity": "sha512-q4HvNl+mmDdkS0g+MqiBZNteQJCuimWoOyHMy4T/RQLAn9Z29+E91QXRaxOujeMl2HTzRSS0KFPd7lxX3PjV0Q==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@remix-run/router": "1.23.4",
|
||||
"react-router": "6.30.6"
|
||||
"@remix-run/router": "1.23.3",
|
||||
"react-router": "6.30.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=14.0.0"
|
||||
@@ -14332,16 +14319,16 @@
|
||||
}
|
||||
},
|
||||
"node_modules/rimraf/node_modules/brace-expansion": {
|
||||
"version": "5.0.9",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz",
|
||||
"integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==",
|
||||
"version": "5.0.6",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.6.tgz",
|
||||
"integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"balanced-match": "^4.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": "20 || >=22"
|
||||
"node": "18 || 20 || >=22"
|
||||
}
|
||||
},
|
||||
"node_modules/rimraf/node_modules/glob": {
|
||||
@@ -15585,9 +15572,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/tar": {
|
||||
"version": "7.5.22",
|
||||
"resolved": "https://registry.npmjs.org/tar/-/tar-7.5.22.tgz",
|
||||
"integrity": "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==",
|
||||
"version": "7.5.13",
|
||||
"resolved": "https://registry.npmjs.org/tar/-/tar-7.5.13.tgz",
|
||||
"integrity": "sha512-tOG/7GyXpFevhXVh8jOPJrmtRpOTsYqUIkVdVooZYJS/z8WhfQUX8RJILmeuJNinGAMSu1veBr4asSHFt5/hng==",
|
||||
"dev": true,
|
||||
"license": "BlueOak-1.0.0",
|
||||
"dependencies": {
|
||||
@@ -15974,34 +15961,17 @@
|
||||
}
|
||||
},
|
||||
"node_modules/type-is": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",
|
||||
"integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==",
|
||||
"version": "2.0.1",
|
||||
"resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz",
|
||||
"integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"content-type": "^2.0.0",
|
||||
"content-type": "^1.0.5",
|
||||
"media-typer": "^1.1.0",
|
||||
"mime-types": "^3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 18"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
}
|
||||
},
|
||||
"node_modules/type-is/node_modules/content-type": {
|
||||
"version": "2.1.0",
|
||||
"resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz",
|
||||
"integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/express"
|
||||
"node": ">= 0.6"
|
||||
}
|
||||
},
|
||||
"node_modules/typed-array-buffer": {
|
||||
@@ -16085,7 +16055,6 @@
|
||||
"version": "5.8.3",
|
||||
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",
|
||||
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
|
||||
"devOptional": true,
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"tsc": "bin/tsc",
|
||||
@@ -17217,16 +17186,16 @@
|
||||
}
|
||||
},
|
||||
"node_modules/workbox-build/node_modules/brace-expansion": {
|
||||
"version": "5.0.9",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz",
|
||||
"integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==",
|
||||
"version": "5.0.6",
|
||||
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.6.tgz",
|
||||
"integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"balanced-match": "^4.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": "20 || >=22"
|
||||
"node": "18 || 20 || >=22"
|
||||
}
|
||||
},
|
||||
"node_modules/workbox-build/node_modules/glob": {
|
||||
|
||||
+5
-4
@@ -3,7 +3,7 @@
|
||||
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment",
|
||||
"homepage": "https://shakespeare.diy",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"version": "9.16.4",
|
||||
"version": "9.14.0",
|
||||
"type": "module",
|
||||
"author": {
|
||||
"name": "shakespeare.diy",
|
||||
@@ -34,8 +34,8 @@
|
||||
"@isomorphic-git/lightning-fs": "^4.6.2",
|
||||
"@modelcontextprotocol/sdk": "^1.22.0",
|
||||
"@mozilla/readability": "^0.6.0",
|
||||
"@nostrify/nostrify": "^0.54.1",
|
||||
"@nostrify/react": "^0.6.6",
|
||||
"@nostrify/nostrify": "^0.51.1",
|
||||
"@nostrify/react": "^0.4.1",
|
||||
"@opensecret/react": "^1.5.4",
|
||||
"@plausible-analytics/tracker": "^0.4.4",
|
||||
"@radix-ui/react-accordion": "^1.2.0",
|
||||
@@ -68,6 +68,7 @@
|
||||
"@sentry/react": "^10.22.0",
|
||||
"@std/encoding": "npm:@jsr/std__encoding@^1.0.10",
|
||||
"@tanstack/react-query": "^5.56.2",
|
||||
"@typescript/ata": "^0.9.8",
|
||||
"@unhead/addons": "^2.0.10",
|
||||
"@unhead/react": "^2.0.10",
|
||||
"acorn": "^8.16.0",
|
||||
@@ -110,6 +111,7 @@
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"tailwindcss-safe-area": "^0.8.0",
|
||||
"turndown": "^7.2.1",
|
||||
"typescript": "^5.8.3",
|
||||
"uri-templates": "^0.2.0",
|
||||
"use-stick-to-bottom": "^1.1.1",
|
||||
"vaul": "^0.9.3",
|
||||
@@ -147,7 +149,6 @@
|
||||
"jsdom": "^26.1.0",
|
||||
"postcss": "^8.4.47",
|
||||
"tailwindcss": "^3.4.11",
|
||||
"typescript": "^5.5.3",
|
||||
"typescript-eslint": "^8.0.1",
|
||||
"vite": "^6.3.5",
|
||||
"vite-plugin-pwa": "^1.1.0",
|
||||
|
||||
@@ -1,57 +1,5 @@
|
||||
# Changelog
|
||||
|
||||
## [9.16.4] - 2026-09-16
|
||||
|
||||
### Changed
|
||||
- Published sites carry only the tags the nsite spec defines — the relay hints Shakespeare used to attach were read by nothing, and taking a site back no longer rewrites them
|
||||
|
||||
## [9.16.3] - 2026-09-14
|
||||
|
||||
### Added
|
||||
- Take back your sites one at a time — every name waiting for you now has its own Publish, Show, and Delete buttons, so you can keep the few you want and clear out the rest
|
||||
- Show opens a site by its Nostr address before you decide about it, so you can look at names that never loaded in a browser
|
||||
|
||||
### Changed
|
||||
- Deleting a name only gives it up on shakespeare.wtf — anything published to Nostr stays yours
|
||||
- Names that couldn't be taken back safely can now be cleared out, instead of only explaining why they were stuck
|
||||
|
||||
## [9.16.2] - 2026-09-13
|
||||
|
||||
### Changed
|
||||
- Deploy settings now says how many of your names are waiting to be taken back, and stays quiet when there are none
|
||||
|
||||
### Fixed
|
||||
- Names you published before shakespeare.wtf changed hands are recognized as yours as you type them — the Deploy screen offers to hand them back instead of reporting them taken by somebody else
|
||||
|
||||
## [9.16.1] - 2026-09-13
|
||||
|
||||
### Fixed
|
||||
- Deploying to a name you already own works again — names you took back in the migration were reported as taken by somebody else, and the Deploy button refused to publish to your own site
|
||||
|
||||
## [9.16.0] - 2026-09-13
|
||||
|
||||
### Added
|
||||
- Take back the sites you published before shakespeare.wtf changed hands — Deploy settings now lists every name that's waiting for you and hands them all back at once, republished under your own key
|
||||
- Deploys report which relays accepted your site, and can fill in any that missed it without republishing
|
||||
|
||||
### Changed
|
||||
- Deploying to Shakespeare now publishes your site to Nostr under your own key, so it stays readable by any Nostr site viewer with or without shakespeare.wtf
|
||||
- Recovered sites are titled whatever they call themselves rather than after their web address
|
||||
|
||||
### Fixed
|
||||
- Deploying to Shakespeare works again — it had been reporting success while changing nothing, because the host it uploaded to no longer serves those addresses
|
||||
- New accounts start with Shakespeare set up as a deployment target instead of an empty screen
|
||||
- Deployment provider settings now scroll, so Save is always reachable
|
||||
|
||||
## [9.15.0] - 2026-08-19
|
||||
|
||||
### Added
|
||||
- Connect to Meridian as an AI provider — available as a one-click preset with streamlined setup
|
||||
- Optimize Repository action in the project menu that consolidates git history to reclaim space and repair bloated repositories
|
||||
|
||||
### Fixed
|
||||
- Zaps now verify the invoice amount before paying, so you're never charged more than you approved
|
||||
|
||||
## [9.14.0] - 2026-06-05
|
||||
|
||||
### Added
|
||||
|
||||
@@ -156,7 +156,7 @@ export function AddAIProviderDialog({
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && apiKey.trim() && (termsAgreed || !preset.tosURL)) {
|
||||
if (e.key === 'Enter' && apiKey.trim() && termsAgreed) {
|
||||
handleAdd();
|
||||
}
|
||||
}}
|
||||
@@ -165,20 +165,20 @@ export function AddAIProviderDialog({
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Terms of Service Agreement (skipped for providers without terms, e.g. local services) */}
|
||||
{preset.tosURL && (
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Checkbox
|
||||
id="agree-terms"
|
||||
checked={termsAgreed}
|
||||
onCheckedChange={(checked) => setTermsAgreed(checked === true)}
|
||||
className="size-3 [&_svg]:size-3"
|
||||
/>
|
||||
<label
|
||||
htmlFor="agree-terms"
|
||||
className="text-xs text-muted-foreground leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
|
||||
>
|
||||
{t('agreeToTermsOfService', { providerName: preset.name })}{' '}
|
||||
{/* Terms of Service Agreement */}
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Checkbox
|
||||
id="agree-terms"
|
||||
checked={termsAgreed}
|
||||
onCheckedChange={(checked) => setTermsAgreed(checked === true)}
|
||||
className="size-3 [&_svg]:size-3"
|
||||
/>
|
||||
<label
|
||||
htmlFor="agree-terms"
|
||||
className="text-xs text-muted-foreground leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
|
||||
>
|
||||
{t('agreeToTermsOfService', { providerName: preset.name })}{' '}
|
||||
{preset.tosURL ? (
|
||||
<a
|
||||
href={preset.tosURL}
|
||||
target="_blank"
|
||||
@@ -188,9 +188,11 @@ export function AddAIProviderDialog({
|
||||
>
|
||||
{t('termsOfService')}
|
||||
</a>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
) : (
|
||||
t('termsOfService')
|
||||
)}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -203,7 +205,7 @@ export function AddAIProviderDialog({
|
||||
<Button
|
||||
onClick={handleAdd}
|
||||
disabled={
|
||||
(!!preset.tosURL && !termsAgreed) ||
|
||||
!termsAgreed ||
|
||||
(!!preset.apiKeysURL && !apiKey.trim())
|
||||
}
|
||||
>
|
||||
|
||||
@@ -23,7 +23,7 @@ import {
|
||||
SelectValue,
|
||||
} from '@/components/ui/select';
|
||||
import type {
|
||||
NpanelProvider,
|
||||
ShakespeareDeployProvider,
|
||||
NetlifyProvider,
|
||||
VercelProvider,
|
||||
NsiteProvider,
|
||||
@@ -34,7 +34,7 @@ import type {
|
||||
|
||||
// Type for provider without the 'id' field (will be generated)
|
||||
type DeployProviderInput =
|
||||
| Omit<NpanelProvider, 'id'>
|
||||
| Omit<ShakespeareDeployProvider, '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<'npanel' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway' | ''>('');
|
||||
const [customProviderType, setCustomProviderType] = useState<'shakespeare' | '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 [customDashboardHost, setCustomDashboardHost] = useState('');
|
||||
const [customHost, setCustomHost] = useState('');
|
||||
const [customProxy, setCustomProxy] = useState(false);
|
||||
const [customGateway, setCustomGateway] = useState('');
|
||||
const [customRelayUrls, setCustomRelayUrls] = useState<string[]>([]);
|
||||
@@ -73,15 +73,12 @@ export function AddCustomProviderDialog({
|
||||
// Build provider object based on type
|
||||
let provider: DeployProviderInput;
|
||||
|
||||
if (customProviderType === 'npanel') {
|
||||
if (!customDashboardHost.trim() || !customGateway.trim()) return;
|
||||
if (customProviderType === 'shakespeare') {
|
||||
provider = {
|
||||
type: 'npanel',
|
||||
type: 'shakespeare',
|
||||
name: customName.trim(),
|
||||
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/'],
|
||||
...(customHost?.trim() && { host: customHost.trim() }),
|
||||
...(customProxy && { proxy: true }),
|
||||
};
|
||||
} else if (customProviderType === 'nsite') {
|
||||
provider = {
|
||||
@@ -154,7 +151,7 @@ export function AddCustomProviderDialog({
|
||||
setCustomOrganizationId('');
|
||||
setCustomBaseURL('');
|
||||
setCustomBaseDomain('');
|
||||
setCustomDashboardHost('');
|
||||
setCustomHost('');
|
||||
setCustomProxy(false);
|
||||
setCustomGateway('');
|
||||
setCustomRelayUrls([]);
|
||||
@@ -163,22 +160,12 @@ export function AddCustomProviderDialog({
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
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());
|
||||
const isValid = customProviderType && customName.trim() &&
|
||||
(customProviderType === 'shakespeare' || customProviderType === 'nsite' ||
|
||||
(customApiKey.trim() &&
|
||||
(customProviderType !== 'cloudflare' || customAccountId.trim()) &&
|
||||
(customProviderType !== 'deno' || customOrganizationId.trim()) &&
|
||||
(customProviderType !== 'railway' || true)));
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
@@ -197,7 +184,7 @@ export function AddCustomProviderDialog({
|
||||
</Label>
|
||||
<Select
|
||||
value={customProviderType}
|
||||
onValueChange={(value: 'npanel' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway') => {
|
||||
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway') => {
|
||||
setCustomProviderType(value);
|
||||
// Reset form when provider type changes
|
||||
setCustomApiKey('');
|
||||
@@ -205,7 +192,7 @@ export function AddCustomProviderDialog({
|
||||
setCustomOrganizationId('');
|
||||
setCustomBaseURL('');
|
||||
setCustomBaseDomain('');
|
||||
setCustomDashboardHost('');
|
||||
setCustomHost('');
|
||||
setCustomProxy(false);
|
||||
setCustomGateway('');
|
||||
setCustomRelayUrls([]);
|
||||
@@ -216,7 +203,7 @@ export function AddCustomProviderDialog({
|
||||
<SelectValue placeholder={t('selectProviderType')} />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="npanel">nsite gateway</SelectItem>
|
||||
<SelectItem value="shakespeare">Shakespeare Deploy</SelectItem>
|
||||
<SelectItem value="nsite">nsite</SelectItem>
|
||||
<SelectItem value="netlify">Netlify</SelectItem>
|
||||
<SelectItem value="vercel">Vercel</SelectItem>
|
||||
@@ -241,53 +228,20 @@ export function AddCustomProviderDialog({
|
||||
/>
|
||||
</div>
|
||||
|
||||
{customProviderType === 'npanel' ? (
|
||||
{customProviderType === 'shakespeare' ? (
|
||||
<>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('shakespeareDeployNostrAuth')}
|
||||
</p>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-domain">
|
||||
Domain <span className="text-destructive">*</span>
|
||||
</Label>
|
||||
<Label htmlFor="custom-host">Host (Optional)</Label>
|
||||
<Input
|
||||
id="custom-domain"
|
||||
id="custom-host"
|
||||
placeholder="shakespeare.wtf"
|
||||
value={customGateway}
|
||||
onChange={(e) => setCustomGateway(e.target.value)}
|
||||
value={customHost}
|
||||
onChange={(e) => setCustomHost(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_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
|
||||
import { DEFAULT_NSITE_PROVIDER } from '@/lib/deployProviderPresets';
|
||||
|
||||
const DEFAULT_SETTINGS: DeploySettings = {
|
||||
providers: [...DEFAULT_DEPLOY_PROVIDERS],
|
||||
providers: [DEFAULT_NSITE_PROVIDER],
|
||||
};
|
||||
|
||||
export function DeploySettingsProvider({ children }: { children: ReactNode }) {
|
||||
|
||||
@@ -1,26 +1,8 @@
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { faviconUrl } from '@/lib/faviconUrl';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { Globe } from 'lucide-react';
|
||||
import { ReactNode, useMemo } from 'react';
|
||||
|
||||
/**
|
||||
* Icons for known providers whose URLs can't resolve a favicon,
|
||||
* such as services running on localhost.
|
||||
*/
|
||||
function knownProviderIcon(url: string | URL | undefined, size: number): ReactNode | undefined {
|
||||
if (!url) return;
|
||||
try {
|
||||
const u = new URL(url);
|
||||
// Meridian local bridge
|
||||
if (u.hostname === '127.0.0.1' && u.port === '3456') {
|
||||
return <Globe size={size} className="text-purple-500" />;
|
||||
}
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
interface ExternalFaviconProps {
|
||||
/** The URL to fetch the favicon for */
|
||||
url: string | URL | undefined;
|
||||
@@ -60,16 +42,6 @@ export function ExternalFavicon({
|
||||
}
|
||||
}, [url, config.faviconUrl]);
|
||||
|
||||
// Providers with a known icon (e.g. local services) skip the favicon service
|
||||
const knownIcon = knownProviderIcon(url, size);
|
||||
if (knownIcon) {
|
||||
return (
|
||||
<span className={cn('inline-flex items-center justify-center', className)}>
|
||||
{knownIcon}
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
// If faviconSrc is not available, render the fallback directly
|
||||
if (!faviconSrc) {
|
||||
return (
|
||||
|
||||
@@ -74,16 +74,18 @@ export function ProviderConfigDialog({
|
||||
// Use baseURL from configured provider, falling back to preset baseURL
|
||||
const baseURL = ('baseURL' in localProvider && localProvider.baseURL) || preset?.baseURL;
|
||||
|
||||
// A gateway is recognised by the domain it serves, not by its API origin
|
||||
const gatewayUrl = localProvider.type === 'npanel' ? normalizeUrl(localProvider.domain) : undefined;
|
||||
// For Shakespeare, special handling for host field
|
||||
const shakespeareUrl = localProvider.type === 'shakespeare' && 'host' in localProvider && localProvider.host
|
||||
? normalizeUrl(localProvider.host)
|
||||
: undefined;
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md max-h-[90vh] flex flex-col">
|
||||
<DialogHeader className="shrink-0">
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<div className="flex items-center gap-2">
|
||||
<ExternalFavicon
|
||||
url={gatewayUrl || baseURL}
|
||||
url={shakespeareUrl || baseURL}
|
||||
size={20}
|
||||
fallback={<Rocket size={20} />}
|
||||
/>
|
||||
@@ -94,10 +96,7 @@ export function ProviderConfigDialog({
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{/* The fields scroll, the buttons don't: a provider with relay and
|
||||
blossom lists is taller than a phone, and a Save button below the
|
||||
fold is a Save button nobody can press. */}
|
||||
<div className="flex-1 overflow-y-auto space-y-4 py-4 px-1 -mx-1">
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-name">
|
||||
Name <span className="text-destructive">*</span>
|
||||
@@ -110,55 +109,22 @@ export function ProviderConfigDialog({
|
||||
/>
|
||||
</div>
|
||||
|
||||
{localProvider.type === 'npanel' ? (
|
||||
{localProvider.type === 'shakespeare' ? (
|
||||
<>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('shakespeareDeployNostrAuth')}
|
||||
</p>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="provider-domain">
|
||||
Domain <span className="text-destructive">*</span>
|
||||
<Label htmlFor="provider-host">
|
||||
Host (Optional)
|
||||
</Label>
|
||||
<Input
|
||||
id="provider-domain"
|
||||
id="provider-host"
|
||||
placeholder="shakespeare.wtf"
|
||||
value={localProvider.domain}
|
||||
onChange={(e) => setLocalProvider({ ...localProvider, domain: e.target.value })}
|
||||
value={localProvider.host || ''}
|
||||
onChange={(e) => setLocalProvider({ ...localProvider, host: 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' ? (
|
||||
<>
|
||||
@@ -306,7 +272,7 @@ export function ProviderConfigDialog({
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter className="gap-2 shrink-0">
|
||||
<DialogFooter className="gap-2">
|
||||
<Button
|
||||
variant="destructive"
|
||||
onClick={handleDelete}
|
||||
|
||||
@@ -27,6 +27,7 @@ import { NpmAddPackageTool } from '@/lib/tools/NpmAddPackageTool';
|
||||
import { NpmRemovePackageTool } from '@/lib/tools/NpmRemovePackageTool';
|
||||
import { GitCommitTool } from '@/lib/tools/GitCommitTool';
|
||||
import { BuildProjectTool } from '@/lib/tools/BuildProjectTool';
|
||||
import { TypecheckProjectTool } from '@/lib/tools/TypecheckProjectTool';
|
||||
import { NostrReadNipTool } from '@/lib/tools/NostrReadNipTool';
|
||||
import { NostrFetchEventTool } from '@/lib/tools/NostrFetchEventTool';
|
||||
import { NostrReadKindTool } from '@/lib/tools/NostrReadKindTool';
|
||||
@@ -213,6 +214,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
npm_add_package: new NpmAddPackageTool(fs, cwd),
|
||||
npm_remove_package: new NpmRemovePackageTool(fs, cwd),
|
||||
build_project: new BuildProjectTool(fs, cwd, esmUrlRef.current),
|
||||
typecheck: new TypecheckProjectTool(fs, cwd),
|
||||
nostr_read_nip: new NostrReadNipTool(),
|
||||
nostr_fetch_event: new NostrFetchEventTool(),
|
||||
nostr_read_kind: new NostrReadKindTool(),
|
||||
|
||||
@@ -29,6 +29,7 @@ import {
|
||||
Search,
|
||||
Clipboard,
|
||||
AppWindow,
|
||||
FileCheck,
|
||||
} from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { VFSImage } from '@/components/VFSImage';
|
||||
@@ -240,6 +241,14 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
|
||||
errorTitle: 'Failed to build project',
|
||||
};
|
||||
|
||||
case 'typecheck':
|
||||
return {
|
||||
icon: FileCheck,
|
||||
title: 'Typechecked project',
|
||||
callingTitle: 'Typechecking project',
|
||||
errorTitle: 'Found type errors',
|
||||
};
|
||||
|
||||
case 'nostr_read_nip':
|
||||
return {
|
||||
icon: BookOpen,
|
||||
|
||||
@@ -17,11 +17,10 @@ import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { NostrURI } from '@/lib/NostrURI';
|
||||
import { Link } from 'react-router-dom';
|
||||
import type { DeployProvider, NpanelProvider } from '@/contexts/DeploySettingsContext';
|
||||
import { NpanelMigrationDialog } from '@/components/deploy/NpanelMigrationDialog';
|
||||
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
||||
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
||||
import { PRESET_DEPLOY_PROVIDERS } from '@/lib/deployProviderPresets';
|
||||
import { NpanelDeployForm } from '@/components/deploy/NpanelDeployForm';
|
||||
import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm';
|
||||
import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm';
|
||||
import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
|
||||
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
|
||||
@@ -30,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 { NpanelAdapter } from '@/lib/deploy/NpanelAdapter';
|
||||
import { ShakespeareAdapter } from '@/lib/deploy/ShakespeareAdapter';
|
||||
import { NsiteAdapter } from '@/lib/deploy/NsiteAdapter';
|
||||
import { NetlifyAdapter } from '@/lib/deploy/NetlifyAdapter';
|
||||
import { VercelAdapter } from '@/lib/deploy/VercelAdapter';
|
||||
@@ -75,11 +74,12 @@ 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;
|
||||
|
||||
// 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;
|
||||
// For Shakespeare, special handling for host field
|
||||
const shakespeareUrl = provider.type === 'shakespeare' && 'host' in provider && provider.host
|
||||
? normalizeUrl(provider.host)
|
||||
: undefined;
|
||||
|
||||
const url = gatewayUrl || baseURL;
|
||||
const url = shakespeareUrl || baseURL;
|
||||
|
||||
if (url) {
|
||||
return (
|
||||
@@ -100,10 +100,8 @@ interface DeployStepsProps {
|
||||
onClose: () => void;
|
||||
}
|
||||
|
||||
interface NpanelFormData {
|
||||
interface ShakespeareFormData {
|
||||
subdomain: string;
|
||||
siteTitle: string;
|
||||
siteDescription: string;
|
||||
}
|
||||
|
||||
interface NsiteFormData {
|
||||
@@ -154,25 +152,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 [isNpanelFormValid, setIsNpanelFormValid] = useState(true);
|
||||
/**
|
||||
* The gateway whose held names are being looked at, if any.
|
||||
*
|
||||
* Owned here rather than by the name field, because what someone recognising
|
||||
* one of their names wants is usually all of them, and because the dialog
|
||||
* that hands them back outlives the field that prompted it.
|
||||
*/
|
||||
const [migratingProvider, setMigratingProvider] = useState<NpanelProvider | null>(null);
|
||||
|
||||
/**
|
||||
* Whether the deploy failed because the gateway is holding the name for this
|
||||
* user, which is a refusal with something to do about it.
|
||||
*
|
||||
* Read off the sentence npanel sent rather than a status code, since the 409
|
||||
* it arrives as also covers a name somebody else holds and a name that is
|
||||
* simply configured already.
|
||||
*/
|
||||
const heldName = error !== null && /being held for you/i.test(error);
|
||||
const [isShakespeareFormValid, setIsShakespeareFormValid] = useState(true);
|
||||
|
||||
// .nsite/config.json state — loaded once on mount, used to skip config form on re-deploy
|
||||
const [nsiteVfsConfig, setNsiteVfsConfig] = useState<NsiteVfsConfig | null>(null);
|
||||
@@ -207,10 +187,8 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
}, [fs, projectsPath, projectId]);
|
||||
|
||||
// Provider-specific form data
|
||||
const [npanelForm, setNpanelForm] = useState<NpanelFormData>({
|
||||
const [shakespeareForm, setShakespeareForm] = useState<ShakespeareFormData>({
|
||||
subdomain: projectId,
|
||||
siteTitle: projectName || projectId,
|
||||
siteDescription: '',
|
||||
});
|
||||
const [nsiteForm, setNsiteForm] = useState<NsiteFormData>({
|
||||
siteTitle: '',
|
||||
@@ -267,36 +245,18 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
|
||||
let adapter: DeployAdapter;
|
||||
|
||||
if (selectedProvider.type === 'npanel') {
|
||||
if (selectedProvider.type === 'shakespeare') {
|
||||
if (!user) {
|
||||
throw new Error('You must be logged in with Nostr to deploy here.');
|
||||
throw new Error('You must be logged in with Nostr to use Shakespeare Deploy');
|
||||
}
|
||||
|
||||
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({
|
||||
const shakespeareProvider = selectedProvider;
|
||||
adapter = new ShakespeareAdapter({
|
||||
fs,
|
||||
nostr,
|
||||
signer: user.signer,
|
||||
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,
|
||||
host: shakespeareProvider.host,
|
||||
subdomain: shakespeareForm.subdomain || undefined,
|
||||
corsProxy: shakespeareProvider.proxy ? config.corsProxy : undefined,
|
||||
});
|
||||
} else if (selectedProvider.type === 'nsite') {
|
||||
const nsiteProvider = selectedProvider;
|
||||
@@ -415,14 +375,12 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
});
|
||||
|
||||
// Save project-specific settings (updateSettings now automatically sets currentProvider)
|
||||
if (selectedProvider.type === 'npanel') {
|
||||
if (selectedProvider.type === 'shakespeare') {
|
||||
await updateProjectSettings(selectedProviderId, {
|
||||
type: 'npanel',
|
||||
type: 'shakespeare',
|
||||
url: result.url,
|
||||
data: {
|
||||
subdomain: npanelForm.subdomain.trim() || undefined,
|
||||
siteTitle: npanelForm.siteTitle || undefined,
|
||||
siteDescription: npanelForm.siteDescription || undefined,
|
||||
subdomain: shakespeareForm.subdomain || undefined,
|
||||
},
|
||||
});
|
||||
} else if (selectedProvider.type === 'nsite') {
|
||||
@@ -558,7 +516,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
setDeployResult(null);
|
||||
setError(null);
|
||||
// Reset forms
|
||||
setNpanelForm({ subdomain: projectId, siteTitle: projectName || projectId, siteDescription: '' });
|
||||
setShakespeareForm({ subdomain: projectId });
|
||||
setNsiteForm({ siteTitle: '', siteDescription: '', dTag: '' });
|
||||
setNetlifyForm({ siteId: '', siteName: '' });
|
||||
setVercelForm({ projectName: projectName || projectId, teamId: '' });
|
||||
@@ -570,20 +528,12 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
onClose();
|
||||
};
|
||||
|
||||
const handleNpanelSubdomainChange = useCallback((subdomain: string) => {
|
||||
setNpanelForm(prev => ({ ...prev, subdomain }));
|
||||
const handleShakespeareSubdomainChange = useCallback((subdomain: string) => {
|
||||
setShakespeareForm({ subdomain });
|
||||
}, []);
|
||||
|
||||
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 handleShakespeareValidationChange = useCallback((isValid: boolean) => {
|
||||
setIsShakespeareFormValid(isValid);
|
||||
}, []);
|
||||
|
||||
const handleNsiteSiteTitleChange = useCallback((siteTitle: string) => {
|
||||
@@ -628,25 +578,18 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
const renderProviderFields = () => {
|
||||
if (!selectedProvider) return null;
|
||||
|
||||
if (selectedProvider.type === 'npanel') {
|
||||
const npanelProvider = selectedProvider;
|
||||
if (selectedProvider.type === 'shakespeare') {
|
||||
const shakespeareProvider = selectedProvider;
|
||||
const savedConfig = projectSettings.providers[selectedProviderId];
|
||||
const saved = savedConfig?.type === 'npanel' ? savedConfig.data : undefined;
|
||||
const savedSubdomain = savedConfig?.type === 'shakespeare' ? savedConfig.data.subdomain : undefined;
|
||||
|
||||
return (
|
||||
<NpanelDeployForm
|
||||
dashboardHost={npanelProvider.dashboardHost}
|
||||
domain={npanelProvider.domain}
|
||||
<ShakespeareDeployForm
|
||||
host={shakespeareProvider.host}
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
savedSubdomain={saved?.subdomain}
|
||||
savedSiteTitle={saved?.siteTitle}
|
||||
savedSiteDescription={saved?.siteDescription}
|
||||
onSubdomainChange={handleNpanelSubdomainChange}
|
||||
onSiteTitleChange={handleNpanelSiteTitleChange}
|
||||
onSiteDescriptionChange={handleNpanelSiteDescriptionChange}
|
||||
onValidationChange={handleNpanelValidationChange}
|
||||
onTakeBackSites={() => setMigratingProvider(npanelProvider)}
|
||||
savedSubdomain={savedSubdomain}
|
||||
onSubdomainChange={handleShakespeareSubdomainChange}
|
||||
onValidationChange={handleShakespeareValidationChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -963,11 +906,11 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
|
||||
{selectedProvider && renderProviderFields()}
|
||||
|
||||
{selectedProvider?.type === 'npanel' && !user && (
|
||||
{selectedProvider?.type === 'shakespeare' && !user && (
|
||||
<Alert>
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
You must be logged in with Nostr to publish a site.{' '}
|
||||
You must be logged in with Nostr to use Shakespeare Deploy.{' '}
|
||||
<Link
|
||||
to="/settings/nostr"
|
||||
className="underline hover:no-underline"
|
||||
@@ -998,22 +941,7 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription className="space-y-2">
|
||||
<p>{error}</p>
|
||||
{/* The gateway refuses a name it is holding for this user
|
||||
and says to take it back instead. Saying so and leaving
|
||||
them to find out where is the worst of both. */}
|
||||
{heldName && selectedProvider?.type === 'npanel' && (
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => setMigratingProvider(selectedProvider)}
|
||||
>
|
||||
Take back your sites
|
||||
</Button>
|
||||
)}
|
||||
</AlertDescription>
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
@@ -1022,8 +950,8 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
onClick={handleDeploy}
|
||||
disabled={
|
||||
isDeploying ||
|
||||
(selectedProvider.type === 'npanel' && !user) ||
|
||||
(selectedProvider.type === 'npanel' && !isNpanelFormValid) ||
|
||||
(selectedProvider.type === 'shakespeare' && !user) ||
|
||||
(selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) ||
|
||||
(selectedProvider.type === 'nsite' && !user) ||
|
||||
(selectedProvider.type === 'nsite' && !nsiteForm.dTag) ||
|
||||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
|
||||
@@ -1050,14 +978,6 @@ export function DeploySteps({ projectId, projectName, onClose }: DeployStepsProp
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{migratingProvider && (
|
||||
<NpanelMigrationDialog
|
||||
open
|
||||
onOpenChange={(open) => !open && setMigratingProvider(null)}
|
||||
provider={migratingProvider}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,267 +0,0 @@
|
||||
import { useState, useEffect, useRef, useCallback } from 'react';
|
||||
import { AlertCircle, Check, Loader2 } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
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;
|
||||
/**
|
||||
* Open the list of names this gateway is holding for whoever signs in.
|
||||
*
|
||||
* Passed in rather than opened here: recognising one name is usually not the
|
||||
* whole of what somebody has waiting, and the dialog that hands them all back
|
||||
* belongs above this field rather than inside it.
|
||||
*/
|
||||
onTakeBackSites?: () => void;
|
||||
}
|
||||
|
||||
/** What the field is currently saying about the name in it. */
|
||||
type NameState =
|
||||
| { kind: 'empty' }
|
||||
| { kind: 'mine' }
|
||||
| { kind: 'waiting' }
|
||||
| { kind: 'checking' }
|
||||
| { kind: 'free' }
|
||||
| { kind: 'unavailable'; message: string };
|
||||
|
||||
function describe(availability: NameAvailability, domain: string): NameState {
|
||||
// A name the gateway recognises as this user's own. It is spoken for, and
|
||||
// they are who it is spoken for by — deploying updates the site already
|
||||
// there rather than taking anything.
|
||||
if (availability.reason === 'mine') return { kind: 'mine' };
|
||||
|
||||
// Theirs from before the gateway, and still held for them. Not somewhere
|
||||
// they can deploy until they take it back, which is a thing they can do
|
||||
// from here rather than a wall.
|
||||
if (availability.reason === 'waiting') return { kind: 'waiting' };
|
||||
|
||||
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,
|
||||
onTakeBackSites,
|
||||
}: NpanelDeployFormProps) {
|
||||
const { user } = useCurrentUser();
|
||||
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. Compared trimmed, since that is what gets deployed: a
|
||||
// trailing space is not a different name.
|
||||
const trimmed = subdomain.trim();
|
||||
const isOwnName = Boolean(savedSubdomain) && trimmed === savedSubdomain;
|
||||
|
||||
useEffect(() => {
|
||||
if (!trimmed) {
|
||||
setNameState({ kind: 'empty' });
|
||||
return;
|
||||
}
|
||||
if (isOwnName) {
|
||||
setNameState({ kind: 'mine' });
|
||||
return;
|
||||
}
|
||||
|
||||
setNameState({ kind: 'checking' });
|
||||
|
||||
const controller = new AbortController();
|
||||
const timer = setTimeout(async () => {
|
||||
// Signed, where there is someone to sign: a name this user owns but this
|
||||
// project has never deployed to — one they took back through the
|
||||
// migration — is otherwise indistinguishable from a stranger's.
|
||||
const availability = await checkNameAvailable(
|
||||
dashboardHost,
|
||||
`${trimmed}.${domain}`,
|
||||
controller.signal,
|
||||
user?.signer,
|
||||
);
|
||||
if (!controller.signal.aborted) setNameState(describe(availability, domain));
|
||||
}, AVAILABILITY_DEBOUNCE_MS);
|
||||
|
||||
return () => {
|
||||
controller.abort();
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [trimmed, isOwnName, dashboardHost, domain, user?.signer]);
|
||||
|
||||
// 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.
|
||||
// A name still waiting is not one to deploy to: the gateway would refuse,
|
||||
// because taking it back is what turns it into somewhere this user can
|
||||
// publish. The field says so and offers the step rather than the refusal.
|
||||
const isValid =
|
||||
subdomain.trim() !== '' && nameState.kind !== 'unavailable' && nameState.kind !== 'waiting';
|
||||
|
||||
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 === 'waiting' && (
|
||||
<div className="rounded-md border border-dashed p-3 space-y-2">
|
||||
<p className="text-sm">
|
||||
<span className="font-mono">{subdomain.trim()}.{domain}</span> is being held for you.
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
You published it before {domain} moved to this gateway. It is being served from an
|
||||
archive until you take it back, which publishes your own copy and points the name at
|
||||
it.
|
||||
</p>
|
||||
{onTakeBackSites && (
|
||||
<Button type="button" variant="outline" size="sm" onClick={onTakeBackSites}>
|
||||
Take back your sites
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{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,745 +0,0 @@
|
||||
import { useState } from 'react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import { AlertCircle, Check, ExternalLink, Eye, Loader2, Rocket, Tag, Trash2 } from 'lucide-react';
|
||||
import type { LucideIcon } from 'lucide-react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNpanelClaims, type NpanelClaimPlan, type NpanelTakenSite } from '@/hooks/useNpanelClaims';
|
||||
import type { NpanelProvider } from '@/contexts/DeploySettingsContext';
|
||||
import { claimNpanelHostname, deleteNpanelClaim } from '@/lib/deploy/npanelApi';
|
||||
import {
|
||||
NAMED_SITE_KIND,
|
||||
nsitePreviewUrl,
|
||||
republishTags,
|
||||
retitleTags,
|
||||
sitePreviewUrl,
|
||||
} from '@/lib/deploy/npanelMigration';
|
||||
import { checkRelayCoverage, forwardMissing, host, publishToRelays } from '@/lib/deploy/publishToRelays';
|
||||
|
||||
/** Where a single name has got to. */
|
||||
type RowStatus =
|
||||
| { kind: 'waiting' }
|
||||
| { kind: 'publishing' }
|
||||
| { kind: 'claiming' }
|
||||
| { kind: 'deleting' }
|
||||
| { kind: 'deleted'; note?: string }
|
||||
| { kind: 'done'; partial?: string }
|
||||
| { kind: 'failed'; error: string };
|
||||
|
||||
/** A name a person has asked to delete, and has not confirmed yet. */
|
||||
interface PendingDeletion {
|
||||
hostname: string;
|
||||
/** Whether a copy of the site is published under their own key. */
|
||||
published: boolean;
|
||||
}
|
||||
|
||||
/** What the last coverage run found, as a sentence per relay. */
|
||||
interface CoverageReport {
|
||||
lines: string[];
|
||||
}
|
||||
|
||||
interface NpanelMigrationDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
provider: NpanelProvider;
|
||||
}
|
||||
|
||||
function describeStep(claim: NpanelClaimPlan): string {
|
||||
switch (claim.step.kind) {
|
||||
case 'claim':
|
||||
return claim.step.reason === 'mine'
|
||||
? 'Already published under your key — only the record changes.'
|
||||
: 'You already publish a site under this name; the address will point at it.';
|
||||
case 'republish':
|
||||
return 'A copy will be published under your key, then the name repointed.';
|
||||
case 'blocked':
|
||||
return claim.step.reason;
|
||||
}
|
||||
}
|
||||
|
||||
/** The `d` tag of an event, which for a named site is the site's identifier. */
|
||||
function eventIdentifier(event: NostrEvent): string {
|
||||
return event.tags.find(([name]) => name === 'd')?.[1] ?? '';
|
||||
}
|
||||
|
||||
/** "took 3 of 5 relays", where that is worth saying. */
|
||||
function coverageNote(accepted: string[], rejected: { url: string; reason: string }[]): string | undefined {
|
||||
if (!rejected.length) return undefined;
|
||||
const total = accepted.length + rejected.length;
|
||||
return `${accepted.length} of ${total} relays took it — ${host(rejected[0].url)}: ${rejected[0].reason}`;
|
||||
}
|
||||
|
||||
export function NpanelMigrationDialog({ open, onOpenChange, provider }: NpanelMigrationDialogProps) {
|
||||
const { user } = useCurrentUser();
|
||||
const { nostr } = useNostr();
|
||||
const queryClient = useQueryClient();
|
||||
const { data, isLoading, error } = useNpanelClaims(open ? provider : undefined);
|
||||
|
||||
const [statuses, setStatuses] = useState<Record<string, RowStatus>>({});
|
||||
const [running, setRunning] = useState<null | 'migrate' | 'titles' | 'coverage' | 'row'>(null);
|
||||
const [coverage, setCoverage] = useState<CoverageReport | null>(null);
|
||||
const [confirming, setConfirming] = useState<PendingDeletion | null>(null);
|
||||
/** Whether anything has happened that the cached lists do not know about. */
|
||||
const [dirty, setDirty] = useState(false);
|
||||
|
||||
const claims = data?.waiting ?? [];
|
||||
const actionable = claims.filter((claim) => claim.step.kind !== 'blocked');
|
||||
const blocked = claims.filter((claim) => claim.step.kind === 'blocked');
|
||||
|
||||
const retitlable = (data?.taken ?? []).filter((site) => site.needsTitle && !site.stray);
|
||||
const strays = (data?.taken ?? []).filter((site) => site.stray);
|
||||
|
||||
const done = Object.values(statuses).filter((status) => status.kind === 'done').length;
|
||||
const deleted = Object.values(statuses).filter((status) => status.kind === 'deleted').length;
|
||||
const failed = Object.values(statuses).filter((status) => status.kind === 'failed').length;
|
||||
|
||||
const setStatus = (hostname: string, status: RowStatus) => {
|
||||
setStatuses((previous) => ({ ...previous, [hostname]: status }));
|
||||
};
|
||||
|
||||
/** Whether a row has already reached a state no further action applies to. */
|
||||
const settled = (hostname: string): boolean => {
|
||||
const kind = statuses[hostname]?.kind;
|
||||
return kind === 'done' || kind === 'deleted';
|
||||
};
|
||||
|
||||
/**
|
||||
* Take back one name.
|
||||
*
|
||||
* Publish before claiming, always: a hostname pointed at an event the gateway
|
||||
* has never seen serves nothing until it catches up, and the order that gap
|
||||
* is smallest in is this one.
|
||||
*/
|
||||
const migrate = async (claim: NpanelClaimPlan): Promise<void> => {
|
||||
if (!user || claim.step.kind === 'blocked') return;
|
||||
|
||||
let address: string;
|
||||
let note: string | undefined;
|
||||
|
||||
if (claim.step.kind === 'republish') {
|
||||
setStatus(claim.hostname, { kind: 'publishing' });
|
||||
|
||||
const event = await user.signer.signEvent({
|
||||
kind: NAMED_SITE_KIND,
|
||||
content: claim.step.manifest.content,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
tags: republishTags(claim.step.manifest, claim.step.identifier, {
|
||||
title: claim.suggestedTitle,
|
||||
description: claim.suggestedDescription,
|
||||
}),
|
||||
});
|
||||
|
||||
const published = await publishToRelays(nostr, event, provider.relayUrls);
|
||||
note = coverageNote(published.accepted, published.rejected);
|
||||
|
||||
address = `${NAMED_SITE_KIND}:${user.pubkey}:${claim.step.identifier}`;
|
||||
} else {
|
||||
address = claim.step.address;
|
||||
}
|
||||
|
||||
setStatus(claim.hostname, { kind: 'claiming' });
|
||||
await claimNpanelHostname(provider.dashboardHost, user.signer, claim.hostname, address);
|
||||
setStatus(claim.hostname, { kind: 'done', partial: note });
|
||||
};
|
||||
|
||||
/** Republish one already-claimed site under the name it chose for itself. */
|
||||
const retitle = async (site: NpanelTakenSite): Promise<void> => {
|
||||
if (!user) return;
|
||||
|
||||
setStatus(site.hostname, { kind: 'publishing' });
|
||||
|
||||
const event = await user.signer.signEvent({
|
||||
kind: site.event.kind,
|
||||
content: site.event.content,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
tags: retitleTags(site.event, {
|
||||
title: site.suggestedTitle,
|
||||
description: site.suggestedDescription,
|
||||
}),
|
||||
});
|
||||
|
||||
const published = await publishToRelays(nostr, event, provider.relayUrls);
|
||||
setStatus(site.hostname, {
|
||||
kind: 'done',
|
||||
partial: coverageNote(published.accepted, published.rejected),
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Give a name up rather than take it back.
|
||||
*
|
||||
* Only npanel forgets anything. The archive's manifest stays on relays under
|
||||
* the archive's key, and a copy published under the user's own key stays
|
||||
* theirs — what ends is this gateway serving the name and holding it for
|
||||
* them. Saying otherwise in the confirmation would be a promise nothing here
|
||||
* can keep.
|
||||
*/
|
||||
const removeClaim = async (hostname: string): Promise<void> => {
|
||||
if (!user) return;
|
||||
|
||||
setStatus(hostname, { kind: 'deleting' });
|
||||
await deleteNpanelClaim(provider.dashboardHost, user.signer, hostname);
|
||||
setStatus(hostname, { kind: 'deleted' });
|
||||
};
|
||||
|
||||
/**
|
||||
* Undo a manifest published for a name that can never load.
|
||||
*
|
||||
* Both halves, because there is no useful middle state: a relay is asked to
|
||||
* forget the event, and the gateway to forget the name. Keeping the record
|
||||
* for a hostname whose TLS handshake has always failed and always will would
|
||||
* leave a row in this list forever with nothing to do about it.
|
||||
*
|
||||
* The gateway going second is deliberate — it is the recoverable half. A
|
||||
* deletion request cannot be taken back, so it is the one that has to be
|
||||
* worth making on its own.
|
||||
*/
|
||||
const removeStray = async (site: NpanelTakenSite): Promise<void> => {
|
||||
if (!user) return;
|
||||
|
||||
setStatus(site.hostname, { kind: 'publishing' });
|
||||
|
||||
const deletion = await user.signer.signEvent({
|
||||
kind: 5,
|
||||
content: 'Published for a hostname no certificate can cover.',
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
tags: [
|
||||
['e', site.event.id],
|
||||
['a', `${site.event.kind}:${user.pubkey}:${eventIdentifier(site.event)}`],
|
||||
['k', String(site.event.kind)],
|
||||
],
|
||||
});
|
||||
|
||||
await publishToRelays(nostr, deletion, provider.relayUrls);
|
||||
await removeClaim(site.hostname);
|
||||
setStatus(site.hostname, { kind: 'deleted', note: 'Retracted, and taken off the gateway.' });
|
||||
};
|
||||
|
||||
/** Run `action` over `rows`, one at a time, recording failures per row. */
|
||||
const runEach = async <T,>(
|
||||
rows: T[],
|
||||
key: (row: T) => string,
|
||||
action: (row: T) => Promise<void>,
|
||||
): Promise<void> => {
|
||||
for (const row of rows) {
|
||||
if (settled(key(row))) continue;
|
||||
|
||||
try {
|
||||
await action(row);
|
||||
} catch (err) {
|
||||
setStatus(key(row), {
|
||||
kind: 'failed',
|
||||
error: err instanceof Error ? err.message : 'Failed',
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* One row's action, on its own.
|
||||
*
|
||||
* Still holds the whole dialog while it runs. A signer answers one request at
|
||||
* a time whatever the UI allows, and two buttons that look live but queue
|
||||
* behind each other read as a hang.
|
||||
*/
|
||||
const runRow = async (hostname: string, action: () => Promise<void>): Promise<void> => {
|
||||
setRunning('row');
|
||||
|
||||
try {
|
||||
await action();
|
||||
// Deliberately not refetched here. Somebody clearing out twenty sites
|
||||
// clicks twenty times, and re-reading the list after each one would cost
|
||||
// a signature and a relay round trip to learn what the row already says.
|
||||
// The list is caught up when the dialog closes.
|
||||
setDirty(true);
|
||||
} catch (err) {
|
||||
setStatus(hostname, { kind: 'failed', error: err instanceof Error ? err.message : 'Failed' });
|
||||
}
|
||||
|
||||
setRunning(null);
|
||||
};
|
||||
|
||||
const migrateAll = async () => {
|
||||
setRunning('migrate');
|
||||
// One at a time: a remote signer answers one request at a time anyway, and
|
||||
// a failure halfway through should leave a list somebody can read rather
|
||||
// than a hundred simultaneous errors.
|
||||
await runEach(actionable, (claim) => claim.hostname, migrate);
|
||||
setRunning(null);
|
||||
setDirty(true);
|
||||
// Whatever succeeded is no longer waiting, and whatever failed still is.
|
||||
queryClient.invalidateQueries({ queryKey: ['npanel-claims'] });
|
||||
};
|
||||
|
||||
const fixTitles = async () => {
|
||||
setRunning('titles');
|
||||
await runEach(retitlable, (site) => site.hostname, retitle);
|
||||
setRunning(null);
|
||||
setDirty(true);
|
||||
queryClient.invalidateQueries({ queryKey: ['npanel-claims'] });
|
||||
};
|
||||
|
||||
/**
|
||||
* Fill in the relays that are missing these manifests.
|
||||
*
|
||||
* Costs no signatures: the events go out exactly as they are, ids and
|
||||
* signatures unchanged, so a relay that already has one says `duplicate:`
|
||||
* and a relay that refused before says why.
|
||||
*/
|
||||
const fixCoverage = async () => {
|
||||
const events = data?.events ?? [];
|
||||
if (!events.length) return;
|
||||
|
||||
setRunning('coverage');
|
||||
setCoverage(null);
|
||||
|
||||
try {
|
||||
const found = await checkRelayCoverage(
|
||||
nostr,
|
||||
provider.relayUrls,
|
||||
events.map((event) => event.id),
|
||||
);
|
||||
const result = await forwardMissing(nostr, found, events);
|
||||
|
||||
const lines = found.map((relay) => {
|
||||
const had = relay.present.size;
|
||||
const sent = result.filled.get(relay.url) ?? 0;
|
||||
const why = result.refused.get(relay.url);
|
||||
|
||||
if (why) return `${host(relay.url)}: had ${had} of ${events.length}, refused the rest — ${why}`;
|
||||
if (sent) return `${host(relay.url)}: had ${had} of ${events.length}, sent ${sent} more`;
|
||||
return `${host(relay.url)}: has all ${events.length}`;
|
||||
});
|
||||
|
||||
setCoverage({ lines });
|
||||
} catch (err) {
|
||||
setCoverage({ lines: [err instanceof Error ? err.message : 'Could not check relay coverage.'] });
|
||||
}
|
||||
|
||||
setRunning(null);
|
||||
};
|
||||
|
||||
const renderStatus = (hostname: string, fallback: string) => {
|
||||
const status = statuses[hostname] ?? { kind: 'waiting' as const };
|
||||
|
||||
switch (status.kind) {
|
||||
case 'publishing':
|
||||
return (
|
||||
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<Loader2 className="h-3 w-3 animate-spin" /> Publishing…
|
||||
</span>
|
||||
);
|
||||
case 'claiming':
|
||||
return (
|
||||
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<Loader2 className="h-3 w-3 animate-spin" /> Claiming…
|
||||
</span>
|
||||
);
|
||||
case 'deleting':
|
||||
return (
|
||||
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<Loader2 className="h-3 w-3 animate-spin" /> Deleting…
|
||||
</span>
|
||||
);
|
||||
case 'deleted':
|
||||
return (
|
||||
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<Check className="h-3 w-3 shrink-0" />
|
||||
{status.note ?? `Deleted from ${provider.domain}.`}
|
||||
</span>
|
||||
);
|
||||
case 'done':
|
||||
return (
|
||||
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<Check className="h-3 w-3 shrink-0" />
|
||||
{status.partial ? (
|
||||
<span>{status.partial}</span>
|
||||
) : (
|
||||
<a
|
||||
href={`https://${hostname}`}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="flex items-center gap-1 hover:text-foreground"
|
||||
>
|
||||
Yours <ExternalLink className="h-3 w-3" />
|
||||
</a>
|
||||
)}
|
||||
</span>
|
||||
);
|
||||
case 'failed':
|
||||
return <span className="text-xs text-destructive">{status.error}</span>;
|
||||
case 'waiting':
|
||||
return <span className="text-xs text-muted-foreground">{fallback}</span>;
|
||||
}
|
||||
};
|
||||
|
||||
const busy = running !== null;
|
||||
|
||||
/** Names still worth running the bulk button over. */
|
||||
const remaining = actionable.filter((claim) => !settled(claim.hostname)).length;
|
||||
|
||||
/**
|
||||
* Where this sitting has got to, said once.
|
||||
*
|
||||
* Deleting is reported alongside taking names back rather than folded into
|
||||
* it, because they are opposite decisions and somebody who has just made
|
||||
* thirty of them should be able to see that they did.
|
||||
*/
|
||||
const summary = (() => {
|
||||
const parts: string[] = [];
|
||||
if (done) parts.push(`${done} done`);
|
||||
if (deleted) parts.push(`${deleted} deleted`);
|
||||
if (failed) parts.push(`${failed} failed`);
|
||||
|
||||
if (failed) return `${parts.join(', ')} — try the failed ones again.`;
|
||||
if (parts.length) {
|
||||
return `${parts.join(', ')}. A republished site takes the gateway about a minute to pick up.`;
|
||||
}
|
||||
return `${remaining} to migrate.`;
|
||||
})();
|
||||
|
||||
/**
|
||||
* Close, and let the lists catch up.
|
||||
*
|
||||
* Marked stale rather than refetched: the query is disabled while the dialog
|
||||
* is shut, so nothing is asked until somebody opens it again — and asking
|
||||
* costs a signature, which on a remote signer costs a round trip.
|
||||
*/
|
||||
const close = () => {
|
||||
if (dirty) {
|
||||
queryClient.invalidateQueries({ queryKey: ['npanel-claims'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['npanel-claim-count'] });
|
||||
}
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
/**
|
||||
* What can be done about one name, minus whatever does not apply to it.
|
||||
*
|
||||
* Every row gets its own controls rather than only the bulk button, because
|
||||
* the list is not a queue of decisions already made. Somebody with forty
|
||||
* names on file wants three of them back and the rest gone, and until now the
|
||||
* only thing the dialog would do was hand them all forty.
|
||||
*/
|
||||
const renderActions = (
|
||||
hostname: string,
|
||||
options: {
|
||||
/** Where the site can be looked at, when anywhere can show it. */
|
||||
preview?: string;
|
||||
/** The one thing this row's section does to a name that is staying. */
|
||||
act?: { label: string; icon: LucideIcon; run: () => Promise<void> };
|
||||
/** Present when the name can be given up. `published` decides what the confirmation promises. */
|
||||
deletable?: { published: boolean };
|
||||
},
|
||||
) => {
|
||||
const gone = settled(hostname);
|
||||
const ActionIcon = options.act?.icon;
|
||||
|
||||
return (
|
||||
<div className="shrink-0 flex items-center gap-1">
|
||||
{options.preview && (
|
||||
<Button size="sm" variant="ghost" className="h-8 px-2 text-muted-foreground" asChild>
|
||||
<a href={options.preview} target="_blank" rel="noreferrer">
|
||||
<Eye className="h-4 w-4 sm:mr-1.5" />
|
||||
<span className="hidden sm:inline">Show</span>
|
||||
</a>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{options.act && ActionIcon && !gone && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="h-8 px-2"
|
||||
disabled={busy}
|
||||
onClick={() => runRow(hostname, options.act!.run)}
|
||||
>
|
||||
<ActionIcon className="h-4 w-4 sm:mr-1.5" />
|
||||
<span className="hidden sm:inline">{options.act.label}</span>
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{options.deletable && !gone && (
|
||||
<Button
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="h-8 px-2 text-muted-foreground hover:text-destructive"
|
||||
disabled={busy}
|
||||
aria-label={`Delete ${hostname}`}
|
||||
onClick={() => setConfirming({ hostname, published: options.deletable!.published })}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={busy ? undefined : (next) => (next ? onOpenChange(true) : close())}>
|
||||
<DialogContent className="max-w-2xl max-h-[85vh] flex flex-col">
|
||||
<DialogHeader className="shrink-0">
|
||||
<DialogTitle>Take back your sites</DialogTitle>
|
||||
<DialogDescription>
|
||||
These names on {provider.domain} were yours before this gateway took the domain over.
|
||||
They are being served from an archive key until you publish your own copy.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex-1 overflow-y-auto space-y-6 py-2">
|
||||
{isLoading && (
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-12 w-full" />
|
||||
<Skeleton className="h-12 w-full" />
|
||||
<Skeleton className="h-12 w-full" />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
<AlertDescription>{error.message}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{data && !claims.length && !data.taken.length && (
|
||||
<p className="text-sm text-muted-foreground py-8 text-center">
|
||||
Nothing is waiting for you here.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{actionable.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-sm font-medium">Waiting for you</h4>
|
||||
<div className="rounded-md border divide-y">
|
||||
{actionable.map((claim) => (
|
||||
<div key={claim.hostname} className="flex items-center justify-between gap-3 p-3">
|
||||
<div className="min-w-0">
|
||||
<div className="font-mono text-sm truncate">{claim.hostname}</div>
|
||||
<div className="truncate">{renderStatus(claim.hostname, describeStep(claim))}</div>
|
||||
</div>
|
||||
{renderActions(claim.hostname, {
|
||||
preview: sitePreviewUrl(claim.address, claim.hostname, provider.domain),
|
||||
// The word the button uses is the work it does. A name
|
||||
// whose site is already on this key publishes nothing.
|
||||
act: {
|
||||
label: claim.step.kind === 'republish' ? 'Publish' : 'Claim',
|
||||
icon: Rocket,
|
||||
run: () => migrate(claim),
|
||||
},
|
||||
// A `claim` step, either reason, means a copy of the site
|
||||
// is already published under this key and survives the
|
||||
// name going away. A `republish` step means it is not.
|
||||
deletable: { published: claim.step.kind === 'claim' },
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{retitlable.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-end justify-between gap-4">
|
||||
<div>
|
||||
<h4 className="text-sm font-medium">Titled after their address</h4>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
The archive could only call a site by its hostname. These say what they are
|
||||
actually called, so the name they publish under can too.
|
||||
</p>
|
||||
</div>
|
||||
<Button size="sm" variant="outline" onClick={fixTitles} disabled={busy}>
|
||||
{running === 'titles' ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Fix titles'}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="rounded-md border divide-y">
|
||||
{retitlable.map((site) => (
|
||||
<div key={site.hostname} className="flex items-center justify-between gap-3 p-3">
|
||||
<div className="min-w-0">
|
||||
<div className="font-mono text-sm truncate">{site.hostname}</div>
|
||||
<div className="truncate">
|
||||
{renderStatus(
|
||||
site.hostname,
|
||||
site.suggestedTitle ? `Will be titled "${site.suggestedTitle}".` : 'The title will be removed.',
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{renderActions(site.hostname, {
|
||||
preview: sitePreviewUrl(
|
||||
`${site.event.kind}:${site.event.pubkey}:${eventIdentifier(site.event)}`,
|
||||
site.hostname,
|
||||
provider.domain,
|
||||
),
|
||||
act: { label: 'Retitle', icon: Tag, run: () => retitle(site) },
|
||||
deletable: { published: true },
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{(data?.events.length ?? 0) > 0 && (
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-end justify-between gap-4">
|
||||
<div>
|
||||
<h4 className="text-sm font-medium">Relay coverage</h4>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
A site is only as findable as the relays holding its manifest. This sends the
|
||||
events you already published to the relays that do not have them — same events,
|
||||
no signing.
|
||||
</p>
|
||||
</div>
|
||||
<Button size="sm" variant="outline" onClick={fixCoverage} disabled={busy}>
|
||||
{running === 'coverage' ? <Loader2 className="h-4 w-4 animate-spin" /> : 'Check relays'}
|
||||
</Button>
|
||||
</div>
|
||||
{coverage && (
|
||||
<div className="rounded-md border bg-muted/30 p-3 space-y-1">
|
||||
{coverage.lines.map((line) => (
|
||||
<p key={line} className="text-xs font-mono text-muted-foreground break-words">
|
||||
{line}
|
||||
</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{strays.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-sm font-medium">Published for a name that cannot load</h4>
|
||||
<div className="rounded-md border border-dashed divide-y">
|
||||
{strays.map((site) => (
|
||||
<div key={site.hostname} className="flex items-center justify-between gap-3 p-3">
|
||||
<div className="min-w-0 space-y-0.5">
|
||||
<div className="font-mono text-sm truncate">{site.hostname}</div>
|
||||
<div className="truncate">
|
||||
{renderStatus(
|
||||
site.hostname,
|
||||
`No certificate covers a name this deep under ${provider.domain}.`,
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{/*
|
||||
One button, not two. What is wrong with these is that
|
||||
they exist at all, so there is no version of retracting
|
||||
the manifest that leaves the gateway's record worth
|
||||
keeping — the name has never loaded for anyone and never
|
||||
will. The hostname is unservable, so the preview can only
|
||||
come from the address.
|
||||
*/}
|
||||
{renderActions(site.hostname, {
|
||||
preview: nsitePreviewUrl(
|
||||
`${site.event.kind}:${site.event.pubkey}:${eventIdentifier(site.event)}`,
|
||||
),
|
||||
act: { label: 'Retract', icon: Trash2, run: () => removeStray(site) },
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{blocked.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-sm font-medium">Needs a decision</h4>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Nothing here can be taken back safely without you choosing something first. Deleting
|
||||
is a decision too, and for most of these it is the right one.
|
||||
</p>
|
||||
<div className="rounded-md border border-dashed divide-y">
|
||||
{blocked.map((claim) => (
|
||||
<div key={claim.hostname} className="flex items-center justify-between gap-3 p-3">
|
||||
<div className="min-w-0 space-y-0.5">
|
||||
<div className="font-mono text-sm truncate">{claim.hostname}</div>
|
||||
<div className="truncate">{renderStatus(claim.hostname, describeStep(claim))}</div>
|
||||
</div>
|
||||
{renderActions(claim.hostname, {
|
||||
preview: sitePreviewUrl(claim.address, claim.hostname, provider.domain),
|
||||
deletable: { published: claim.mine },
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter className="shrink-0 gap-2 sm:justify-between items-center">
|
||||
<span className="text-xs text-muted-foreground">{summary}</span>
|
||||
<div className="flex gap-2">
|
||||
<Button variant="outline" onClick={() => close()} disabled={busy}>
|
||||
Close
|
||||
</Button>
|
||||
<Button onClick={migrateAll} disabled={busy || remaining === 0}>
|
||||
{running === 'migrate' ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Migrating…
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Rocket className="h-4 w-4 mr-2" />
|
||||
{failed > 0 ? 'Retry' : `Migrate all (${remaining})`}
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
<AlertDialog open={confirming !== null} onOpenChange={(next) => !next && setConfirming(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete {confirming?.hostname}?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
{provider.name} stops serving this name and stops holding it for you, and it goes back
|
||||
to being anybody's to take. This cannot be undone.{' '}
|
||||
{confirming?.published
|
||||
? 'The site itself stays published under your key, and can still be reached by its address.'
|
||||
: 'The archived copy stays on Nostr under the key that published it — this only ends the gateway serving it.'}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
onClick={() => {
|
||||
const hostname = confirming?.hostname;
|
||||
setConfirming(null);
|
||||
if (hostname) void runRow(hostname, () => removeClaim(hostname));
|
||||
}}
|
||||
>
|
||||
Delete
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
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,20 +5,10 @@ export interface BaseDeployProvider {
|
||||
name: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 ShakespeareDeployProvider extends BaseDeployProvider {
|
||||
type: 'shakespeare';
|
||||
host?: string;
|
||||
proxy?: boolean;
|
||||
}
|
||||
|
||||
export interface NetlifyProvider extends BaseDeployProvider {
|
||||
@@ -67,7 +57,7 @@ export interface RailwayProvider extends BaseDeployProvider {
|
||||
proxy?: boolean;
|
||||
}
|
||||
|
||||
export type DeployProvider = NpanelProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider | RailwayProvider;
|
||||
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider | RailwayProvider;
|
||||
|
||||
export interface DeploySettings {
|
||||
providers: DeployProvider[];
|
||||
|
||||
+1
-11
@@ -2,7 +2,6 @@ import { useState, useCallback } from 'react';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { LN } from '@getalby/sdk';
|
||||
import { assertInvoiceAmount } from '@/lib/bolt11';
|
||||
|
||||
export interface NWCConnection {
|
||||
connectionString: string;
|
||||
@@ -160,21 +159,12 @@ export function useNWCInternal() {
|
||||
// Send payment using the SDK
|
||||
const sendPayment = useCallback(async (
|
||||
connection: NWCConnection,
|
||||
invoice: string,
|
||||
/**
|
||||
* Amount in millisatoshis the user approved. The wallet is handed only the
|
||||
* invoice, so this is the last point at which the sum the user agreed to
|
||||
* and the sum the invoice charges can be compared — without it, whoever
|
||||
* issued the invoice decides how much leaves the wallet.
|
||||
*/
|
||||
expectedAmountMsat: number,
|
||||
invoice: string
|
||||
): Promise<{ preimage: string }> => {
|
||||
if (!connection.connectionString) {
|
||||
throw new Error('Invalid connection: missing connection string');
|
||||
}
|
||||
|
||||
assertInvoiceAmount(invoice, expectedAmountMsat);
|
||||
|
||||
let client: LN;
|
||||
try {
|
||||
client = new LN(connection.connectionString);
|
||||
|
||||
@@ -1,192 +0,0 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import type { NpanelProvider } from '@/contexts/DeploySettingsContext';
|
||||
import {
|
||||
fetchNpanelClaimCount,
|
||||
fetchNpanelClaims,
|
||||
type NpanelClaim,
|
||||
type NpanelClaimCount,
|
||||
} from '@/lib/deploy/npanelApi';
|
||||
import {
|
||||
NAMED_SITE_KIND,
|
||||
hasArchiveTitle,
|
||||
isServableHostname,
|
||||
manifestIdentifier,
|
||||
planClaim,
|
||||
type MigrationStep,
|
||||
} from '@/lib/deploy/npanelMigration';
|
||||
|
||||
/** How long the relay round trip for one's own sites is given. */
|
||||
const RELAY_TIMEOUT_MS = 6_000;
|
||||
|
||||
/** A waiting name, with what it would take to get it back. */
|
||||
export interface NpanelClaimPlan extends NpanelClaim {
|
||||
step: MigrationStep;
|
||||
}
|
||||
|
||||
/** A name already taken back, and the event currently serving it. */
|
||||
export interface NpanelTakenSite {
|
||||
hostname: string;
|
||||
/** The claimant's own manifest, as relays hold it right now. */
|
||||
event: NostrEvent;
|
||||
/** What the site calls itself, per the gateway. Null when it never said. */
|
||||
suggestedTitle: string | null;
|
||||
suggestedDescription: string | null;
|
||||
/** Whether the event is still titled after its hostname. */
|
||||
needsTitle: boolean;
|
||||
/** A name no certificate can cover, which should never have been published. */
|
||||
stray: boolean;
|
||||
}
|
||||
|
||||
export interface NpanelClaims {
|
||||
/** Names still waiting, each with a plan. */
|
||||
waiting: NpanelClaimPlan[];
|
||||
/** Names already taken back whose manifest could be improved or removed. */
|
||||
taken: NpanelTakenSite[];
|
||||
/** Every event of the user's this query saw, for checking relay coverage. */
|
||||
events: NostrEvent[];
|
||||
}
|
||||
|
||||
/** The `identifier` half of a `kind:pubkey:identifier` address. */
|
||||
function addressIdentifier(address: string): string {
|
||||
return address.split(':').slice(2).join(':');
|
||||
}
|
||||
|
||||
/** The `d` tag of an event, which for a named site is the site's identifier. */
|
||||
function eventIdentifier(event: NostrEvent): string {
|
||||
return event.tags.find(([name]) => name === 'd')?.[1] ?? '';
|
||||
}
|
||||
|
||||
/**
|
||||
* The names waiting for the logged-in user on a gateway, and what each needs.
|
||||
*
|
||||
* Half the answer comes from relays rather than the gateway: to know whether a
|
||||
* name can simply be repointed, one has to know which sites this user already
|
||||
* publishes, and that is on the network, not in npanel. The same query answers
|
||||
* two more questions at no extra cost — which taken names are still titled
|
||||
* after their hostname, and which of them should never have been published at
|
||||
* all — so it is made once and its events are kept.
|
||||
*/
|
||||
export function useNpanelClaims(provider: NpanelProvider | undefined) {
|
||||
const { user } = useCurrentUser();
|
||||
const { nostr } = useNostr();
|
||||
|
||||
return useQuery<NpanelClaims>({
|
||||
queryKey: ['npanel-claims', provider?.dashboardHost, user?.pubkey],
|
||||
enabled: Boolean(provider && user),
|
||||
// Nobody's list of waiting names changes on its own, and every refetch
|
||||
// costs a signature — which on a remote signer costs a round trip.
|
||||
staleTime: 5 * 60 * 1000,
|
||||
refetchOnWindowFocus: false,
|
||||
retry: false,
|
||||
queryFn: async ({ signal }) => {
|
||||
const empty: NpanelClaims = { waiting: [], taken: [], events: [] };
|
||||
if (!provider || !user) return empty;
|
||||
|
||||
const claims = await fetchNpanelClaims(provider.dashboardHost, user.signer, signal, { taken: true });
|
||||
if (!claims.length) return empty;
|
||||
|
||||
// Only the names actually in play are asked about, rather than every
|
||||
// site this key has ever published.
|
||||
const wanted = new Set<string>();
|
||||
for (const claim of claims) {
|
||||
const identifier = claim.manifest ? manifestIdentifier(claim.manifest) : '';
|
||||
if (identifier) wanted.add(identifier);
|
||||
if (claim.address) wanted.add(addressIdentifier(claim.address));
|
||||
}
|
||||
wanted.delete('');
|
||||
|
||||
const events = wanted.size
|
||||
? await nostr.group(provider.relayUrls).query(
|
||||
[{ kinds: [NAMED_SITE_KIND], authors: [user.pubkey], '#d': [...wanted] }],
|
||||
{ signal: AbortSignal.any([signal, AbortSignal.timeout(RELAY_TIMEOUT_MS)]) },
|
||||
)
|
||||
: [];
|
||||
|
||||
const byIdentifier = new Map<string, NostrEvent>();
|
||||
for (const event of events) {
|
||||
const identifier = eventIdentifier(event);
|
||||
if (!identifier) continue;
|
||||
const seen = byIdentifier.get(identifier);
|
||||
if (!seen || seen.created_at < event.created_at) byIdentifier.set(identifier, event);
|
||||
}
|
||||
const published = new Set(byIdentifier.keys());
|
||||
|
||||
// A name npanel serves from this user's own key is a site this user
|
||||
// published, so relays that know nothing about any of them are relays
|
||||
// that are not answering. Planning against that silence would mean
|
||||
// republishing over live sites, so it fails loudly instead.
|
||||
const known = claims
|
||||
.filter((claim) => claim.mine && claim.address)
|
||||
.map((claim) => addressIdentifier(claim.address ?? ''))
|
||||
.filter(Boolean);
|
||||
|
||||
if (known.length && !known.some((identifier) => published.has(identifier))) {
|
||||
throw new Error(
|
||||
'Relays did not answer with the sites you already publish, so it is not safe to work out what needs republishing. Try again in a moment.',
|
||||
);
|
||||
}
|
||||
|
||||
const waiting: NpanelClaimPlan[] = [];
|
||||
const taken: NpanelTakenSite[] = [];
|
||||
|
||||
for (const claim of claims) {
|
||||
if (!claim.claimed) {
|
||||
waiting.push({ ...claim, step: planClaim(claim, user.pubkey, published, provider.domain) });
|
||||
continue;
|
||||
}
|
||||
|
||||
const identifier = claim.address ? addressIdentifier(claim.address) : '';
|
||||
const event = identifier ? byIdentifier.get(identifier) : undefined;
|
||||
// A claimed name whose event no relay answered with is not a name with
|
||||
// nothing wrong; it is a name nothing can be said about. Leaving it out
|
||||
// is the only option that cannot make it worse.
|
||||
if (!event) continue;
|
||||
|
||||
const stray = !isServableHostname(claim.hostname, provider.domain);
|
||||
|
||||
taken.push({
|
||||
hostname: claim.hostname,
|
||||
event,
|
||||
suggestedTitle: claim.suggestedTitle ?? null,
|
||||
suggestedDescription: claim.suggestedDescription ?? null,
|
||||
needsTitle: hasArchiveTitle(event, claim.hostname),
|
||||
stray,
|
||||
});
|
||||
}
|
||||
|
||||
return { waiting, taken, events: [...byIdentifier.values()] };
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* How many names a gateway is holding for the logged-in user.
|
||||
*
|
||||
* Separate from {@link useNpanelClaims} because it is asked at a different
|
||||
* moment and must cost a different amount. That one runs when somebody opens
|
||||
* the dialog and has already decided to look; it reads every claimed deploy on
|
||||
* the gateway and queries relays for this user's own events. This one runs
|
||||
* because a settings page was opened, so it is one signature and two counted
|
||||
* rows, and a gateway that cannot answer it says nothing rather than failing.
|
||||
*/
|
||||
export function useNpanelClaimCount(provider: NpanelProvider | undefined) {
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
return useQuery<NpanelClaimCount>({
|
||||
queryKey: ['npanel-claim-count', provider?.dashboardHost, user?.pubkey],
|
||||
enabled: Boolean(provider && user),
|
||||
// Nobody's list of waiting names changes on its own, and every refetch
|
||||
// costs a signature — which on a remote signer costs a round trip. Long
|
||||
// enough that opening settings twice in a sitting asks once.
|
||||
staleTime: 30 * 60 * 1000,
|
||||
refetchOnWindowFocus: false,
|
||||
retry: false,
|
||||
queryFn: async ({ signal }) => {
|
||||
if (!provider || !user) return { waiting: 0, taken: 0 };
|
||||
return await fetchNpanelClaimCount(provider.dashboardHost, user.signer, signal);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -3,14 +3,11 @@ import { z } from 'zod';
|
||||
import { useFS } from './useFS';
|
||||
import { useFSPaths } from './useFSPaths';
|
||||
|
||||
const npanelProjectConfigSchema = z.object({
|
||||
type: z.literal('npanel'),
|
||||
const shakespeareProjectConfigSchema = z.object({
|
||||
type: z.literal('shakespeare'),
|
||||
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(),
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -74,7 +71,7 @@ const railwayProjectConfigSchema = z.object({
|
||||
});
|
||||
|
||||
const projectProviderConfigSchema = z.discriminatedUnion('type', [
|
||||
npanelProjectConfigSchema,
|
||||
shakespeareProjectConfigSchema,
|
||||
nsiteProjectConfigSchema,
|
||||
netlifyProjectConfigSchema,
|
||||
vercelProjectConfigSchema,
|
||||
@@ -88,7 +85,7 @@ const projectDeploySettingsSchema = z.object({
|
||||
currentProvider: z.string().optional(),
|
||||
});
|
||||
|
||||
export type NpanelProjectConfig = z.infer<typeof npanelProjectConfigSchema>;
|
||||
export type ShakespeareProjectConfig = z.infer<typeof shakespeareProjectConfigSchema>;
|
||||
export type NsiteProjectConfig = z.infer<typeof nsiteProjectConfigSchema>;
|
||||
export type NetlifyProjectConfig = z.infer<typeof netlifyProjectConfigSchema>;
|
||||
export type VercelProjectConfig = z.infer<typeof vercelProjectConfigSchema>;
|
||||
@@ -98,24 +95,6 @@ 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
|
||||
@@ -139,20 +118,10 @@ export function useProjectDeploySettings(projectId: string | null) {
|
||||
try {
|
||||
setIsLoading(true);
|
||||
const content = await fs.fs.readFile(settingsPath, 'utf8');
|
||||
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),
|
||||
]),
|
||||
),
|
||||
};
|
||||
const parsed = JSON.parse(content as string);
|
||||
|
||||
// Validate with Zod
|
||||
const validated = projectDeploySettingsSchema.parse(migrated);
|
||||
const validated = projectDeploySettingsSchema.parse(parsed);
|
||||
setSettings(validated);
|
||||
} catch (error) {
|
||||
// File doesn't exist, is invalid JSON, or doesn't match schema - use empty settings
|
||||
|
||||
+8
-54
@@ -11,8 +11,6 @@ import type { WebLNProvider } from 'webln';
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import { assertInvoiceAmount, invoiceCommitsTo } from '@/lib/bolt11';
|
||||
import { resolveLnurlPay, type LnurlPayParams } from '@/lib/lnurlPay';
|
||||
|
||||
export function useZaps(
|
||||
target: Event | Event[],
|
||||
@@ -182,19 +180,12 @@ export function useZaps(
|
||||
return;
|
||||
}
|
||||
|
||||
// Resolve the recipient's LNURL-pay endpoint in-repo instead of via
|
||||
// nip57.getZapEndpoint, which returns only the callback URL and discards
|
||||
// the minSendable/maxSendable bounds and metadata needed to validate the
|
||||
// invoice we get back.
|
||||
let lnurlParams: LnurlPayParams;
|
||||
try {
|
||||
lnurlParams = await resolveLnurlPay({ lud06, lud16 });
|
||||
} catch (endpointError) {
|
||||
// Get zap endpoint using the old reliable method
|
||||
const zapEndpoint = await nip57.getZapEndpoint(author.data.event);
|
||||
if (!zapEndpoint) {
|
||||
toast({
|
||||
title: 'Zap endpoint not found',
|
||||
description: endpointError instanceof Error
|
||||
? endpointError.message
|
||||
: 'Could not find a zap endpoint for the author.',
|
||||
description: 'Could not find a zap endpoint for the author.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
setIsZapping(false);
|
||||
@@ -203,20 +194,6 @@ export function useZaps(
|
||||
|
||||
const zapAmount = amount * 1000; // convert to millisats
|
||||
|
||||
// The endpoint advertises what it will accept; asking for anything
|
||||
// outside that range can only produce an invoice we'd have to reject.
|
||||
if (zapAmount < lnurlParams.minSendable || zapAmount > lnurlParams.maxSendable) {
|
||||
toast({
|
||||
title: 'Amount out of range',
|
||||
description:
|
||||
`This lightning address accepts between ${Math.ceil(lnurlParams.minSendable / 1000)} and ` +
|
||||
`${Math.floor(lnurlParams.maxSendable / 1000)} sats.`,
|
||||
variant: 'destructive',
|
||||
});
|
||||
setIsZapping(false);
|
||||
return;
|
||||
}
|
||||
|
||||
const writeRelays = config.relayMetadata.relays
|
||||
.filter(r => r.write)
|
||||
.map(r => r.url);
|
||||
@@ -232,14 +209,9 @@ export function useZaps(
|
||||
throw new Error('No signer available');
|
||||
}
|
||||
const signedZapRequest = await user.signer.signEvent(zapRequest);
|
||||
const zapRequestJson = JSON.stringify(signedZapRequest);
|
||||
|
||||
try {
|
||||
const zapUrl = new URL(lnurlParams.callback);
|
||||
zapUrl.searchParams.set('amount', String(zapAmount));
|
||||
zapUrl.searchParams.set('nostr', zapRequestJson);
|
||||
|
||||
const res = await fetch(zapUrl.toString());
|
||||
const res = await fetch(`${zapEndpoint}?amount=${zapAmount}&nostr=${encodeURI(JSON.stringify(signedZapRequest))}`);
|
||||
const responseData = await res.json();
|
||||
|
||||
if (!res.ok) {
|
||||
@@ -251,31 +223,13 @@ export function useZaps(
|
||||
throw new Error('Lightning service did not return a valid invoice');
|
||||
}
|
||||
|
||||
// The endpoint that produced this invoice is chosen by the recipient,
|
||||
// so the invoice is not trusted: decode it and require that it charges
|
||||
// exactly what the user approved. Without this, the recipient — not the
|
||||
// sender — decides how much the sender pays. Throwing here aborts
|
||||
// before any wallet is touched, on every payment path.
|
||||
const decodedInvoice = assertInvoiceAmount(newInvoice, zapAmount);
|
||||
|
||||
// LUD-06 binds the invoice to the endpoint's `metadata`; NIP-57 binds
|
||||
// it to the zap request instead. Either is fine, anything else means
|
||||
// the invoice was not issued for this request.
|
||||
if (!invoiceCommitsTo(decodedInvoice, [zapRequestJson, lnurlParams.metadata])) {
|
||||
throw new Error('Lightning service returned an invoice for a different request. Payment cancelled.');
|
||||
}
|
||||
|
||||
// Report what the invoice actually charges rather than what was asked
|
||||
// for, so a success screen can never understate a spend.
|
||||
const paidSats = Math.round(decodedInvoice.amountMsat / 1000);
|
||||
|
||||
// Get the current active NWC connection dynamically
|
||||
const currentNWCConnection = getActiveConnection();
|
||||
|
||||
// Try NWC first if available and properly connected
|
||||
if (currentNWCConnection && currentNWCConnection.connectionString && currentNWCConnection.isConnected) {
|
||||
try {
|
||||
await sendPayment(currentNWCConnection, newInvoice, zapAmount);
|
||||
await sendPayment(currentNWCConnection, newInvoice);
|
||||
|
||||
// Clear states immediately on success
|
||||
setIsZapping(false);
|
||||
@@ -283,7 +237,7 @@ export function useZaps(
|
||||
|
||||
toast({
|
||||
title: 'Zap successful!',
|
||||
description: `You sent ${paidSats} sats via NWC to the author.`,
|
||||
description: `You sent ${amount} sats via NWC to the author.`,
|
||||
});
|
||||
|
||||
// Invalidate zap queries to refresh counts
|
||||
@@ -315,7 +269,7 @@ export function useZaps(
|
||||
|
||||
toast({
|
||||
title: 'Zap successful!',
|
||||
description: `You sent ${paidSats} sats to the author.`,
|
||||
description: `You sent ${amount} sats to the author.`,
|
||||
});
|
||||
|
||||
// Invalidate zap queries to refresh counts
|
||||
|
||||
@@ -7,8 +7,6 @@ export interface PresetProvider {
|
||||
tosURL?: string;
|
||||
proxy?: boolean;
|
||||
openSecret?: string;
|
||||
/** Default API key for providers where the key is a required placeholder */
|
||||
apiKey?: string;
|
||||
}
|
||||
|
||||
export const AI_PROVIDER_PRESETS: PresetProvider[] = [
|
||||
@@ -108,12 +106,4 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [
|
||||
tosURL: "https://vercel.com/legal/terms",
|
||||
proxy: true,
|
||||
},
|
||||
{
|
||||
// Local Anthropic/OpenAI-compatible bridge; authenticates via the
|
||||
// Claude Code SDK. The API key is a placeholder — any value works.
|
||||
id: "meridian",
|
||||
name: "Meridian",
|
||||
baseURL: "http://127.0.0.1:3456/v1",
|
||||
apiKey: "x",
|
||||
},
|
||||
];
|
||||
];
|
||||
@@ -1,115 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
|
||||
import { assertInvoiceAmount, decodeBolt11, invoiceCommitsTo } from './bolt11';
|
||||
|
||||
// BOLT 11 specification test vectors.
|
||||
/** 2500u = 250,000,000 msat, with a plain-text description. */
|
||||
const INVOICE_2500U =
|
||||
'lnbc2500u1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypq' +
|
||||
'dq5xysxxatsyp3k7enxv4jsxqzpuaztrnwngzn3kdzw5hydlzf03qdgm2hdq27cqv3agm2aw' +
|
||||
'hz5se903vruatfhq77w3ls4evs3ch9zw97j25emudupq63nyw24cg27h2rspfj9srp';
|
||||
|
||||
/** No amount in the human-readable part — the payer or payee picks the sum. */
|
||||
const INVOICE_AMOUNTLESS =
|
||||
'lnbc1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqdpl2p' +
|
||||
'kx2ctnv5sxxmmwwd5kgetjypeh2ursdae8g6twvus8g6rfwvs8qun0dfjkxaq8rkx3yf5tcs' +
|
||||
'yz3d73gafnh3cax9rn449d9p5uxz9ezhhypd0elx87sjle52x86fux2ypatgddc6k63n7erq' +
|
||||
'z25le42c4u4ecky03ylcqca784w';
|
||||
|
||||
/** 20m = 2,000,000,000 msat, carrying a description hash rather than text. */
|
||||
const INVOICE_20M_WITH_HASH =
|
||||
'lnbc20m1pvjluezpp5qqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqqqsyqcyq5rqwzqfqypqhp' +
|
||||
'58yjmdan79s6qqdhdzgynm4zwqd5d7xmw5fk98klysy043l2ahrqscc6gd6ql3jrc5yzme8v' +
|
||||
'4ntcewwz5cnw92tz0pc8qcuufvq7khhr8wpald05e92xw006sq94mg8v2ndf4sefvf9sygks' +
|
||||
'hp5zfem29trqq2yxxz7';
|
||||
|
||||
/** The string whose sha256 is the description hash in {@link INVOICE_20M_WITH_HASH}. */
|
||||
const HASHED_DESCRIPTION =
|
||||
'One piece of chocolate cake, one icecream cone, one pickle, one slice of swiss cheese, ' +
|
||||
'one slice of salami, one lollypop, one piece of cherry pie, one sausage, one cupcake, ' +
|
||||
'and one slice of watermelon';
|
||||
|
||||
describe('decodeBolt11', () => {
|
||||
it('decodes the amount from the human-readable part', () => {
|
||||
expect(decodeBolt11(INVOICE_2500U).amountMsat).toBe(250_000_000);
|
||||
expect(decodeBolt11(INVOICE_20M_WITH_HASH).amountMsat).toBe(2_000_000_000);
|
||||
});
|
||||
|
||||
it('reports an amountless invoice as null rather than zero', () => {
|
||||
expect(decodeBolt11(INVOICE_AMOUNTLESS).amountMsat).toBeNull();
|
||||
});
|
||||
|
||||
it('reads the network, timestamp and payment hash', () => {
|
||||
const decoded = decodeBolt11(INVOICE_2500U);
|
||||
expect(decoded.network).toBe('bc');
|
||||
expect(decoded.timestamp).toBe(1496314658);
|
||||
expect(decoded.paymentHash).toBe(
|
||||
'0001020304050607080900010203040506070809000102030405060708090102',
|
||||
);
|
||||
});
|
||||
|
||||
it('reads the plain-text description', () => {
|
||||
expect(decodeBolt11(INVOICE_2500U).description).toBe('1 cup coffee');
|
||||
});
|
||||
|
||||
it('reads the description hash', () => {
|
||||
expect(decodeBolt11(INVOICE_20M_WITH_HASH).descriptionHash).toHaveLength(64);
|
||||
});
|
||||
|
||||
it('tolerates a lightning: URI prefix, whitespace and uppercase', () => {
|
||||
expect(decodeBolt11(` LIGHTNING:${INVOICE_2500U.toUpperCase()} `).amountMsat).toBe(250_000_000);
|
||||
});
|
||||
|
||||
it('rejects a string that is not an invoice', () => {
|
||||
expect(() => decodeBolt11('not-an-invoice')).toThrow();
|
||||
expect(() => decodeBolt11('')).toThrow();
|
||||
});
|
||||
|
||||
it('rejects an invoice whose checksum has been tampered with', () => {
|
||||
// Flip the last character of the bech32 checksum.
|
||||
const tampered = INVOICE_2500U.slice(0, -1) + (INVOICE_2500U.endsWith('p') ? 'q' : 'p');
|
||||
expect(() => decodeBolt11(tampered)).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('assertInvoiceAmount', () => {
|
||||
it('accepts an invoice for exactly the requested amount', () => {
|
||||
expect(assertInvoiceAmount(INVOICE_2500U, 250_000_000).amountMsat).toBe(250_000_000);
|
||||
});
|
||||
|
||||
it('rejects an invoice for more than was requested', () => {
|
||||
// The reported attack: the user approves 776 sats and the recipient's own
|
||||
// LNURL server answers with an invoice for 5,000,000 sats.
|
||||
expect(() => assertInvoiceAmount(INVOICE_2500U, 776_000)).toThrow(/250000 sats.*776 sats/);
|
||||
});
|
||||
|
||||
it('rejects an invoice for less than was requested', () => {
|
||||
expect(() => assertInvoiceAmount(INVOICE_2500U, 250_000_001)).toThrow();
|
||||
});
|
||||
|
||||
it('rejects an amountless invoice, which would let the wallet pick the sum', () => {
|
||||
expect(() => assertInvoiceAmount(INVOICE_AMOUNTLESS, 250_000_000)).toThrow(/no amount/);
|
||||
});
|
||||
|
||||
it('rejects an unparseable invoice rather than passing it through', () => {
|
||||
expect(() => assertInvoiceAmount('lnbc-garbage', 1000)).toThrow(/unreadable/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('invoiceCommitsTo', () => {
|
||||
it('accepts an invoice whose description hash matches a candidate', () => {
|
||||
const decoded = decodeBolt11(INVOICE_20M_WITH_HASH);
|
||||
expect(invoiceCommitsTo(decoded, ['something else', HASHED_DESCRIPTION])).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects an invoice bound to a different request', () => {
|
||||
const decoded = decodeBolt11(INVOICE_20M_WITH_HASH);
|
||||
expect(invoiceCommitsTo(decoded, ['a different zap request'])).toBe(false);
|
||||
});
|
||||
|
||||
it('accepts an invoice with no description hash at all', () => {
|
||||
// Many providers use a plain `d` description; the amount check is what
|
||||
// stops an overcharge, this is only defence in depth.
|
||||
expect(invoiceCommitsTo(decodeBolt11(INVOICE_2500U), ['anything'])).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -1,258 +0,0 @@
|
||||
/**
|
||||
* BOLT11 lightning invoice decoding.
|
||||
*
|
||||
* This is an *authentication* decoder, not a display heuristic: before any
|
||||
* wallet is asked to pay an invoice we have to know exactly what that invoice
|
||||
* commits to. `nip57.getSatoshisAmountFromBolt11` reads the human-readable
|
||||
* part of a string that is assumed to already be an invoice — it will happily
|
||||
* report an amount for a string that is not a valid invoice at all, and it
|
||||
* cannot see the tagged fields. Use {@link decodeBolt11} for anything that
|
||||
* moves money.
|
||||
*
|
||||
* Built on `@scure/base` + `@noble/hashes`, both already in the entry bundle
|
||||
* via `nostr-tools`, so this adds no new dependency.
|
||||
*
|
||||
* Reference: BOLT 11, "Invoice Protocol for Lightning Payments".
|
||||
*/
|
||||
import { bech32 } from '@scure/base';
|
||||
import { sha256 } from '@noble/hashes/sha256';
|
||||
import { bytesToHex, utf8ToBytes } from '@noble/hashes/utils';
|
||||
|
||||
/** A decoded BOLT11 invoice. Only the fields we need are surfaced. */
|
||||
export interface DecodedInvoice {
|
||||
/**
|
||||
* Amount in millisatoshis, or `null` when the invoice is *amountless* —
|
||||
* meaning the payer or the payee chooses the sum. Never pay an amountless
|
||||
* invoice on the user's behalf.
|
||||
*/
|
||||
amountMsat: number | null;
|
||||
/** Network prefix from the human-readable part: `bc`, `tb`, `bcrt`, `sb`. */
|
||||
network: string;
|
||||
/** Hex 32-byte payment hash (`p` field). */
|
||||
paymentHash?: string;
|
||||
/** Hex 32-byte description hash (`h` field), if the invoice carries one. */
|
||||
descriptionHash?: string;
|
||||
/** Plain-text description (`d` field), if the invoice carries one. */
|
||||
description?: string;
|
||||
/** Hex 33-byte payee node id (`n` field), if the invoice carries one. */
|
||||
payee?: string;
|
||||
/** Invoice creation time, in Unix seconds. */
|
||||
timestamp: number;
|
||||
/** Seconds after {@link timestamp} that the invoice expires. */
|
||||
expiry: number;
|
||||
}
|
||||
|
||||
/** Millisatoshis in one bitcoin. */
|
||||
const MSAT_PER_BTC = 100_000_000_000n;
|
||||
|
||||
/**
|
||||
* BOLT11 amount multipliers, as the divisor applied to {@link MSAT_PER_BTC}.
|
||||
* `p` (pico) divides to 1/10 msat, so pico amounts must be a multiple of 10.
|
||||
*/
|
||||
const MULTIPLIERS: Record<string, bigint> = {
|
||||
m: 1_000n,
|
||||
u: 1_000_000n,
|
||||
n: 1_000_000_000n,
|
||||
p: 1_000_000_000_000n,
|
||||
};
|
||||
|
||||
/** `ln` + network + optional amount. Longer prefixes first (`bcrt` vs `bc`). */
|
||||
const HRP_RE = /^ln(bcrt|bc|tbs|tb|sb)(?:(\d+)([munp])?)?$/;
|
||||
|
||||
/** BOLT11 tagged-field types, as bech32 word values. */
|
||||
const TAG_PAYMENT_HASH = 1; // 'p'
|
||||
const TAG_DESCRIPTION = 13; // 'd'
|
||||
const TAG_PAYEE = 19; // 'n'
|
||||
const TAG_DESCRIPTION_HASH = 23; // 'h'
|
||||
const TAG_EXPIRY = 6; // 'x'
|
||||
|
||||
/** Words occupied by the trailing signature (65 bytes = 520 bits). */
|
||||
const SIGNATURE_WORDS = 104;
|
||||
/** Words occupied by the leading timestamp (35 bits). */
|
||||
const TIMESTAMP_WORDS = 7;
|
||||
|
||||
/** BOLT11's default expiry when no `x` field is present. */
|
||||
const DEFAULT_EXPIRY = 3600;
|
||||
|
||||
/**
|
||||
* Pack 5-bit bech32 words into bytes, discarding any trailing bits that do
|
||||
* not complete a byte. BOLT11 fields are not all byte-aligned (a 32-byte hash
|
||||
* occupies 52 words = 260 bits), so `bech32.fromWords` — which rejects
|
||||
* leftover bits — cannot be used here.
|
||||
*/
|
||||
function wordsToBytes(words: number[]): Uint8Array {
|
||||
const out = new Uint8Array(Math.floor((words.length * 5) / 8));
|
||||
let acc = 0;
|
||||
let bits = 0;
|
||||
let i = 0;
|
||||
for (const word of words) {
|
||||
acc = (acc << 5) | word;
|
||||
bits += 5;
|
||||
while (bits >= 8) {
|
||||
bits -= 8;
|
||||
out[i++] = (acc >> bits) & 0xff;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Read a big-endian integer out of 5-bit words. */
|
||||
function wordsToInt(words: number[]): number {
|
||||
let value = 0;
|
||||
for (const word of words) {
|
||||
value = value * 32 + word;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
/** Parse the amount out of a BOLT11 human-readable part, in millisatoshis. */
|
||||
function parseHrpAmount(digits: string | undefined, multiplier: string | undefined): number | null {
|
||||
if (!digits) return null;
|
||||
|
||||
const value = BigInt(digits);
|
||||
const divisor = multiplier ? MULTIPLIERS[multiplier] : 1n;
|
||||
const numerator = value * MSAT_PER_BTC;
|
||||
|
||||
if (numerator % divisor !== 0n) {
|
||||
// Sub-millisatoshi precision. BOLT11 forbids it, and we can't pay it.
|
||||
throw new Error('Invalid BOLT11 invoice: amount is not a whole number of millisatoshis');
|
||||
}
|
||||
|
||||
const msat = numerator / divisor;
|
||||
if (msat > BigInt(Number.MAX_SAFE_INTEGER)) {
|
||||
throw new Error('Invalid BOLT11 invoice: amount is implausibly large');
|
||||
}
|
||||
|
||||
return Number(msat);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decode a BOLT11 invoice, verifying its bech32 checksum and structure.
|
||||
*
|
||||
* Throws on anything that is not a well-formed invoice. The signature is not
|
||||
* checked — verifying it would only prove the invoice was signed by whoever
|
||||
* the invoice itself names as payee, which tells us nothing we didn't already
|
||||
* decide by choosing to talk to that endpoint. What matters to callers is the
|
||||
* *amount* and the *description hash*, both of which are covered here.
|
||||
*/
|
||||
export function decodeBolt11(invoice: string): DecodedInvoice {
|
||||
const trimmed = invoice.trim().replace(/^lightning:/i, '');
|
||||
const lowered = trimmed.toLowerCase();
|
||||
|
||||
if (!lowered.startsWith('ln')) {
|
||||
throw new Error('Invalid BOLT11 invoice: missing "ln" prefix');
|
||||
}
|
||||
|
||||
// `false` disables bech32's 90-character limit, which invoices exceed.
|
||||
const { prefix, words } = bech32.decode(lowered as `${Lowercase<string>}1${string}`, false);
|
||||
|
||||
const hrp = HRP_RE.exec(prefix);
|
||||
if (!hrp) {
|
||||
throw new Error('Invalid BOLT11 invoice: unrecognized prefix');
|
||||
}
|
||||
|
||||
const [, network, digits, multiplier] = hrp;
|
||||
const amountMsat = parseHrpAmount(digits, multiplier);
|
||||
|
||||
if (words.length < TIMESTAMP_WORDS + SIGNATURE_WORDS) {
|
||||
throw new Error('Invalid BOLT11 invoice: truncated');
|
||||
}
|
||||
|
||||
const timestamp = wordsToInt(words.slice(0, TIMESTAMP_WORDS));
|
||||
const tagged = words.slice(TIMESTAMP_WORDS, words.length - SIGNATURE_WORDS);
|
||||
|
||||
const decoded: DecodedInvoice = { amountMsat, network, timestamp, expiry: DEFAULT_EXPIRY };
|
||||
|
||||
for (let i = 0; i + 3 <= tagged.length;) {
|
||||
const type = tagged[i];
|
||||
const length = tagged[i + 1] * 32 + tagged[i + 2];
|
||||
const start = i + 3;
|
||||
const end = start + length;
|
||||
if (end > tagged.length) {
|
||||
throw new Error('Invalid BOLT11 invoice: tagged field overruns the invoice');
|
||||
}
|
||||
const data = tagged.slice(start, end);
|
||||
i = end;
|
||||
|
||||
switch (type) {
|
||||
case TAG_PAYMENT_HASH:
|
||||
if (length === 52) decoded.paymentHash = bytesToHex(wordsToBytes(data));
|
||||
break;
|
||||
case TAG_DESCRIPTION_HASH:
|
||||
if (length === 52) decoded.descriptionHash = bytesToHex(wordsToBytes(data));
|
||||
break;
|
||||
case TAG_PAYEE:
|
||||
if (length === 53) decoded.payee = bytesToHex(wordsToBytes(data));
|
||||
break;
|
||||
case TAG_DESCRIPTION:
|
||||
decoded.description = new TextDecoder().decode(wordsToBytes(data));
|
||||
break;
|
||||
case TAG_EXPIRY:
|
||||
decoded.expiry = wordsToInt(data);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return decoded;
|
||||
}
|
||||
|
||||
/**
|
||||
* Assert that `invoice` is payable for exactly `expectedMsat`.
|
||||
*
|
||||
* LNURL-pay endpoints are chosen by the *recipient*, so the invoice they hand
|
||||
* back is attacker-controlled whenever the recipient is hostile. Without this
|
||||
* check the recipient — not the sender — decides how much the sender pays.
|
||||
*
|
||||
* Returns the decoded invoice so callers can report the amount they actually
|
||||
* paid rather than the one they asked for.
|
||||
*/
|
||||
export function assertInvoiceAmount(
|
||||
invoice: string,
|
||||
expectedMsat: number,
|
||||
): DecodedInvoice & { amountMsat: number } {
|
||||
let decoded: DecodedInvoice;
|
||||
try {
|
||||
decoded = decodeBolt11(invoice);
|
||||
} catch (error) {
|
||||
throw new Error(
|
||||
`Lightning service returned an unreadable invoice: ${
|
||||
error instanceof Error ? error.message : 'unknown error'
|
||||
}`,
|
||||
);
|
||||
}
|
||||
|
||||
if (decoded.amountMsat === null) {
|
||||
throw new Error(
|
||||
'Lightning service returned an invoice with no amount, which would let it charge any sum. Payment cancelled.',
|
||||
);
|
||||
}
|
||||
|
||||
if (decoded.amountMsat !== expectedMsat) {
|
||||
throw new Error(
|
||||
`Lightning service returned an invoice for ${Math.round(decoded.amountMsat / 1000)} sats, ` +
|
||||
`but ${Math.round(expectedMsat / 1000)} sats was requested. Payment cancelled.`,
|
||||
);
|
||||
}
|
||||
|
||||
return { ...decoded, amountMsat: decoded.amountMsat };
|
||||
}
|
||||
|
||||
/**
|
||||
* Check an invoice's `h` field against the strings it is allowed to commit to.
|
||||
*
|
||||
* LUD-06 binds the invoice to the LNURL endpoint's `metadata`; NIP-57 replaces
|
||||
* that with the zap request JSON. Providers implement one or the other, so any
|
||||
* match is accepted. An invoice with no `h` field at all is accepted too —
|
||||
* plenty of providers use a plain `d` description — because the amount check
|
||||
* is what actually stops an overcharge; this is defence in depth against a
|
||||
* substituted invoice on an otherwise honest response.
|
||||
*/
|
||||
export function invoiceCommitsTo(decoded: DecodedInvoice, candidates: string[]): boolean {
|
||||
if (!decoded.descriptionHash) return true;
|
||||
|
||||
// Use noble's own `utf8ToBytes` rather than `TextEncoder`: under jsdom the
|
||||
// latter returns a Uint8Array from a different realm, which `sha256` rejects.
|
||||
return candidates.some(
|
||||
(candidate) => bytesToHex(sha256(utf8ToBytes(candidate))) === decoded.descriptionHash,
|
||||
);
|
||||
}
|
||||
@@ -11,7 +11,6 @@ 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 => ({
|
||||
@@ -279,11 +278,7 @@ describe('configUtils', () => {
|
||||
{
|
||||
id: 'provider-3',
|
||||
name: 'Shakespeare',
|
||||
type: 'npanel',
|
||||
dashboardHost: 'npanel.shakespeare.to',
|
||||
domain: 'shakespeare.wtf',
|
||||
relayUrls: ['wss://relay.ditto.pub'],
|
||||
blossomServers: ['https://blossom.ditto.pub'],
|
||||
type: 'shakespeare',
|
||||
},
|
||||
{
|
||||
id: 'provider-4',
|
||||
@@ -305,38 +300,13 @@ describe('configUtils', () => {
|
||||
expect(result).toEqual(sampleDeploySettings);
|
||||
});
|
||||
|
||||
it('should offer the default provider when no settings have been saved', async () => {
|
||||
it('should return default settings if file does not exist', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
|
||||
|
||||
const result = await readDeploySettings(mockFS);
|
||||
|
||||
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',
|
||||
expect(result).toEqual({
|
||||
providers: [],
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
+12
-36
@@ -1,7 +1,6 @@
|
||||
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';
|
||||
@@ -91,12 +90,9 @@ const baseDeployProviderSchema = z.object({
|
||||
proxy: z.boolean().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 shakespeareDeployProviderSchema = baseDeployProviderSchema.extend({
|
||||
type: z.literal('shakespeare'),
|
||||
host: z.string().optional(),
|
||||
});
|
||||
|
||||
const netlifyProviderSchema = baseDeployProviderSchema.extend({
|
||||
@@ -141,7 +137,7 @@ const railwayProviderSchema = baseDeployProviderSchema.extend({
|
||||
});
|
||||
|
||||
const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('type', [
|
||||
npanelProviderSchema,
|
||||
shakespeareDeployProviderSchema,
|
||||
netlifyProviderSchema,
|
||||
vercelProviderSchema,
|
||||
nsiteProviderSchema,
|
||||
@@ -318,44 +314,24 @@ 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 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] };
|
||||
}
|
||||
const defaultSettings: DeploySettings = {
|
||||
providers: [],
|
||||
};
|
||||
|
||||
try {
|
||||
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);
|
||||
const deployConfigPath = getDeployConfigPath(configPath);
|
||||
const content = await fs.readFile(deployConfigPath, 'utf8');
|
||||
const data = JSON.parse(content);
|
||||
return deploySettingsSchema.parse(data);
|
||||
} 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 { providers: [] };
|
||||
return defaultSettings;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,302 +0,0 @@
|
||||
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,
|
||||
});
|
||||
});
|
||||
|
||||
it('asks again as the signer when a name comes back taken', async () => {
|
||||
// "Taken" and "taken by you" are the same word to a stranger and opposite
|
||||
// answers to the person about to deploy.
|
||||
fetchMock
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ hostname: `x.${DOMAIN}`, available: false, reason: 'taken' })),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ hostname: `x.${DOMAIN}`, available: true, reason: 'mine' })),
|
||||
);
|
||||
|
||||
await expect(
|
||||
checkNameAvailable(DASHBOARD_HOST, `x.${DOMAIN}`, undefined, signer),
|
||||
).resolves.toMatchObject({ available: true, reason: 'mine' });
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
|
||||
// The first ask carries nothing; only the second spends a signature.
|
||||
const [, anonymous] = fetchMock.mock.calls[0];
|
||||
expect((anonymous as RequestInit | undefined)?.headers).toBeUndefined();
|
||||
|
||||
const signed = fetchMock.mock.calls[1][0] as Request;
|
||||
expect(signed.headers.get('Authorization')).toMatch(/^Nostr /);
|
||||
expect(signed.url).toBe(`https://${DASHBOARD_HOST}/api/hosts/x.${DOMAIN}/available`);
|
||||
});
|
||||
|
||||
it('spends no signature on a name that is free', async () => {
|
||||
// Picking a new name is the common case, and a remote signer on the other
|
||||
// end of every keystroke is not something to spend it on.
|
||||
fetchMock.mockResolvedValue(new Response(JSON.stringify({ hostname: 'x', available: true })));
|
||||
|
||||
await checkNameAvailable(DASHBOARD_HOST, `x.${DOMAIN}`, undefined, signer);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('keeps the public answer when the gateway is too old to know better', async () => {
|
||||
fetchMock
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ hostname: `x.${DOMAIN}`, available: false, reason: 'taken' })),
|
||||
)
|
||||
.mockResolvedValueOnce(new Response('nope', { status: 404 }));
|
||||
|
||||
await expect(
|
||||
checkNameAvailable(DASHBOARD_HOST, `x.${DOMAIN}`, undefined, signer),
|
||||
).resolves.toMatchObject({ available: false, reason: 'taken' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('checkNameAvailable, for a name held for its previous owner', () => {
|
||||
it('reports waiting rather than taken', async () => {
|
||||
// The state almost every unclaimed name is in: an archive serving it, so
|
||||
// the public answer is taken and the useful answer is that it is theirs.
|
||||
fetchMock
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ hostname: `x.${DOMAIN}`, available: false, reason: 'taken' })),
|
||||
)
|
||||
.mockResolvedValueOnce(
|
||||
new Response(JSON.stringify({ hostname: `x.${DOMAIN}`, available: false, reason: 'waiting' })),
|
||||
);
|
||||
|
||||
await expect(
|
||||
checkNameAvailable(DASHBOARD_HOST, `x.${DOMAIN}`, undefined, signer),
|
||||
).resolves.toMatchObject({ available: false, reason: 'waiting' });
|
||||
});
|
||||
|
||||
it('says nothing more to somebody who did not sign', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(JSON.stringify({ hostname: `x.${DOMAIN}`, available: false, reason: 'taken' })),
|
||||
);
|
||||
|
||||
await expect(checkNameAvailable(DASHBOARD_HOST, `x.${DOMAIN}`)).resolves.toMatchObject({
|
||||
reason: 'taken',
|
||||
});
|
||||
expect(fetchMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
@@ -1,180 +0,0 @@
|
||||
import type { NostrSigner } from '@nostrify/nostrify';
|
||||
import type { DeployAdapter, DeployOptions, DeployResult, NpanelDeployConfig } from './types';
|
||||
import { NsiteAdapter } from './NsiteAdapter';
|
||||
import { NPANEL_TIMEOUT_MS, npanelError, npanelRequest } from './npanelApi';
|
||||
|
||||
/** nsite named-site kind. An npanel host always points at one of these. */
|
||||
const NAMED_SITE_KIND = 35128;
|
||||
|
||||
/** What `GET /api/hosts/:hostname/available` answers. */
|
||||
export interface NameAvailability {
|
||||
hostname: string;
|
||||
available: boolean;
|
||||
/**
|
||||
* Why it is not free, or — with `available` — that it is not free of somebody
|
||||
* else.
|
||||
*
|
||||
* `mine` is a name this signer can already point somewhere. `waiting` is one
|
||||
* the gateway is holding for them from before it took the domain over: not
|
||||
* free, not theirs to deploy to yet, and one claim away from both. Both come
|
||||
* only from a signed request, and only from a gateway new enough to answer
|
||||
* one; an older one says `taken`, which is not wrong, just of no use to the
|
||||
* person the name belongs to.
|
||||
*/
|
||||
reason?: 'taken' | 'invalid' | 'mine' | 'waiting';
|
||||
/** Present when `reason` is `invalid`; written to be shown to whoever typed it. */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask whether a name can still be claimed.
|
||||
*
|
||||
* Asked anonymously first, 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 name that comes back taken is then asked about again, signed, because
|
||||
* "taken" and "taken by you" are the same answer to a stranger and opposite
|
||||
* answers to the person about to deploy. Only on that branch: a free name is the
|
||||
* common case while somebody is picking one, and signing every keystroke would
|
||||
* put a remote signer on the other end of the typing.
|
||||
*
|
||||
* 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,
|
||||
signer?: NostrSigner,
|
||||
): Promise<NameAvailability> {
|
||||
const path = `/api/hosts/${encodeURIComponent(hostname)}/available`;
|
||||
|
||||
try {
|
||||
const response = await fetch(`https://${dashboardHost}${path}`, {
|
||||
signal: signal ?? AbortSignal.timeout(NPANEL_TIMEOUT_MS),
|
||||
});
|
||||
if (!response.ok) return { hostname, available: true };
|
||||
|
||||
const availability = (await response.json()) as NameAvailability;
|
||||
if (availability.available || availability.reason !== 'taken' || !signer) return availability;
|
||||
|
||||
const asOwner = await npanelRequest(dashboardHost, signer, 'GET', path, undefined, signal);
|
||||
if (!asOwner.ok) return availability;
|
||||
|
||||
return (await asOwner.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 request(method: string, path: string, body?: unknown): Promise<Response> {
|
||||
return npanelRequest(this.dashboardHost, this.signer, method, path, body);
|
||||
}
|
||||
|
||||
/** The gateway's own sentence about a failure, which is written to be read. */
|
||||
private error(response: Response, fallback: string): Promise<Error> {
|
||||
return npanelError(response, fallback);
|
||||
}
|
||||
}
|
||||
@@ -4,7 +4,6 @@ import { nip19 } from 'nostr-tools';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
import type { DeployAdapter, DeployOptions, DeployResult, NsiteDeployConfig } from './types';
|
||||
import { buildNsiteUrl } from '../utils/nsite';
|
||||
import { publishToRelays } from './publishToRelays';
|
||||
|
||||
/** nsite v2 root-site kind (replaceable by pubkey+kind) */
|
||||
const NSITE_ROOT_SITE_KIND = 15128;
|
||||
@@ -250,8 +249,8 @@ async function runConcurrent<T>(
|
||||
* - HEAD-checks each file on each Blossom server before uploading
|
||||
* - PUTs files to Blossom servers with pre-signed auth headers
|
||||
* - Publishes a single kind-15128 (root) or kind-35128 (named) site manifest event
|
||||
* containing all ["path", "/path", sha256] tags and ["server", url] Blossom
|
||||
* hints — no separate kind 10002 or kind 10063 published
|
||||
* containing all ["path", "/path", sha256] tags, ["server", url] Blossom hints,
|
||||
* and ["relay", url] relay hints — no separate kind 10002 or kind 10063 published
|
||||
*
|
||||
* Named sites (kind 35128, siteIdentifier set):
|
||||
* URL = https://{base36pubkey}{siteIdentifier}.{gateway}
|
||||
@@ -297,6 +296,9 @@ export class NsiteAdapter implements DeployAdapter {
|
||||
const pubkey = await this.signer.getPublicKey();
|
||||
const npub = nip19.npubEncode(pubkey);
|
||||
|
||||
// Create grouped relay client
|
||||
const relayClient = this.nostr.group(this.relayUrls);
|
||||
|
||||
// ── Step 1: Walk dist/ and read + hash all files ──────────────────────────
|
||||
const files: FileEntry[] = [];
|
||||
await this.collectFiles(distPath, '', files);
|
||||
@@ -367,10 +369,8 @@ export class NsiteAdapter implements DeployAdapter {
|
||||
pathTags.push(['path', '/404.html', indexFile.sha256]);
|
||||
}
|
||||
|
||||
// NIP-5A defines no relay-hint tag for a manifest, so the relays a site was
|
||||
// published to are not written into it. Where to find the event is the
|
||||
// reader's problem and the author's kind 10002, not the manifest's.
|
||||
const serverTags: string[][] = serverBases.map(url => ['server', url]);
|
||||
const relayTags: string[][] = this.relayUrls.map(url => ['relay', url]);
|
||||
|
||||
const tags: string[][] = [];
|
||||
|
||||
@@ -379,7 +379,7 @@ export class NsiteAdapter implements DeployAdapter {
|
||||
tags.push(['d', this.siteIdentifier]);
|
||||
}
|
||||
|
||||
tags.push(...pathTags, ...serverTags);
|
||||
tags.push(...pathTags, ...serverTags, ...relayTags);
|
||||
|
||||
if (this.siteTitle) {
|
||||
tags.push(['title', this.siteTitle]);
|
||||
@@ -401,13 +401,9 @@ export class NsiteAdapter implements DeployAdapter {
|
||||
});
|
||||
|
||||
// ── Step 5: Publish manifest ──────────────────────────────────────────────
|
||||
// Blossom server hints are embedded as tags in the manifest itself —
|
||||
// Relay and server hints are embedded as tags in the manifest itself —
|
||||
// no separate kind 10002 or kind 10063 events are published.
|
||||
//
|
||||
// Relay by relay, because the site is only as findable as the relays that
|
||||
// actually took it, and publishing to the group as a whole reports success
|
||||
// the moment one of them does — throwing away what the others said.
|
||||
const publish = await publishToRelays(this.nostr, manifestEvent, this.relayUrls);
|
||||
await relayClient.event(manifestEvent, { signal: AbortSignal.timeout(10_000) });
|
||||
|
||||
// Build the canonical deployed URL (always the long-form base36 or npub URL)
|
||||
const siteUrl = buildNsiteUrl({
|
||||
@@ -437,9 +433,6 @@ export class NsiteAdapter implements DeployAdapter {
|
||||
manifestKind,
|
||||
vanityUrl,
|
||||
canonicalUrl: siteUrl,
|
||||
eventId: manifestEvent.id,
|
||||
relaysAccepted: publish.accepted,
|
||||
relaysRejected: publish.rejected,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,122 @@
|
||||
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 './NpanelAdapter';
|
||||
export * from './ShakespeareAdapter';
|
||||
export * from './NetlifyAdapter';
|
||||
export * from './VercelAdapter';
|
||||
export * from './NsiteAdapter';
|
||||
|
||||
@@ -1,87 +0,0 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
|
||||
import { getPublicKey, generateSecretKey } from 'nostr-tools';
|
||||
import type { NostrSigner } from '@nostrify/nostrify';
|
||||
import { fetchNpanelClaimCount } from './npanelApi';
|
||||
|
||||
const DASHBOARD_HOST = 'npanel.example.test';
|
||||
|
||||
const pubkey = getPublicKey(generateSecretKey());
|
||||
|
||||
/**
|
||||
* A signer that fills in the fields a real one would, without signing.
|
||||
*
|
||||
* Signing for real is 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 environment.
|
||||
* Nothing here verifies a signature — what matters is which request goes out
|
||||
* and what is made of the answer.
|
||||
*/
|
||||
const signer: NostrSigner = {
|
||||
getPublicKey: async () => pubkey,
|
||||
signEvent: async (template) => ({
|
||||
...template,
|
||||
id: 'f'.repeat(64),
|
||||
pubkey,
|
||||
sig: '0'.repeat(128),
|
||||
}),
|
||||
} as NostrSigner;
|
||||
|
||||
let fetchMock: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
fetchMock = vi.fn();
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe('fetchNpanelClaimCount', () => {
|
||||
it('asks the gateway only for the count', async () => {
|
||||
fetchMock.mockResolvedValue(new Response(JSON.stringify({ waiting: 3, taken: 1 })));
|
||||
|
||||
await expect(fetchNpanelClaimCount(DASHBOARD_HOST, signer)).resolves.toEqual({
|
||||
waiting: 3,
|
||||
taken: 1,
|
||||
});
|
||||
|
||||
const request = fetchMock.mock.calls[0][0] as Request;
|
||||
expect(request.url).toBe(`https://${DASHBOARD_HOST}/api/claims?summary=1`);
|
||||
expect(request.headers.get('Authorization')).toMatch(/^Nostr /);
|
||||
});
|
||||
|
||||
it('reports nothing waiting when the gateway answers with the list instead', async () => {
|
||||
// An older gateway ignores the parameter and returns every claim, which is
|
||||
// a different shape rather than a bigger number — counting it would be
|
||||
// inventing one.
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(JSON.stringify({ claims: [{ hostname: `a.example.test` }] })),
|
||||
);
|
||||
|
||||
await expect(fetchNpanelClaimCount(DASHBOARD_HOST, signer)).resolves.toEqual({
|
||||
waiting: 0,
|
||||
taken: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('reports nothing waiting when the gateway cannot be reached', async () => {
|
||||
// This runs because somebody opened a settings page. A number that failed
|
||||
// to arrive is not an error worth showing them.
|
||||
fetchMock.mockRejectedValue(new Error('offline'));
|
||||
|
||||
await expect(fetchNpanelClaimCount(DASHBOARD_HOST, signer)).resolves.toEqual({
|
||||
waiting: 0,
|
||||
taken: 0,
|
||||
});
|
||||
});
|
||||
|
||||
it('reports nothing waiting when the gateway refuses', async () => {
|
||||
fetchMock.mockResolvedValue(new Response('nope', { status: 403 }));
|
||||
|
||||
await expect(fetchNpanelClaimCount(DASHBOARD_HOST, signer)).resolves.toEqual({
|
||||
waiting: 0,
|
||||
taken: 0,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,210 +0,0 @@
|
||||
import { NIP98 } from '@nostrify/nostrify';
|
||||
import { N64 } from '@nostrify/nostrify/utils';
|
||||
import type { NostrSigner } from '@nostrify/nostrify';
|
||||
|
||||
/** Timeout for a single API call (ms). */
|
||||
export const NPANEL_TIMEOUT_MS = 15_000;
|
||||
|
||||
/**
|
||||
* A NIP-98 request to an npanel gateway's API.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
export async function npanelRequest(
|
||||
dashboardHost: string,
|
||||
signer: NostrSigner,
|
||||
method: string,
|
||||
path: string,
|
||||
body?: unknown,
|
||||
signal?: AbortSignal,
|
||||
): Promise<Response> {
|
||||
const url = `https://${dashboardHost}${path}`;
|
||||
|
||||
let request = new Request(url, {
|
||||
method,
|
||||
...(body === undefined
|
||||
? {}
|
||||
: { body: JSON.stringify(body), headers: { 'Content-Type': 'application/json' } }),
|
||||
});
|
||||
|
||||
const template = await NIP98.template(request);
|
||||
const event = await signer.signEvent(template);
|
||||
|
||||
const headers = new Headers(request.headers);
|
||||
headers.set('Authorization', `Nostr ${N64.encodeEvent(event)}`);
|
||||
request = new Request(request, {
|
||||
headers,
|
||||
signal: signal ?? AbortSignal.timeout(NPANEL_TIMEOUT_MS),
|
||||
});
|
||||
|
||||
return await fetch(request);
|
||||
}
|
||||
|
||||
/** The gateway's own sentence about a failure, which is written to be read. */
|
||||
export async function npanelError(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}).`);
|
||||
}
|
||||
|
||||
/** An nsite manifest, reduced to the parts that are the site. */
|
||||
export interface NpanelClaimManifest {
|
||||
kind: number;
|
||||
content: string;
|
||||
tags: string[][];
|
||||
}
|
||||
|
||||
/** A name waiting to be handed back to whoever held it before this gateway. */
|
||||
export interface NpanelClaim {
|
||||
hostname: string;
|
||||
/** Where the record came from, eg `picohost`. */
|
||||
source: string;
|
||||
/** Whether something is being served at the name right now. */
|
||||
live: boolean;
|
||||
/** Where the name points today, as `kind:pubkey:identifier`, or null if nowhere. */
|
||||
address: string | null;
|
||||
/** Whether that address is already the claimant's own key. */
|
||||
mine: boolean;
|
||||
/** The archive's copy, when there is one to republish. Null when `mine`. */
|
||||
manifest: NpanelClaimManifest | null;
|
||||
/**
|
||||
* Whether this name has already been taken back.
|
||||
*
|
||||
* Absent from gateways that predate the field, which is why it is optional
|
||||
* rather than assumed false: a list of waiting names is what `GET /api/claims`
|
||||
* has always returned, so a missing flag means the row is waiting.
|
||||
*/
|
||||
claimed?: boolean;
|
||||
/** What the site calls itself, where the gateway could work it out. */
|
||||
suggestedTitle?: string | null;
|
||||
suggestedDescription?: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The names this signer can take back from the gateway's archive.
|
||||
*
|
||||
* Empty for anyone with nothing waiting, which is almost everyone — this is the
|
||||
* residue of one migration, not a feature of the gateway.
|
||||
*
|
||||
* `taken` also returns names already claimed, which is how an app fixes
|
||||
* something about how it claimed them. Older gateways ignore the parameter and
|
||||
* answer with the waiting ones, which is a smaller answer rather than a wrong
|
||||
* one.
|
||||
*/
|
||||
export async function fetchNpanelClaims(
|
||||
dashboardHost: string,
|
||||
signer: NostrSigner,
|
||||
signal?: AbortSignal,
|
||||
opts: { taken?: boolean } = {},
|
||||
): Promise<NpanelClaim[]> {
|
||||
const path = opts.taken ? '/api/claims?taken=1' : '/api/claims';
|
||||
const response = await npanelRequest(dashboardHost, signer, 'GET', path, undefined, signal);
|
||||
|
||||
if (!response.ok) {
|
||||
throw await npanelError(response, 'Could not ask the gateway which names are waiting for you');
|
||||
}
|
||||
|
||||
const { claims } = (await response.json()) as { claims: NpanelClaim[] };
|
||||
return claims;
|
||||
}
|
||||
|
||||
/** How many names a gateway is holding for somebody, and how many they took. */
|
||||
export interface NpanelClaimCount {
|
||||
waiting: number;
|
||||
taken: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* The count alone, without working out what to do about any of them.
|
||||
*
|
||||
* {@link fetchNpanelClaims} reads every file of every claimed deploy and returns
|
||||
* a manifest each, which is the right price for the dialog that hands the names
|
||||
* back and much too high for the sentence that gets somebody to open it. A
|
||||
* gateway too old to know the parameter answers with the list instead, so the
|
||||
* shape is checked rather than assumed — and a gateway that fails outright
|
||||
* reports nothing waiting, since a number nobody can fetch should not become an
|
||||
* error on a settings page.
|
||||
*/
|
||||
export async function fetchNpanelClaimCount(
|
||||
dashboardHost: string,
|
||||
signer: NostrSigner,
|
||||
signal?: AbortSignal,
|
||||
): Promise<NpanelClaimCount> {
|
||||
const none: NpanelClaimCount = { waiting: 0, taken: 0 };
|
||||
|
||||
try {
|
||||
const response = await npanelRequest(
|
||||
dashboardHost,
|
||||
signer,
|
||||
'GET',
|
||||
'/api/claims?summary=1',
|
||||
undefined,
|
||||
signal,
|
||||
);
|
||||
if (!response.ok) return none;
|
||||
|
||||
const body = (await response.json()) as Partial<NpanelClaimCount>;
|
||||
if (typeof body.waiting !== 'number' || typeof body.taken !== 'number') return none;
|
||||
|
||||
return { waiting: body.waiting, taken: body.taken };
|
||||
} catch {
|
||||
return none;
|
||||
}
|
||||
}
|
||||
|
||||
/** Point a name waiting for this signer at a site they published. */
|
||||
export async function claimNpanelHostname(
|
||||
dashboardHost: string,
|
||||
signer: NostrSigner,
|
||||
hostname: string,
|
||||
address: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> {
|
||||
const response = await npanelRequest(
|
||||
dashboardHost,
|
||||
signer,
|
||||
'POST',
|
||||
`/api/claims/${encodeURIComponent(hostname)}`,
|
||||
{ address },
|
||||
signal,
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw await npanelError(response, `Could not take back ${hostname}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Give a name up rather than take it back.
|
||||
*
|
||||
* The gateway forgets the hostname entirely: it stops serving the archived
|
||||
* site, stops holding the name, and the name goes back to being anybody's. What
|
||||
* this cannot touch is the network — the archive's manifest is its own event
|
||||
* under its own key, and a copy the user published is theirs to retract — so
|
||||
* this is a request to one server and nothing more.
|
||||
*/
|
||||
export async function deleteNpanelClaim(
|
||||
dashboardHost: string,
|
||||
signer: NostrSigner,
|
||||
hostname: string,
|
||||
signal?: AbortSignal,
|
||||
): Promise<void> {
|
||||
const response = await npanelRequest(
|
||||
dashboardHost,
|
||||
signer,
|
||||
'DELETE',
|
||||
`/api/claims/${encodeURIComponent(hostname)}`,
|
||||
undefined,
|
||||
signal,
|
||||
);
|
||||
|
||||
if (!response.ok) {
|
||||
throw await npanelError(response, `Could not delete ${hostname}`);
|
||||
}
|
||||
}
|
||||
@@ -1,232 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import type { NpanelClaim } from './npanelApi';
|
||||
import {
|
||||
NAMED_SITE_KIND,
|
||||
ROOT_SITE_KIND,
|
||||
hasArchiveTitle,
|
||||
isServableHostname,
|
||||
nsitePreviewUrl,
|
||||
planClaim,
|
||||
republishTags,
|
||||
retitleTags,
|
||||
sitePreviewUrl,
|
||||
} from './npanelMigration';
|
||||
|
||||
const PUBKEY = 'a'.repeat(64);
|
||||
const ARCHIVE = 'b'.repeat(64);
|
||||
const DOMAIN = 'shakespeare.wtf';
|
||||
|
||||
function claim(overrides: Partial<NpanelClaim> = {}): NpanelClaim {
|
||||
return {
|
||||
hostname: 'mysite.shakespeare.wtf',
|
||||
source: 'picohost',
|
||||
live: true,
|
||||
address: `${NAMED_SITE_KIND}:${ARCHIVE}:mysite`,
|
||||
mine: false,
|
||||
manifest: {
|
||||
kind: NAMED_SITE_KIND,
|
||||
content: '',
|
||||
tags: [
|
||||
['d', 'mysite'],
|
||||
['title', 'mysite.shakespeare.wtf'],
|
||||
['alt', 'mysite.shakespeare.wtf — archived so that it keeps working.'],
|
||||
['path', '/index.html', 'c'.repeat(64)],
|
||||
['server', 'https://blossom.ditto.pub/'],
|
||||
],
|
||||
},
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
describe('planClaim', () => {
|
||||
it('only changes the record for a site already on the owner’s key', () => {
|
||||
const address = `${NAMED_SITE_KIND}:${PUBKEY}:mysite`;
|
||||
|
||||
expect(
|
||||
planClaim(claim({ mine: true, address, manifest: null }), PUBKEY, new Set(), DOMAIN),
|
||||
).toEqual({ kind: 'claim', address, reason: 'mine' });
|
||||
});
|
||||
|
||||
it('points a name at a site the owner already publishes, rather than republishing over it', () => {
|
||||
// The destructive case: kind 35128 is addressable, so publishing the
|
||||
// archive's stale copy at this `d` tag would replace the live site.
|
||||
expect(planClaim(claim(), PUBKEY, new Set(['mysite']), DOMAIN)).toEqual({
|
||||
kind: 'claim',
|
||||
address: `${NAMED_SITE_KIND}:${PUBKEY}:mysite`,
|
||||
reason: 'published',
|
||||
});
|
||||
});
|
||||
|
||||
it('republishes the archived manifest when nothing is published under that name', () => {
|
||||
const step = planClaim(claim(), PUBKEY, new Set(['something-else']), DOMAIN);
|
||||
|
||||
expect(step.kind).toBe('republish');
|
||||
expect(step).toMatchObject({ identifier: 'mysite' });
|
||||
});
|
||||
|
||||
it('refuses a root site, which would replace the owner’s main site', () => {
|
||||
const rooted = claim({ manifest: { kind: 15128, content: '', tags: [] } });
|
||||
|
||||
expect(planClaim(rooted, PUBKEY, new Set(), DOMAIN).kind).toBe('blocked');
|
||||
});
|
||||
|
||||
it('has nothing to do for a reservation whose site never made it across', () => {
|
||||
const empty = claim({ live: false, address: null, manifest: null });
|
||||
|
||||
expect(planClaim(empty, PUBKEY, new Set(), DOMAIN).kind).toBe('blocked');
|
||||
});
|
||||
|
||||
it('refuses a name no certificate can cover, however it got on the list', () => {
|
||||
// A wildcard covers one label. The host this migration inherits from took
|
||||
// these anyway, so five of them are on file and none can serve TLS.
|
||||
const deep = claim({ hostname: 'webvoice.shakespeare.wtf.shakespeare.wtf', mine: true });
|
||||
|
||||
const step = planClaim(deep, PUBKEY, new Set(), DOMAIN);
|
||||
expect(step.kind).toBe('blocked');
|
||||
expect(step).toMatchObject({ reason: expect.stringContaining('certificate') });
|
||||
});
|
||||
});
|
||||
|
||||
describe('isServableHostname', () => {
|
||||
it('accepts exactly one label under the domain', () => {
|
||||
expect(isServableHostname('mysite.shakespeare.wtf', DOMAIN)).toBe(true);
|
||||
expect(isServableHostname('My-Site.Shakespeare.WTF', DOMAIN)).toBe(true);
|
||||
expect(isServableHostname('a.b.shakespeare.wtf', DOMAIN)).toBe(false);
|
||||
expect(isServableHostname('shakespeare.wtf', DOMAIN)).toBe(false);
|
||||
expect(isServableHostname('mysite.example.com', DOMAIN)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('nsitePreviewUrl', () => {
|
||||
it('addresses a named site by its base36 pubkey and identifier', () => {
|
||||
expect(nsitePreviewUrl(`${NAMED_SITE_KIND}:${ARCHIVE}:mysite`)).toMatch(/^https:\/\/[0-9a-z]{50}mysite\.nsite\.lol$/);
|
||||
});
|
||||
|
||||
it('addresses a root site by its npub', () => {
|
||||
expect(nsitePreviewUrl(`${ROOT_SITE_KIND}:${ARCHIVE}:`)).toMatch(/^https:\/\/npub1[0-9a-z]+\.nsite\.lol$/);
|
||||
});
|
||||
|
||||
it('has nowhere to send an identifier that will not fit a DNS label', () => {
|
||||
// About a quarter of what this migration carries: the host it came from
|
||||
// named sites after projects and never had to fit one in a subdomain.
|
||||
expect(nsitePreviewUrl(`${NAMED_SITE_KIND}:${ARCHIVE}:nostr-pro-file-manager`)).toBeUndefined();
|
||||
// Uppercase resolves as a DNS label and then matches no `d` tag, which is
|
||||
// worse than no link at all.
|
||||
expect(nsitePreviewUrl(`${NAMED_SITE_KIND}:${ARCHIVE}:ErrorTime`)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('says nothing about an address it cannot read', () => {
|
||||
expect(nsitePreviewUrl(null)).toBeUndefined();
|
||||
expect(nsitePreviewUrl(undefined)).toBeUndefined();
|
||||
expect(nsitePreviewUrl(`${NAMED_SITE_KIND}:not-a-pubkey:mysite`)).toBeUndefined();
|
||||
expect(nsitePreviewUrl(`${NAMED_SITE_KIND}:${ARCHIVE}:`)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('sitePreviewUrl', () => {
|
||||
it('prefers the address, which outlives both the name and its certificate', () => {
|
||||
expect(sitePreviewUrl(`${NAMED_SITE_KIND}:${ARCHIVE}:mysite`, 'mysite.shakespeare.wtf', DOMAIN)).toMatch(
|
||||
/\.nsite\.lol$/,
|
||||
);
|
||||
});
|
||||
|
||||
it('falls back to the hostname when no gateway label can hold the identifier', () => {
|
||||
expect(
|
||||
sitePreviewUrl(`${NAMED_SITE_KIND}:${ARCHIVE}:nostr-pro-file-manager`, 'long.shakespeare.wtf', DOMAIN),
|
||||
).toBe('https://long.shakespeare.wtf');
|
||||
});
|
||||
|
||||
it('offers nothing for a name that is neither servable nor addressable', () => {
|
||||
// A link to a certificate error is worse than no button.
|
||||
expect(sitePreviewUrl(null, 'a.b.shakespeare.wtf', DOMAIN)).toBeUndefined();
|
||||
expect(
|
||||
sitePreviewUrl(`${NAMED_SITE_KIND}:${ARCHIVE}:nostr-pro-file-manager`, 'a.b.shakespeare.wtf', DOMAIN),
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('republishTags', () => {
|
||||
it('keeps the files and where to fetch them, and takes the archive’s words', () => {
|
||||
const manifest = claim().manifest;
|
||||
if (!manifest) throw new Error('fixture has a manifest');
|
||||
|
||||
const tags = republishTags(
|
||||
{ ...manifest, tags: [...manifest.tags, ['relay', 'wss://gone.example']] },
|
||||
'mysite',
|
||||
{ title: 'My Site', description: 'What it is for.' },
|
||||
);
|
||||
|
||||
expect(tags[0]).toEqual(['d', 'mysite']);
|
||||
expect(tags).toContainEqual(['path', '/index.html', 'c'.repeat(64)]);
|
||||
expect(tags).toContainEqual(['server', 'https://blossom.ditto.pub/']);
|
||||
// NIP-5A has no relay-hint tag, so the archive's are dropped and none of
|
||||
// ours take their place.
|
||||
expect(tags.some(([name]) => name === 'relay' || name === 'r')).toBe(false);
|
||||
expect(tags.filter(([name]) => name === 'd')).toHaveLength(1);
|
||||
|
||||
// The archive's title was the hostname and its `alt` says the site is
|
||||
// archived, which stops being true the moment it comes home.
|
||||
expect(tags).toContainEqual(['title', 'My Site']);
|
||||
expect(tags).toContainEqual(['description', 'What it is for.']);
|
||||
expect(tags.filter(([name]) => name === 'title')).toHaveLength(1);
|
||||
expect(tags.some(([name]) => name === 'alt')).toBe(false);
|
||||
});
|
||||
|
||||
it('leaves a site that never said what it is called untitled', () => {
|
||||
const manifest = claim().manifest;
|
||||
if (!manifest) throw new Error('fixture has a manifest');
|
||||
|
||||
// Roughly a third of these are shells that set their title from JavaScript.
|
||||
// No title is what an nsite manifest without one has always meant, and is
|
||||
// better than a domain wearing a name's clothes.
|
||||
const tags = republishTags(manifest, 'mysite', {});
|
||||
|
||||
expect(tags.some(([name]) => name === 'title')).toBe(false);
|
||||
expect(tags).toContainEqual(['path', '/index.html', 'c'.repeat(64)]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('retitleTags', () => {
|
||||
it('swaps the archive’s words, drops the tags NIP-5A never had, and passes the rest through', () => {
|
||||
const event = {
|
||||
id: 'e'.repeat(64),
|
||||
pubkey: PUBKEY,
|
||||
kind: NAMED_SITE_KIND,
|
||||
created_at: 1,
|
||||
content: '',
|
||||
sig: '0'.repeat(128),
|
||||
tags: [
|
||||
['d', 'mysite'],
|
||||
['title', 'mysite.shakespeare.wtf'],
|
||||
['path', '/index.html', 'c'.repeat(64)],
|
||||
['server', 'https://blossom.ditto.pub/'],
|
||||
['relay', 'wss://relay.ditto.pub'],
|
||||
],
|
||||
} as NostrEvent;
|
||||
|
||||
const tags = retitleTags(event, { title: 'My Site' });
|
||||
|
||||
expect(tags).toContainEqual(['d', 'mysite']);
|
||||
// Built from the event as relays hold it, so a site redeployed since this
|
||||
// migration ran keeps whatever it has become.
|
||||
expect(tags).toContainEqual(['path', '/index.html', 'c'.repeat(64)]);
|
||||
expect(tags).toContainEqual(['server', 'https://blossom.ditto.pub/']);
|
||||
// Except the relay hints an older deploy wrote, which re-signing is the
|
||||
// chance to stop carrying.
|
||||
expect(tags.some(([name]) => name === 'relay')).toBe(false);
|
||||
expect(tags).toContainEqual(['title', 'My Site']);
|
||||
expect(tags.filter(([name]) => name === 'title')).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('hasArchiveTitle', () => {
|
||||
const event = (title: string) =>
|
||||
({ tags: [['d', 'mysite'], ['title', title]] }) as NostrEvent;
|
||||
|
||||
it('recognises a title that is really an address', () => {
|
||||
expect(hasArchiveTitle(event('mysite.shakespeare.wtf'), 'mysite.shakespeare.wtf')).toBe(true);
|
||||
expect(hasArchiveTitle(event('My Site'), 'mysite.shakespeare.wtf')).toBe(false);
|
||||
expect(hasArchiveTitle({ tags: [] } as unknown as NostrEvent, 'mysite.shakespeare.wtf')).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -1,269 +0,0 @@
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import { buildNsiteUrl, isValidDTag } from '@/lib/utils/nsite';
|
||||
import type { NpanelClaim, NpanelClaimManifest } from './npanelApi';
|
||||
|
||||
/** nsite named-site kind. Everything a gateway archived is one of these. */
|
||||
export const NAMED_SITE_KIND = 35128;
|
||||
|
||||
/** nsite root-site kind. One per key, which is why one is never republished. */
|
||||
export const ROOT_SITE_KIND = 15128;
|
||||
|
||||
/**
|
||||
* A gateway that serves any nsite from its address alone.
|
||||
*
|
||||
* Not this gateway, deliberately. Everything in this list is a decision about a
|
||||
* site somebody has not looked at in a year, and the honest way to show them one
|
||||
* is from an address rather than from the name that is in question — a name
|
||||
* about to be deleted, or one that no certificate covers and that has therefore
|
||||
* never loaded for anyone. It reads the same relays this provider publishes to,
|
||||
* so the archive's copy is as findable there as anywhere.
|
||||
*/
|
||||
const PREVIEW_GATEWAY = 'nsite.lol';
|
||||
|
||||
/**
|
||||
* Tags the archive wrote about itself, which are not the site's to carry.
|
||||
*
|
||||
* The title it invented was the hostname, because that was all it knew, and the
|
||||
* `alt` it wrote says the site is archived so that it keeps working — a true
|
||||
* sentence about the archive that stops being true the moment its owner takes
|
||||
* the name back.
|
||||
*/
|
||||
const ARCHIVE_TAGS = new Set(['title', 'description', 'alt']);
|
||||
|
||||
/**
|
||||
* What taking one name back requires.
|
||||
*
|
||||
* Three outcomes rather than two, because the interesting case is the one in
|
||||
* the middle: a name whose site is already published under the claimant's own
|
||||
* key needs no republishing at all, and republishing it anyway would overwrite
|
||||
* a live site with an old snapshot of itself.
|
||||
*/
|
||||
export type MigrationStep =
|
||||
/** Point the name at a site that already exists. Costs one request. */
|
||||
| { kind: 'claim'; address: string; reason: 'mine' | 'published' }
|
||||
/** Publish the archived manifest under the claimant's key, then point at it. */
|
||||
| { kind: 'republish'; identifier: string; manifest: NpanelClaimManifest }
|
||||
/** Nothing safe to do without a person deciding something first. */
|
||||
| { kind: 'blocked'; reason: string };
|
||||
|
||||
/** What a site calls itself, when it says. */
|
||||
export interface SiteIdentity {
|
||||
title?: string | null;
|
||||
description?: string | null;
|
||||
}
|
||||
|
||||
/** The `d` tag of a manifest, which for a named site is the site's identifier. */
|
||||
export function manifestIdentifier(manifest: NpanelClaimManifest): string {
|
||||
return manifest.tags.find(([name]) => name === 'd')?.[1] ?? '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a hostname is one label under the gateway's domain.
|
||||
*
|
||||
* The wildcard certificate a gateway serves covers exactly one label, so
|
||||
* `a.b.example.com` can be pointed at a site, claimed, and published for, and
|
||||
* will still fail its TLS handshake for everyone forever. The records exist
|
||||
* because the host this migration inherits from accepted them; there is no
|
||||
* point signing anything for one.
|
||||
*/
|
||||
export function isServableHostname(hostname: string, domain: string): boolean {
|
||||
const suffix = `.${domain.toLowerCase()}`;
|
||||
const name = hostname.toLowerCase();
|
||||
|
||||
if (!name.endsWith(suffix)) return false;
|
||||
|
||||
const label = name.slice(0, -suffix.length);
|
||||
return label.length > 0 && !label.includes('.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Somewhere the site at an address can actually be looked at.
|
||||
*
|
||||
* Preferred over the hostname because a preview is worth most for the names the
|
||||
* hostname cannot show: one too deep for a wildcard certificate, which answers a
|
||||
* TLS error and always has, and one about to be deleted, which will stop
|
||||
* answering at all. An address survives both.
|
||||
*
|
||||
* Undefined when the identifier is longer than a DNS label leaves room for —
|
||||
* about a quarter of what this migration carries, because the host it came from
|
||||
* named sites after projects and never had to fit one in a subdomain. There is
|
||||
* no address-based URL for those on any gateway, so callers fall back to the
|
||||
* hostname where the hostname works.
|
||||
*/
|
||||
export function nsitePreviewUrl(address: string | null | undefined): string | undefined {
|
||||
if (!address) return undefined;
|
||||
|
||||
const [kind, pubkey, ...rest] = address.split(':');
|
||||
const identifier = rest.join(':');
|
||||
|
||||
if (!/^[0-9a-f]{64}$/i.test(pubkey ?? '')) return undefined;
|
||||
|
||||
if (Number(kind) === ROOT_SITE_KIND && !identifier) {
|
||||
return buildNsiteUrl({ pubkeyHex: pubkey, npub: nip19.npubEncode(pubkey), gateway: PREVIEW_GATEWAY });
|
||||
}
|
||||
|
||||
if (Number(kind) === NAMED_SITE_KIND && isValidDTag(identifier)) {
|
||||
return buildNsiteUrl({
|
||||
pubkeyHex: pubkey,
|
||||
npub: nip19.npubEncode(pubkey),
|
||||
gateway: PREVIEW_GATEWAY,
|
||||
siteIdentifier: identifier,
|
||||
});
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where to send somebody who wants to see a site before deciding about it.
|
||||
*
|
||||
* {@link nsitePreviewUrl} first, the hostname second, and nothing at all for a
|
||||
* name that is both unservable and unaddressable — which is a real combination
|
||||
* here, and better shown as no button than as a link to a certificate error.
|
||||
*/
|
||||
export function sitePreviewUrl(
|
||||
address: string | null | undefined,
|
||||
hostname: string,
|
||||
domain: string,
|
||||
): string | undefined {
|
||||
return nsitePreviewUrl(address) ?? (isServableHostname(hostname, domain) ? `https://${hostname}` : undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
* Decide how a single waiting name gets back to its owner.
|
||||
*
|
||||
* `published` is the set of `d` tags the owner already publishes kind-35128
|
||||
* events under. It is what separates a name that only needs a record changed
|
||||
* from one that needs a site published, and getting it wrong in the careless
|
||||
* direction destroys a live site: kind 35128 is addressable, so a second event
|
||||
* at the same `d` tag replaces the first one everywhere.
|
||||
*/
|
||||
export function planClaim(
|
||||
claim: NpanelClaim,
|
||||
pubkey: string,
|
||||
published: ReadonlySet<string>,
|
||||
domain: string,
|
||||
): MigrationStep {
|
||||
if (!isServableHostname(claim.hostname, domain)) {
|
||||
return {
|
||||
kind: 'blocked',
|
||||
reason: `No certificate covers a name this deep under ${domain}, so it can never load.`,
|
||||
};
|
||||
}
|
||||
|
||||
// Already on their key — the site was never anyone else's, only the record
|
||||
// of who owns the name was missing.
|
||||
if (claim.mine && claim.address) {
|
||||
return { kind: 'claim', address: claim.address, reason: 'mine' };
|
||||
}
|
||||
|
||||
if (!claim.manifest) {
|
||||
return {
|
||||
kind: 'blocked',
|
||||
reason: 'Nothing was archived under this name. Deploy a project to it to take it back.',
|
||||
};
|
||||
}
|
||||
|
||||
// A root site is the one site a key can only have one of. Republishing an
|
||||
// archived copy as one would replace whatever the claimant's own key serves.
|
||||
if (claim.manifest.kind !== NAMED_SITE_KIND) {
|
||||
return {
|
||||
kind: 'blocked',
|
||||
reason: 'This name was archived as a root site, which would replace your main site if republished.',
|
||||
};
|
||||
}
|
||||
|
||||
const identifier = manifestIdentifier(claim.manifest);
|
||||
if (!identifier) {
|
||||
return { kind: 'blocked', reason: 'The archived site has no name to publish it under.' };
|
||||
}
|
||||
|
||||
// The site is already theirs under this name; the hostname just needs to be
|
||||
// told about it. Both names then serve the same site, which is what someone
|
||||
// who deployed the same project twice was always asking for.
|
||||
if (published.has(identifier)) {
|
||||
return {
|
||||
kind: 'claim',
|
||||
address: `${NAMED_SITE_KIND}:${pubkey}:${identifier}`,
|
||||
reason: 'published',
|
||||
};
|
||||
}
|
||||
|
||||
return { kind: 'republish', identifier, manifest: claim.manifest };
|
||||
}
|
||||
|
||||
/**
|
||||
* The tags to sign to republish an archived site under one's own key.
|
||||
*
|
||||
* An nsite manifest is its tags — the paths and their hashes, and the Blossom
|
||||
* servers those hashes can be fetched from — so signing these again produces
|
||||
* the same site, file for file, under a different key. The blobs themselves are
|
||||
* addressed by hash and are already where the `server` tags say they are, so
|
||||
* nothing has to be uploaded.
|
||||
*
|
||||
* What is not carried over is the archive's own writing. It titled every site
|
||||
* after its hostname, which is an address wearing a name's clothes; the site's
|
||||
* real name, where it has one, is `identity`. A site that never said what it is
|
||||
* called gets no title, which is what an nsite manifest without one has always
|
||||
* meant and is more honest than a domain.
|
||||
*
|
||||
* The archive's relay hints are dropped and not replaced. NIP-5A gives a
|
||||
* manifest no tag for saying where it was published, so the archive's `relay`
|
||||
* and `r` tags are tags that were never part of the spec, and re-signing them
|
||||
* under someone else's key would only spread them further.
|
||||
*/
|
||||
export function republishTags(
|
||||
manifest: NpanelClaimManifest,
|
||||
identifier: string,
|
||||
identity: SiteIdentity = {},
|
||||
): string[][] {
|
||||
const kept = manifest.tags.filter(
|
||||
([name]) => name !== 'd' && name !== 'relay' && name !== 'r' && !ARCHIVE_TAGS.has(name),
|
||||
);
|
||||
|
||||
return [
|
||||
// First, as an addressable event's `d` tag should be.
|
||||
['d', identifier],
|
||||
...kept,
|
||||
...describeTags(identity),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* The same event, with the name the site chose in place of the one it was given.
|
||||
*
|
||||
* Built from the event as it stands rather than from anything the gateway
|
||||
* holds, because the two are not always the same thing: a site republished by
|
||||
* this migration and then redeployed normally has moved on, and rebuilding it
|
||||
* out of the gateway's copy would quietly restore an older version of the site.
|
||||
* Everything but the archive's own words and the relay hints NIP-5A never
|
||||
* defined is passed through untouched; signing an event is the moment to stop
|
||||
* carrying a tag that does not exist.
|
||||
*/
|
||||
export function retitleTags(event: NostrEvent, identity: SiteIdentity): string[][] {
|
||||
const kept = event.tags.filter(
|
||||
([name]) => name !== 'relay' && name !== 'r' && !ARCHIVE_TAGS.has(name),
|
||||
);
|
||||
|
||||
return [...kept, ...describeTags(identity)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an event is still wearing the title the archive gave it.
|
||||
*
|
||||
* The archive had one thing to call a site it had only ever seen at an address,
|
||||
* so a title that is the hostname is a title nobody chose.
|
||||
*/
|
||||
export function hasArchiveTitle(event: NostrEvent, hostname: string): boolean {
|
||||
const title = event.tags.find(([name]) => name === 'title')?.[1];
|
||||
return typeof title === 'string' && title.toLowerCase() === hostname.toLowerCase();
|
||||
}
|
||||
|
||||
/** `title` and `description` tags, for whichever of them the site supplied. */
|
||||
function describeTags(identity: SiteIdentity): string[][] {
|
||||
const tags: string[][] = [];
|
||||
if (identity.title) tags.push(['title', identity.title]);
|
||||
if (identity.description) tags.push(['description', identity.description]);
|
||||
return tags;
|
||||
}
|
||||
@@ -1,180 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import type { NostrEvent, NRelay } from '@nostrify/nostrify';
|
||||
import { checkRelayCoverage, forwardMissing, publishToRelays, type RelayPool } from './publishToRelays';
|
||||
|
||||
const RELAYS = ['wss://a.example', 'wss://b.example', 'wss://c.example'];
|
||||
|
||||
function event(id: string): NostrEvent {
|
||||
return {
|
||||
id,
|
||||
pubkey: 'a'.repeat(64),
|
||||
kind: 35128,
|
||||
created_at: 1,
|
||||
content: '',
|
||||
tags: [],
|
||||
sig: '0'.repeat(128),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A pool whose relays answer however the test says.
|
||||
*
|
||||
* `verdicts` maps a relay URL to what it does with an event: `true` accepts,
|
||||
* a string refuses with that reason. `holdings` is what each relay answers a
|
||||
* query with.
|
||||
*/
|
||||
function pool(
|
||||
verdicts: Record<string, true | string>,
|
||||
holdings: Record<string, string[]> = {},
|
||||
): RelayPool & { sent: Array<[string, string]> } {
|
||||
const sent: Array<[string, string]> = [];
|
||||
|
||||
return {
|
||||
sent,
|
||||
group(urls: string[]): NRelay {
|
||||
const url = urls[0];
|
||||
return {
|
||||
async event(e: NostrEvent) {
|
||||
const verdict = verdicts[url];
|
||||
if (verdict !== true) throw new Error(verdict ?? 'no such relay');
|
||||
sent.push([url, e.id]);
|
||||
},
|
||||
async query() {
|
||||
return (holdings[url] ?? []).map(event);
|
||||
},
|
||||
} as unknown as NRelay;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('publishToRelays', () => {
|
||||
it('reports every relay separately, not just the first to answer', async () => {
|
||||
// Nostrify's pool resolves on the first acceptance and discards the rest,
|
||||
// which is how 97 manifests reached one relay and none reached another
|
||||
// without anything saying so.
|
||||
const relays = pool({
|
||||
'wss://a.example': true,
|
||||
'wss://b.example': 'blocked: kind 35128 is not accepted by this relay',
|
||||
'wss://c.example': true,
|
||||
});
|
||||
|
||||
const outcome = await publishToRelays(relays, event('f'.repeat(64)), RELAYS);
|
||||
|
||||
expect(outcome.accepted).toEqual(['wss://a.example', 'wss://c.example']);
|
||||
expect(outcome.rejected).toEqual([
|
||||
{ url: 'wss://b.example', reason: 'blocked: kind 35128 is not accepted by this relay' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('is a success when one relay takes it', async () => {
|
||||
const relays = pool({ 'wss://a.example': true, 'wss://b.example': 'no', 'wss://c.example': 'no' });
|
||||
|
||||
// The event exists, and a gateway reading the relay that has it will find
|
||||
// it. Failing the deploy over the other two would be wrong about something
|
||||
// the user can see working.
|
||||
await expect(publishToRelays(relays, event('f'.repeat(64)), RELAYS)).resolves.toMatchObject({
|
||||
accepted: ['wss://a.example'],
|
||||
});
|
||||
});
|
||||
|
||||
it('fails, with every reason, when nobody takes it', async () => {
|
||||
const relays = pool({
|
||||
'wss://a.example': 'blocked: rate limited',
|
||||
'wss://b.example': 'invalid: bad signature',
|
||||
'wss://c.example': 'error: down',
|
||||
});
|
||||
|
||||
await expect(publishToRelays(relays, event('f'.repeat(64)), RELAYS)).rejects.toThrow(
|
||||
/No relay accepted.*a\.example: blocked: rate limited.*b\.example: invalid: bad signature/s,
|
||||
);
|
||||
});
|
||||
|
||||
it('refuses to publish nowhere', async () => {
|
||||
await expect(publishToRelays(pool({}), event('f'.repeat(64)), [])).rejects.toThrow(/No relays/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('relay coverage', () => {
|
||||
it('sends each relay only what it is missing, unchanged', async () => {
|
||||
const events = [event('1'.repeat(64)), event('2'.repeat(64))];
|
||||
|
||||
const relays = pool(
|
||||
{ 'wss://a.example': true, 'wss://b.example': true, 'wss://c.example': true },
|
||||
{
|
||||
'wss://a.example': [events[0].id, events[1].id],
|
||||
'wss://b.example': [events[0].id],
|
||||
'wss://c.example': [],
|
||||
},
|
||||
);
|
||||
|
||||
const coverage = await checkRelayCoverage(relays, RELAYS, events.map((e) => e.id));
|
||||
expect(coverage.map((c) => c.present.size)).toEqual([2, 1, 0]);
|
||||
|
||||
const result = await forwardMissing(relays, coverage, events);
|
||||
|
||||
expect(result.filled.get('wss://a.example')).toBeUndefined();
|
||||
expect(result.filled.get('wss://b.example')).toBe(1);
|
||||
expect(result.filled.get('wss://c.example')).toBe(2);
|
||||
// The same events, so no signer is involved and a second run is harmless.
|
||||
expect(relays.sent).toEqual([
|
||||
['wss://b.example', events[1].id],
|
||||
['wss://c.example', events[0].id],
|
||||
['wss://c.example', events[1].id],
|
||||
]);
|
||||
});
|
||||
|
||||
it('asks a refusing relay once and reports what it said', async () => {
|
||||
const events = [event('1'.repeat(64)), event('2'.repeat(64)), event('3'.repeat(64))];
|
||||
|
||||
const relays = pool({ 'wss://a.example': 'blocked: not accepting these' }, { 'wss://a.example': [] });
|
||||
|
||||
const coverage = await checkRelayCoverage(relays, ['wss://a.example'], events.map((e) => e.id));
|
||||
const result = await forwardMissing(relays, coverage, events);
|
||||
|
||||
// Three copies of one sentence is not more information than one.
|
||||
expect(result.refused.get('wss://a.example')).toBe('blocked: not accepting these');
|
||||
expect(relays.sent).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('tells a relay that cannot be reached apart from one holding nothing', async () => {
|
||||
const relays: RelayPool = {
|
||||
group: () =>
|
||||
({
|
||||
query: () => Promise.reject(new Error('connection refused')),
|
||||
event: () => Promise.resolve(),
|
||||
}) as unknown as NRelay,
|
||||
};
|
||||
|
||||
const coverage = await checkRelayCoverage(relays, ['wss://a.example'], ['1'.repeat(64)]);
|
||||
|
||||
// One is a relay to send to, the other is a relay to try again later.
|
||||
expect(coverage[0].error).toBe('connection refused');
|
||||
expect(coverage[0].present.size).toBe(0);
|
||||
});
|
||||
|
||||
it('calls a timeout silence rather than a verdict', async () => {
|
||||
const relays: RelayPool = {
|
||||
group: () =>
|
||||
({
|
||||
event: () => Promise.reject(new DOMException('aborted', 'TimeoutError')),
|
||||
}) as unknown as NRelay,
|
||||
};
|
||||
|
||||
await expect(publishToRelays(relays, event('f'.repeat(64)), ['wss://a.example'])).rejects.toThrow(
|
||||
/no answer before the timeout/,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('NsiteAdapter integration point', () => {
|
||||
it('passes the pool through without a group of its own', async () => {
|
||||
// The adapter used to call `nostr.group(relays).event(...)`, whose
|
||||
// Promise.any hid this entirely.
|
||||
const relays = pool({ 'wss://a.example': true });
|
||||
const spy = vi.spyOn(relays, 'group');
|
||||
|
||||
await publishToRelays(relays, event('f'.repeat(64)), ['wss://a.example']);
|
||||
|
||||
expect(spy).toHaveBeenCalledWith(['wss://a.example']);
|
||||
});
|
||||
});
|
||||
@@ -1,225 +0,0 @@
|
||||
import type { NostrEvent, NRelay } from '@nostrify/nostrify';
|
||||
|
||||
/** How long one relay is given to accept an event. */
|
||||
const PUBLISH_TIMEOUT_MS = 10_000;
|
||||
|
||||
/** A relay that refused an event, and the sentence it refused with. */
|
||||
export interface RelayRejection {
|
||||
url: string;
|
||||
/** The relay's own `OK false` message, or whatever went wrong instead. */
|
||||
reason: string;
|
||||
}
|
||||
|
||||
/** Which relays took an event and which did not. */
|
||||
export interface PublishOutcome {
|
||||
accepted: string[];
|
||||
rejected: RelayRejection[];
|
||||
}
|
||||
|
||||
/** A pool that can be narrowed to a single relay, which is all this needs. */
|
||||
export interface RelayPool {
|
||||
group(urls: string[]): NRelay;
|
||||
}
|
||||
|
||||
/**
|
||||
* Publish to every relay, and report what each one said.
|
||||
*
|
||||
* Nostrify's pool publishes with `Promise.any`, which resolves as soon as one
|
||||
* relay accepts and discards every other answer — including the rejections.
|
||||
* A deploy to five relays that only one accepted is reported as a success
|
||||
* indistinguishable from a deploy all five took, and the reason the other four
|
||||
* refused is received and thrown away.
|
||||
*
|
||||
* That is not a hypothetical difference. Of 102 manifests published this way in
|
||||
* one session, one relay held all of them and another held none, and nothing
|
||||
* anywhere said so.
|
||||
*
|
||||
* One acceptance is still a success — the event exists, and a gateway reading
|
||||
* any relay that has it will find it — so this throws only when nobody took it.
|
||||
* The rest is reported rather than raised, because a site published to four
|
||||
* relays out of five is working, and a deploy that failed over it would be
|
||||
* wrong about something the user can see.
|
||||
*/
|
||||
export async function publishToRelays(
|
||||
pool: RelayPool,
|
||||
event: NostrEvent,
|
||||
relayUrls: string[],
|
||||
signal?: AbortSignal,
|
||||
): Promise<PublishOutcome> {
|
||||
if (!relayUrls.length) {
|
||||
throw new Error('No relays are configured to publish to.');
|
||||
}
|
||||
|
||||
const results = await Promise.allSettled(
|
||||
relayUrls.map((url) =>
|
||||
// One relay per group, so a rejection can be attributed to the relay that
|
||||
// made it. The pool shares the underlying connections either way.
|
||||
pool.group([url]).event(event, {
|
||||
signal: signal ?? AbortSignal.timeout(PUBLISH_TIMEOUT_MS),
|
||||
}),
|
||||
),
|
||||
);
|
||||
|
||||
const accepted: string[] = [];
|
||||
const rejected: RelayRejection[] = [];
|
||||
|
||||
results.forEach((result, index) => {
|
||||
const url = relayUrls[index];
|
||||
if (result.status === 'fulfilled') {
|
||||
accepted.push(url);
|
||||
} else {
|
||||
rejected.push({ url, reason: describe(result.reason) });
|
||||
}
|
||||
});
|
||||
|
||||
if (!accepted.length) {
|
||||
throw new Error(
|
||||
`No relay accepted this event. ${rejected.map((r) => `${host(r.url)}: ${r.reason}`).join('; ')}`,
|
||||
);
|
||||
}
|
||||
|
||||
return { accepted, rejected };
|
||||
}
|
||||
|
||||
/**
|
||||
* A relay's refusal, in whatever form it arrived.
|
||||
*
|
||||
* Read by shape rather than by `instanceof`, because a timeout arrives as a
|
||||
* `DOMException`, which is not an `Error` everywhere — and mistaking one for an
|
||||
* object with nothing to say turns "this relay never answered" into "this relay
|
||||
* refused", which are different facts about different things.
|
||||
*/
|
||||
function describe(reason: unknown): string {
|
||||
if (typeof reason === 'string' && reason) return reason;
|
||||
if (typeof reason !== 'object' || reason === null) return 'refused without saying why';
|
||||
|
||||
const { name, message } = reason as { name?: unknown; message?: unknown };
|
||||
|
||||
// An abort is our own deadline, not a verdict from the relay.
|
||||
if (name === 'AbortError' || name === 'TimeoutError') return 'no answer before the timeout';
|
||||
|
||||
if (typeof message === 'string' && message) return message;
|
||||
return typeof name === 'string' && name ? name : 'refused without saying why';
|
||||
}
|
||||
|
||||
/** The hostname of a relay URL, for a message somebody has to read. */
|
||||
export function host(url: string): string {
|
||||
try {
|
||||
return new URL(url).host;
|
||||
} catch {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
/** How many event ids are asked about in one filter. */
|
||||
const COVERAGE_BATCH = 100;
|
||||
|
||||
/** How long one relay is given to say what it has. */
|
||||
const COVERAGE_TIMEOUT_MS = 8_000;
|
||||
|
||||
/** Which of a set of events one relay holds. */
|
||||
export interface RelayCoverage {
|
||||
url: string;
|
||||
/** Ids the relay answered with. */
|
||||
present: Set<string>;
|
||||
/** Set when the relay could not be asked at all, as opposed to answering "none". */
|
||||
error?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask each relay which of these events it already has.
|
||||
*
|
||||
* A relay that cannot be reached is reported as an error rather than as holding
|
||||
* nothing, because the two call for opposite responses: one is a relay to send
|
||||
* to, the other is a relay to try again later.
|
||||
*/
|
||||
export async function checkRelayCoverage(
|
||||
pool: RelayPool,
|
||||
relayUrls: string[],
|
||||
eventIds: string[],
|
||||
signal?: AbortSignal,
|
||||
): Promise<RelayCoverage[]> {
|
||||
const batches: string[][] = [];
|
||||
for (let i = 0; i < eventIds.length; i += COVERAGE_BATCH) {
|
||||
batches.push(eventIds.slice(i, i + COVERAGE_BATCH));
|
||||
}
|
||||
|
||||
return await Promise.all(
|
||||
relayUrls.map(async (url): Promise<RelayCoverage> => {
|
||||
const present = new Set<string>();
|
||||
|
||||
try {
|
||||
for (const ids of batches) {
|
||||
const found = await pool.group([url]).query([{ ids, limit: ids.length }], {
|
||||
signal: signal ?? AbortSignal.timeout(COVERAGE_TIMEOUT_MS),
|
||||
});
|
||||
for (const event of found) present.add(event.id);
|
||||
}
|
||||
} catch (error) {
|
||||
return { url, present, error: describe(error) };
|
||||
}
|
||||
|
||||
return { url, present };
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** What forwarding a set of events to the relays missing them achieved. */
|
||||
export interface ForwardResult {
|
||||
/** Relay URL to the number of events it took that it did not have. */
|
||||
filled: Map<string, number>;
|
||||
/** Relay URL to why it would not take them, from the first refusal. */
|
||||
refused: Map<string, string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send events to the relays that do not have them, exactly as they are.
|
||||
*
|
||||
* The same events, ids and signatures unchanged, so this needs no signer and
|
||||
* can be run as many times as it takes: a relay that already has one answers
|
||||
* `duplicate:` and nothing happens. Publishing to five relays and having one
|
||||
* take it is a success that leaves four gaps, and this is how the gaps close
|
||||
* without anyone re-signing a hundred manifests.
|
||||
*
|
||||
* It is also the only way to read why a relay refused in the first place: the
|
||||
* refusal is thrown away at publish time, and asking again is how you hear it.
|
||||
*/
|
||||
export async function forwardMissing(
|
||||
pool: RelayPool,
|
||||
coverage: RelayCoverage[],
|
||||
events: NostrEvent[],
|
||||
signal?: AbortSignal,
|
||||
): Promise<ForwardResult> {
|
||||
const filled = new Map<string, number>();
|
||||
const refused = new Map<string, string>();
|
||||
|
||||
for (const relay of coverage) {
|
||||
if (relay.error) {
|
||||
refused.set(relay.url, relay.error);
|
||||
continue;
|
||||
}
|
||||
|
||||
const missing = events.filter((event) => !relay.present.has(event.id));
|
||||
if (!missing.length) continue;
|
||||
|
||||
let count = 0;
|
||||
for (const event of missing) {
|
||||
try {
|
||||
await pool.group([relay.url]).event(event, {
|
||||
signal: signal ?? AbortSignal.timeout(PUBLISH_TIMEOUT_MS),
|
||||
});
|
||||
count++;
|
||||
} catch (error) {
|
||||
// One reason per relay: a relay refusing the first of ninety-seven
|
||||
// will refuse the rest for the same reason, and ninety-seven copies of
|
||||
// one sentence is not more information.
|
||||
if (!refused.has(relay.url)) refused.set(relay.url, describe(error));
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (count) filled.set(relay.url, count);
|
||||
}
|
||||
|
||||
return { filled, refused };
|
||||
}
|
||||
+9
-21
@@ -20,6 +20,14 @@ 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;
|
||||
@@ -60,26 +68,6 @@ 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;
|
||||
@@ -115,7 +103,7 @@ export interface RailwayDeployConfig {
|
||||
|
||||
export interface PresetDeployProvider {
|
||||
id: string;
|
||||
type: 'npanel' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway';
|
||||
type: 'shakespeare' | 'netlify' | 'vercel' | 'nsite' | 'cloudflare' | 'deno' | 'railway';
|
||||
name: string;
|
||||
description: string;
|
||||
baseURL?: string;
|
||||
|
||||
@@ -1,48 +0,0 @@
|
||||
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,86 +1,33 @@
|
||||
import type { DeployProvider, NpanelProvider, NsiteProvider } from '@/contexts/DeploySettingsContext';
|
||||
import type { NsiteProvider } from '@/contexts/DeploySettingsContext';
|
||||
import type { PresetDeployProvider } from './deploy/types';
|
||||
|
||||
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. */
|
||||
/** Default nsite provider configuration, pre-configured for new users. */
|
||||
export const DEFAULT_NSITE_PROVIDER: NsiteProvider = {
|
||||
id: 'nsite',
|
||||
name: 'nsite',
|
||||
type: 'nsite',
|
||||
gateway: 'shakespeare.to',
|
||||
relayUrls: DEFAULT_RELAYS,
|
||||
blossomServers: DEFAULT_BLOSSOM_SERVERS,
|
||||
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',
|
||||
],
|
||||
};
|
||||
|
||||
/** 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: 'npanel',
|
||||
type: 'npanel',
|
||||
name: 'Shakespeare',
|
||||
description: 'Publish to Nostr and get a shakespeare.wtf address',
|
||||
id: 'shakespeare',
|
||||
type: 'shakespeare',
|
||||
name: 'Shakespeare Deploy',
|
||||
description: 'Deploy to Shakespeare hosting with Nostr authentication',
|
||||
baseURL: 'https://shakespeare.diy',
|
||||
requiresNostr: true,
|
||||
},
|
||||
|
||||
@@ -1,136 +0,0 @@
|
||||
/**
|
||||
* LNURL-pay (LUD-06 / LUD-16) resolution for zaps.
|
||||
*
|
||||
* `nostr-tools`' `nip57.getZapEndpoint` returns only the `callback` URL and
|
||||
* throws away everything else the endpoint said — including the `minSendable`
|
||||
* / `maxSendable` bounds and the `metadata` string that LUD-06 uses to bind an
|
||||
* invoice to the endpoint that issued it. Both are needed to check that the
|
||||
* invoice we get back is the one we asked for, so resolution lives here
|
||||
* instead.
|
||||
*
|
||||
* Everything in an LNURL-pay response is chosen by the payment *recipient*, so
|
||||
* none of it is trusted: it is validated for shape, the transport is pinned to
|
||||
* HTTPS, and the caller re-checks the resulting invoice against the amount the
|
||||
* user actually approved (see `assertInvoiceAmount` in `@/lib/bolt11`).
|
||||
*/
|
||||
import { bech32 } from '@scure/base';
|
||||
|
||||
/** A validated LNURL-pay response. */
|
||||
export interface LnurlPayParams {
|
||||
/** URL to request the invoice from. Always `https:`. */
|
||||
callback: string;
|
||||
/** Smallest payable amount, in millisatoshis. */
|
||||
minSendable: number;
|
||||
/** Largest payable amount, in millisatoshis. */
|
||||
maxSendable: number;
|
||||
/** LUD-06 metadata string. The invoice's description hash may commit to it. */
|
||||
metadata: string;
|
||||
/** Whether the endpoint accepts a NIP-57 zap request. */
|
||||
allowsNostr: boolean;
|
||||
/** Pubkey the endpoint signs zap receipts with, when it supports zaps. */
|
||||
nostrPubkey?: string;
|
||||
}
|
||||
|
||||
/** Shape of the JSON an LNURL-pay endpoint returns. */
|
||||
interface LnurlPayResponse {
|
||||
tag?: unknown;
|
||||
callback?: unknown;
|
||||
minSendable?: unknown;
|
||||
maxSendable?: unknown;
|
||||
metadata?: unknown;
|
||||
allowsNostr?: unknown;
|
||||
nostrPubkey?: unknown;
|
||||
reason?: unknown;
|
||||
}
|
||||
|
||||
/** A lightning address (`name@domain`) or a bech32 `lnurl1…` string. */
|
||||
export interface LnurlSource {
|
||||
lud06?: string;
|
||||
lud16?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn a `lud06` / `lud16` pointer into the URL to fetch LNURL-pay params
|
||||
* from. Returns `null` when neither is usable.
|
||||
*
|
||||
* HTTPS is required. A `lud06` may encode any URL at all, and plaintext HTTP
|
||||
* would let anyone on the network path swap the invoice for one of their own —
|
||||
* which is the entire attack this module exists to prevent.
|
||||
*/
|
||||
export function lnurlToUrl({ lud06, lud16 }: LnurlSource): string | null {
|
||||
let raw: string;
|
||||
|
||||
if (lud06?.trim()) {
|
||||
const { words } = bech32.decode(lud06.trim().toLowerCase() as `${Lowercase<string>}1${string}`, false);
|
||||
raw = new TextDecoder().decode(bech32.fromWords(words));
|
||||
} else if (lud16?.trim()) {
|
||||
const [name, domain] = lud16.trim().split('@');
|
||||
if (!name || !domain) return null;
|
||||
raw = new URL(`/.well-known/lnurlp/${encodeURIComponent(name)}`, `https://${domain}`).toString();
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
|
||||
const url = new URL(raw);
|
||||
if (url.protocol !== 'https:') {
|
||||
throw new Error('Lightning address must use HTTPS');
|
||||
}
|
||||
return url.toString();
|
||||
}
|
||||
|
||||
/** Coerce a JSON value to a non-negative integer, or `null` if it isn't one. */
|
||||
function toCount(value: unknown): number | null {
|
||||
return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? Math.floor(value) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch and validate the LNURL-pay parameters for a payment pointer.
|
||||
*
|
||||
* Throws with a user-presentable message when the endpoint is unreachable or
|
||||
* its response doesn't conform.
|
||||
*/
|
||||
export async function resolveLnurlPay(source: LnurlSource, signal?: AbortSignal): Promise<LnurlPayParams> {
|
||||
const url = lnurlToUrl(source);
|
||||
if (!url) {
|
||||
throw new Error('No lightning address configured');
|
||||
}
|
||||
|
||||
const res = await fetch(url, { signal });
|
||||
if (!res.ok) {
|
||||
throw new Error(`Lightning service returned HTTP ${res.status}`);
|
||||
}
|
||||
|
||||
const body: LnurlPayResponse = await res.json();
|
||||
|
||||
if (typeof body.reason === 'string' && !body.callback) {
|
||||
throw new Error(body.reason);
|
||||
}
|
||||
if (body.tag !== 'payRequest') {
|
||||
throw new Error('Lightning address does not support payments');
|
||||
}
|
||||
if (typeof body.callback !== 'string') {
|
||||
throw new Error('Lightning service returned no payment callback');
|
||||
}
|
||||
|
||||
// The callback is a second, separate URL the endpoint gets to choose. Pin it
|
||||
// to HTTPS for the same reason as the LNURL itself.
|
||||
const callback = new URL(body.callback);
|
||||
if (callback.protocol !== 'https:') {
|
||||
throw new Error('Lightning service requested an insecure payment callback');
|
||||
}
|
||||
|
||||
const minSendable = toCount(body.minSendable);
|
||||
const maxSendable = toCount(body.maxSendable);
|
||||
if (minSendable === null || maxSendable === null || minSendable > maxSendable) {
|
||||
throw new Error('Lightning service returned invalid payment limits');
|
||||
}
|
||||
|
||||
return {
|
||||
callback: callback.toString(),
|
||||
minSendable,
|
||||
maxSendable,
|
||||
metadata: typeof body.metadata === 'string' ? body.metadata : '',
|
||||
allowsNostr: body.allowsNostr === true,
|
||||
nostrPubkey: typeof body.nostrPubkey === 'string' ? body.nostrPubkey : undefined,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import type { Tool, ToolResult } from "./Tool";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import { typecheckProject, type TypecheckDiagnostic } from "../typecheck";
|
||||
|
||||
const MAX_REPORTED_ERRORS = 50;
|
||||
|
||||
function formatDiagnostic(diagnostic: TypecheckDiagnostic): string {
|
||||
const location = diagnostic.file
|
||||
? `${diagnostic.file}(${diagnostic.line},${diagnostic.column}): `
|
||||
: "";
|
||||
return `${location}error TS${diagnostic.code}: ${diagnostic.message}`;
|
||||
}
|
||||
|
||||
export class TypecheckProjectTool implements Tool<void> {
|
||||
private fs: JSRuntimeFS;
|
||||
private cwd: string;
|
||||
|
||||
readonly description = "Typecheck the project with the TypeScript compiler, similar to running `tsc --noEmit`. Reports type errors across the codebase without emitting any files. Use this tool to verify that your changes are type-safe.";
|
||||
|
||||
constructor(fs: JSRuntimeFS, cwd: string) {
|
||||
this.fs = fs;
|
||||
this.cwd = cwd;
|
||||
}
|
||||
|
||||
async execute(): Promise<ToolResult> {
|
||||
const result = await typecheckProject({
|
||||
fs: this.fs,
|
||||
projectPath: this.cwd,
|
||||
});
|
||||
|
||||
const notes: string[] = [];
|
||||
if (result.missingTypes.length > 0) {
|
||||
notes.push(`⚠️ Type declarations could not be found for: ${result.missingTypes.join(", ")}. Imports from these packages were treated as untyped and not checked.`);
|
||||
}
|
||||
|
||||
if (result.errors.length === 0) {
|
||||
return {
|
||||
content: [
|
||||
`✅ No type errors found. Checked ${result.checkedFileCount} files.`,
|
||||
...notes,
|
||||
].join("\n\n"),
|
||||
};
|
||||
}
|
||||
|
||||
const lines = result.errors.slice(0, MAX_REPORTED_ERRORS).map(formatDiagnostic);
|
||||
if (result.errors.length > MAX_REPORTED_ERRORS) {
|
||||
lines.push(`... and ${result.errors.length - MAX_REPORTED_ERRORS} more errors`);
|
||||
}
|
||||
|
||||
throw new Error([
|
||||
`❌ Found ${result.errors.length} type error${result.errors.length === 1 ? "" : "s"}:`,
|
||||
lines.join("\n"),
|
||||
...notes,
|
||||
].join("\n\n"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,653 @@
|
||||
import * as JSONC from "jsonc-parser";
|
||||
import { setupTypeAcquisition } from "@typescript/ata";
|
||||
|
||||
import type tsNamespace from "typescript";
|
||||
import type { JSRuntimeFS } from "@/lib/JSRuntime";
|
||||
|
||||
type TS = typeof tsNamespace;
|
||||
|
||||
export interface TypecheckProjectOptions {
|
||||
fs: JSRuntimeFS;
|
||||
projectPath: string;
|
||||
}
|
||||
|
||||
export interface TypecheckDiagnostic {
|
||||
/** Path relative to the project root, or undefined for global diagnostics */
|
||||
file?: string;
|
||||
/** 1-based line number */
|
||||
line?: number;
|
||||
/** 1-based column number */
|
||||
column?: number;
|
||||
code: number;
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface TypecheckResult {
|
||||
errors: TypecheckDiagnostic[];
|
||||
checkedFileCount: number;
|
||||
/** npm packages whose type declarations could not be acquired; imports from them were not checked */
|
||||
missingTypes: string[];
|
||||
}
|
||||
|
||||
/** Virtual directory where TypeScript's bundled lib.*.d.ts files are mounted */
|
||||
const LIB_DIR = "/__typescript_libs__";
|
||||
|
||||
/** Virtual file providing Vite-style ambient declarations for asset imports */
|
||||
const SHIM_PATH = `${LIB_DIR}/__vite_shim__.d.ts`;
|
||||
|
||||
const EXCLUDED_DIRS = new Set(["node_modules", "dist", "coverage"]);
|
||||
|
||||
const SOURCE_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts"];
|
||||
const JS_EXTENSIONS = [".js", ".jsx", ".mjs", ".cjs"];
|
||||
|
||||
/** Diagnostic codes produced when a module's declarations cannot be found */
|
||||
const MISSING_MODULE_CODES = new Set([
|
||||
2307, // Cannot find module 'X' or its corresponding type declarations.
|
||||
2688, // Cannot find type definition file for 'X'.
|
||||
7016, // Could not find a declaration file for module 'X'.
|
||||
]);
|
||||
|
||||
/**
|
||||
* Ambient declarations for Vite-specific imports (assets, CSS, import.meta.env).
|
||||
* Only used when the project's `vite` types could not be acquired; mirrors a
|
||||
* subset of `vite/client`. Lives in a .d.ts file, so `skipLibCheck` suppresses
|
||||
* any conflicts if the real vite/client types are also present.
|
||||
*/
|
||||
const VITE_SHIM = `
|
||||
declare module "*.module.css" { const classes: { readonly [key: string]: string }; export default classes; }
|
||||
declare module "*.css" { const css: string; export default css; }
|
||||
declare module "*.scss" { const css: string; export default css; }
|
||||
declare module "*.sass" { const css: string; export default css; }
|
||||
declare module "*.less" { const css: string; export default css; }
|
||||
declare module "*.svg" { const src: string; export default src; }
|
||||
declare module "*.png" { const src: string; export default src; }
|
||||
declare module "*.jpg" { const src: string; export default src; }
|
||||
declare module "*.jpeg" { const src: string; export default src; }
|
||||
declare module "*.gif" { const src: string; export default src; }
|
||||
declare module "*.webp" { const src: string; export default src; }
|
||||
declare module "*.avif" { const src: string; export default src; }
|
||||
declare module "*.ico" { const src: string; export default src; }
|
||||
declare module "*.bmp" { const src: string; export default src; }
|
||||
declare module "*.mp3" { const src: string; export default src; }
|
||||
declare module "*.wav" { const src: string; export default src; }
|
||||
declare module "*.ogg" { const src: string; export default src; }
|
||||
declare module "*.flac" { const src: string; export default src; }
|
||||
declare module "*.aac" { const src: string; export default src; }
|
||||
declare module "*.mp4" { const src: string; export default src; }
|
||||
declare module "*.webm" { const src: string; export default src; }
|
||||
declare module "*.woff" { const src: string; export default src; }
|
||||
declare module "*.woff2" { const src: string; export default src; }
|
||||
declare module "*.ttf" { const src: string; export default src; }
|
||||
declare module "*.otf" { const src: string; export default src; }
|
||||
declare module "*.eot" { const src: string; export default src; }
|
||||
declare module "*.wasm" { const src: string; export default src; }
|
||||
declare module "*.pdf" { const src: string; export default src; }
|
||||
declare module "*.txt" { const src: string; export default src; }
|
||||
declare module "*?raw" { const content: string; export default content; }
|
||||
declare module "*?url" { const url: string; export default url; }
|
||||
declare module "*?inline" { const content: string; export default content; }
|
||||
declare module "*?worker" {
|
||||
const workerConstructor: { new (options?: { name?: string }): Worker };
|
||||
export default workerConstructor;
|
||||
}
|
||||
interface ImportMeta {
|
||||
readonly env: Record<string, any>;
|
||||
readonly hot?: Record<string, any>;
|
||||
glob(pattern: string | string[], options?: Record<string, unknown>): Record<string, any>;
|
||||
}
|
||||
`;
|
||||
|
||||
interface RawTsConfig {
|
||||
extends?: string;
|
||||
compilerOptions?: Record<string, unknown>;
|
||||
include?: string[];
|
||||
exclude?: string[];
|
||||
files?: string[];
|
||||
references?: { path: string }[];
|
||||
}
|
||||
|
||||
interface ProjectPackageJson {
|
||||
dependencies?: Record<string, string>;
|
||||
devDependencies?: Record<string, string>;
|
||||
peerDependencies?: Record<string, string>;
|
||||
}
|
||||
|
||||
interface ProjectPackageLock {
|
||||
packages?: Record<string, { version?: string } | undefined>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Run async tasks with a maximum number in flight at once. The browser fails
|
||||
* requests with ERR_INSUFFICIENT_RESOURCES if too many start simultaneously.
|
||||
*/
|
||||
function createLimiter(limit: number): <T>(task: () => Promise<T>) => Promise<T> {
|
||||
let active = 0;
|
||||
const queue: (() => void)[] = [];
|
||||
|
||||
const next = () => {
|
||||
active--;
|
||||
queue.shift()?.();
|
||||
};
|
||||
|
||||
return async (task) => {
|
||||
if (active >= limit) {
|
||||
await new Promise<void>((resolve) => queue.push(resolve));
|
||||
}
|
||||
active++;
|
||||
try {
|
||||
return await task();
|
||||
} finally {
|
||||
next();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/** Concurrency cap for all network activity performed during a typecheck */
|
||||
const limit = createLimiter(16);
|
||||
|
||||
/** fetch wrapper passed to ATA so dependency downloads don't flood the browser */
|
||||
const limitedFetch: typeof fetch = (input, init) => limit(() => fetch(input, init));
|
||||
|
||||
/**
|
||||
* Lazy loaders for TypeScript's bundled default library files. Each file
|
||||
* becomes its own chunk, loaded on first typecheck and cached afterwards.
|
||||
*/
|
||||
const libFileLoaders = import.meta.glob<string>(
|
||||
"/node_modules/typescript/lib/lib*.d.ts",
|
||||
{ query: "?raw", import: "default" },
|
||||
);
|
||||
|
||||
let libFilesPromise: Promise<Map<string, string>> | undefined;
|
||||
|
||||
function loadLibFiles(): Promise<Map<string, string>> {
|
||||
libFilesPromise ??= (async () => {
|
||||
const entries = await Promise.all(
|
||||
Object.entries(libFileLoaders).map(async ([path, load]) => {
|
||||
const name = path.slice(path.lastIndexOf("/") + 1);
|
||||
return [`${LIB_DIR}/${name}`, await limit(load)] as const;
|
||||
}),
|
||||
);
|
||||
return new Map(entries);
|
||||
})();
|
||||
return libFilesPromise;
|
||||
}
|
||||
|
||||
/** Cache of acquired type declarations, keyed by the synthetic ATA entry source */
|
||||
const typeAcquisitionCache = new Map<string, Promise<Map<string, string>>>();
|
||||
|
||||
const silentLogger = {
|
||||
log: () => {},
|
||||
error: () => {},
|
||||
groupCollapsed: () => {},
|
||||
groupEnd: () => {},
|
||||
};
|
||||
|
||||
/**
|
||||
* Download type declarations for the project's npm dependencies from jsdelivr
|
||||
* using TypeScript's Automatic Type Acquisition. Returns a map of
|
||||
* `/node_modules/...` paths to file contents.
|
||||
*/
|
||||
function acquireTypes(ts: TS, entrySource: string): Promise<Map<string, string>> {
|
||||
const cached = typeAcquisitionCache.get(entrySource);
|
||||
if (cached) return cached;
|
||||
|
||||
const promise = (async () => {
|
||||
const files = new Map<string, string>();
|
||||
const ata = setupTypeAcquisition({
|
||||
projectName: "shakespeare",
|
||||
typescript: ts,
|
||||
logger: silentLogger,
|
||||
fetcher: limitedFetch,
|
||||
delegate: {
|
||||
// First write wins: version-pinned packages are requested up front, so
|
||||
// they must not be overwritten by transitively-discovered "latest" types
|
||||
receivedFile: (code, path) => {
|
||||
if (!files.has(path)) files.set(path, code);
|
||||
},
|
||||
errorMessage: () => {},
|
||||
},
|
||||
});
|
||||
await ata(entrySource);
|
||||
return files;
|
||||
})();
|
||||
|
||||
// Don't cache failures (e.g. network errors) so a retry can succeed
|
||||
promise.catch(() => typeAcquisitionCache.delete(entrySource));
|
||||
typeAcquisitionCache.set(entrySource, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
/** Resolve "." and ".." segments and collapse duplicate slashes */
|
||||
function normalizePath(path: string): string {
|
||||
const isAbsolute = path.startsWith("/");
|
||||
const out: string[] = [];
|
||||
for (const part of path.split("/")) {
|
||||
if (part === "" || part === ".") continue;
|
||||
if (part === "..") {
|
||||
out.pop();
|
||||
continue;
|
||||
}
|
||||
out.push(part);
|
||||
}
|
||||
return (isAbsolute ? "/" : "") + out.join("/");
|
||||
}
|
||||
|
||||
function extensionOf(name: string): string {
|
||||
const dot = name.lastIndexOf(".");
|
||||
return dot === -1 ? "" : name.slice(dot).toLowerCase();
|
||||
}
|
||||
|
||||
/** Extract the npm package name from a bare module specifier */
|
||||
function packageNameFromSpecifier(specifier: string): string {
|
||||
const parts = specifier.split("/");
|
||||
return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
|
||||
}
|
||||
|
||||
/** Prefixes from tsconfig `paths` (e.g. "@/") used to distinguish aliases from npm packages */
|
||||
function aliasPrefixesFrom(options: tsNamespace.CompilerOptions): string[] {
|
||||
return Object.keys(options.paths ?? {}).map((key) => key.replace(/\*.*$/, ""));
|
||||
}
|
||||
|
||||
function isBareSpecifier(specifier: string, aliasPrefixes: string[]): boolean {
|
||||
if (specifier.startsWith(".") || specifier.startsWith("/")) return false;
|
||||
if (specifier.includes(":")) return false; // node:, https:, virtual:, etc.
|
||||
return !aliasPrefixes.some((prefix) => prefix !== "" && specifier.startsWith(prefix));
|
||||
}
|
||||
|
||||
/** DefinitelyTyped package name for an npm package (e.g. "@foo/bar" -> "@types/foo__bar") */
|
||||
function dtPackageName(name: string): string {
|
||||
return `@types/${name.startsWith("@") ? name.slice(1).replace("/", "__") : name}`;
|
||||
}
|
||||
|
||||
function declaredRange(packageJson: ProjectPackageJson, name: string): string | undefined {
|
||||
return (
|
||||
packageJson.dependencies?.[name] ??
|
||||
packageJson.devDependencies?.[name] ??
|
||||
packageJson.peerDependencies?.[name]
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Best version to request from jsdelivr for a package: the exact locked
|
||||
* version if available, otherwise the package.json range with any leading
|
||||
* operator stripped. ATA only supports exact versions or single-segment
|
||||
* ranges like "18", so ranges such as "^18.3.1" must be reduced.
|
||||
*/
|
||||
function pinnedVersion(
|
||||
packageJson: ProjectPackageJson,
|
||||
packageLock: ProjectPackageLock,
|
||||
name: string,
|
||||
): string | undefined {
|
||||
const locked = packageLock.packages?.[`node_modules/${name}`]?.version;
|
||||
if (locked) return locked;
|
||||
|
||||
const range = declaredRange(packageJson, name);
|
||||
if (!range) return undefined;
|
||||
|
||||
const stripped = range.replace(/^[\s~^>=<v]+/, "");
|
||||
return /^\d/.test(stripped) ? stripped : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a synthetic TypeScript source file that imports every npm package the
|
||||
* project references, pinned via ATA's `// types: <version>` comment
|
||||
* convention. When the project declares a matching `@types/*` package, that
|
||||
* package is requested directly at its pinned version, because ATA's own
|
||||
* DefinitelyTyped fallback always downloads the latest version.
|
||||
*/
|
||||
function buildAtaEntrySource(
|
||||
ts: TS,
|
||||
sourceTexts: string[],
|
||||
packageJson: ProjectPackageJson,
|
||||
packageLock: ProjectPackageLock,
|
||||
aliasPrefixes: string[],
|
||||
): string {
|
||||
const packages = new Map<string, string | undefined>();
|
||||
|
||||
const add = (name: string) => {
|
||||
if (packages.has(name)) return;
|
||||
packages.set(name, pinnedVersion(packageJson, packageLock, name));
|
||||
};
|
||||
|
||||
for (const text of sourceTexts) {
|
||||
const meta = ts.preProcessFile(text, true, true);
|
||||
const refs = [...meta.importedFiles, ...meta.typeReferenceDirectives];
|
||||
|
||||
for (const ref of refs) {
|
||||
if (!isBareSpecifier(ref.fileName, aliasPrefixes)) continue;
|
||||
const name = packageNameFromSpecifier(ref.fileName);
|
||||
if (!name) continue;
|
||||
|
||||
const dtName = dtPackageName(name);
|
||||
if (!name.startsWith("@types/") && declaredRange(packageJson, dtName)) {
|
||||
add(dtName);
|
||||
} else {
|
||||
add(name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [...packages.entries()]
|
||||
.sort(([a], [b]) => a.localeCompare(b))
|
||||
.map(([name, version]) => (version ? `import "${name}" // types: ${version}` : `import "${name}"`))
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
/** Read a tsconfig file, following local `extends` chains */
|
||||
async function readRawConfig(fs: JSRuntimeFS, path: string, depth = 0): Promise<RawTsConfig | undefined> {
|
||||
if (depth > 5) return undefined;
|
||||
|
||||
let text: string;
|
||||
try {
|
||||
text = await fs.readFile(path, "utf8");
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const config = (JSONC.parse(text) ?? {}) as RawTsConfig;
|
||||
|
||||
if (typeof config.extends === "string" && config.extends.startsWith(".")) {
|
||||
const dir = path.slice(0, path.lastIndexOf("/"));
|
||||
const extendsPath = config.extends.endsWith(".json") ? config.extends : `${config.extends}.json`;
|
||||
const parent = await readRawConfig(fs, normalizePath(`${dir}/${extendsPath}`), depth + 1);
|
||||
if (parent) {
|
||||
return {
|
||||
...parent,
|
||||
...config,
|
||||
compilerOptions: { ...parent.compilerOptions, ...config.compilerOptions },
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the effective tsconfig for the project. Handles Vite-style project
|
||||
* references (tsconfig.json + tsconfig.app.json) by preferring the app config.
|
||||
*/
|
||||
async function resolveConfig(fs: JSRuntimeFS, projectPath: string): Promise<RawTsConfig> {
|
||||
const root = await readRawConfig(fs, `${projectPath}/tsconfig.json`);
|
||||
if (!root) return {};
|
||||
|
||||
const hasOwnScope = Boolean(root.include?.length || root.files?.length);
|
||||
if (hasOwnScope || !root.references?.length) return root;
|
||||
|
||||
const candidates = [
|
||||
"tsconfig.app.json",
|
||||
...root.references.map((ref) => (ref.path.endsWith(".json") ? ref.path : `${ref.path}/tsconfig.json`)),
|
||||
];
|
||||
|
||||
for (const candidate of candidates) {
|
||||
const config = await readRawConfig(fs, normalizePath(`${projectPath}/${candidate}`));
|
||||
if (config && (config.include?.length || config.files?.length)) return config;
|
||||
}
|
||||
|
||||
return root;
|
||||
}
|
||||
|
||||
/** Recursively read all source-relevant project files into memory */
|
||||
async function readProjectFiles(fs: JSRuntimeFS, projectPath: string): Promise<Map<string, string>> {
|
||||
const files = new Map<string, string>();
|
||||
const relevantExtensions = new Set([...SOURCE_EXTENSIONS, ...JS_EXTENSIONS, ".json"]);
|
||||
|
||||
async function walk(dir: string): Promise<void> {
|
||||
let entries;
|
||||
try {
|
||||
entries = await fs.readdir(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
|
||||
await Promise.all(
|
||||
entries.map(async (entry) => {
|
||||
const path = `${dir}/${entry.name}`;
|
||||
if (entry.isDirectory()) {
|
||||
if (EXCLUDED_DIRS.has(entry.name) || entry.name.startsWith(".")) return;
|
||||
await walk(path);
|
||||
} else if (relevantExtensions.has(extensionOf(entry.name))) {
|
||||
try {
|
||||
files.set(path, await fs.readFile(path, "utf8"));
|
||||
} catch {
|
||||
// Skip unreadable files
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
await walk(projectPath);
|
||||
return files;
|
||||
}
|
||||
|
||||
/** Convert tsconfig include/exclude patterns to simple directory/file prefixes */
|
||||
function patternPrefixes(patterns: string[] | undefined): string[] | undefined {
|
||||
if (!patterns?.length) return undefined;
|
||||
return patterns.map((pattern) => {
|
||||
let prefix = pattern.replace(/^\.\//, "");
|
||||
const globIndex = prefix.search(/[*?[{]/);
|
||||
if (globIndex !== -1) {
|
||||
prefix = prefix.slice(0, globIndex);
|
||||
prefix = prefix.slice(0, prefix.lastIndexOf("/") + 1);
|
||||
}
|
||||
return prefix.replace(/\/+$/, "");
|
||||
});
|
||||
}
|
||||
|
||||
function matchesPrefix(relativePath: string, prefixes: string[]): boolean {
|
||||
return prefixes.some(
|
||||
(prefix) => prefix === "" || relativePath === prefix || relativePath.startsWith(`${prefix}/`),
|
||||
);
|
||||
}
|
||||
|
||||
/** Select the program root files based on the tsconfig include/exclude/files settings */
|
||||
function selectRootFiles(
|
||||
projectFiles: Map<string, string>,
|
||||
projectPath: string,
|
||||
config: RawTsConfig,
|
||||
options: tsNamespace.CompilerOptions,
|
||||
): string[] {
|
||||
const include = patternPrefixes(config.include);
|
||||
const exclude = patternPrefixes(config.exclude);
|
||||
const checkedExtensions = new Set(options.allowJs ? [...SOURCE_EXTENSIONS, ...JS_EXTENSIONS] : SOURCE_EXTENSIONS);
|
||||
|
||||
const rootFiles = new Set<string>();
|
||||
|
||||
for (const path of projectFiles.keys()) {
|
||||
if (!checkedExtensions.has(extensionOf(path))) continue;
|
||||
const relativePath = path.slice(projectPath.length + 1);
|
||||
if (include && !matchesPrefix(relativePath, include)) continue;
|
||||
if (exclude && matchesPrefix(relativePath, exclude)) continue;
|
||||
rootFiles.add(path);
|
||||
}
|
||||
|
||||
for (const file of config.files ?? []) {
|
||||
const path = normalizePath(`${projectPath}/${file}`);
|
||||
if (projectFiles.has(path)) rootFiles.add(path);
|
||||
}
|
||||
|
||||
return [...rootFiles].sort();
|
||||
}
|
||||
|
||||
function createCompilerHost(
|
||||
ts: TS,
|
||||
files: Map<string, string>,
|
||||
projectPath: string,
|
||||
): tsNamespace.CompilerHost {
|
||||
const directories = new Set<string>(["/"]);
|
||||
for (const path of files.keys()) {
|
||||
let dir = path.slice(0, path.lastIndexOf("/"));
|
||||
while (dir && !directories.has(dir)) {
|
||||
directories.add(dir);
|
||||
dir = dir.slice(0, dir.lastIndexOf("/"));
|
||||
}
|
||||
}
|
||||
|
||||
const sourceFileCache = new Map<string, tsNamespace.SourceFile>();
|
||||
|
||||
return {
|
||||
fileExists: (path) => files.has(normalizePath(path)),
|
||||
readFile: (path) => files.get(normalizePath(path)),
|
||||
directoryExists: (path) => directories.has(normalizePath(path)),
|
||||
getDirectories: (path) => {
|
||||
const prefix = normalizePath(path);
|
||||
const base = prefix === "/" ? "/" : `${prefix}/`;
|
||||
const result = new Set<string>();
|
||||
for (const dir of directories) {
|
||||
if (dir.startsWith(base) && dir !== prefix) {
|
||||
const first = dir.slice(base.length).split("/")[0];
|
||||
if (first) result.add(first);
|
||||
}
|
||||
}
|
||||
return [...result];
|
||||
},
|
||||
getSourceFile: (fileName, languageVersionOrOptions) => {
|
||||
const path = normalizePath(fileName);
|
||||
const cached = sourceFileCache.get(path);
|
||||
if (cached) return cached;
|
||||
const text = files.get(path);
|
||||
if (text === undefined) return undefined;
|
||||
const sourceFile = ts.createSourceFile(path, text, languageVersionOrOptions, true);
|
||||
sourceFileCache.set(path, sourceFile);
|
||||
return sourceFile;
|
||||
},
|
||||
getDefaultLibLocation: () => LIB_DIR,
|
||||
getDefaultLibFileName: (options) => `${LIB_DIR}/${ts.getDefaultLibFileName(options)}`,
|
||||
writeFile: () => {},
|
||||
getCurrentDirectory: () => projectPath,
|
||||
getCanonicalFileName: (fileName) => fileName,
|
||||
useCaseSensitiveFileNames: () => true,
|
||||
getNewLine: () => "\n",
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Typecheck a project in the virtual filesystem with the TypeScript compiler,
|
||||
* equivalent to running `tsc --noEmit`. Type declarations for npm dependencies
|
||||
* are downloaded from jsdelivr (the VFS has no node_modules) and cached for
|
||||
* the session.
|
||||
*/
|
||||
export async function typecheckProject({ fs, projectPath }: TypecheckProjectOptions): Promise<TypecheckResult> {
|
||||
const tsModule = await import("typescript");
|
||||
const ts = (tsModule.default ?? tsModule) as TS;
|
||||
|
||||
const [libFiles, projectFiles, config] = await Promise.all([
|
||||
loadLibFiles(),
|
||||
readProjectFiles(fs, projectPath),
|
||||
resolveConfig(fs, projectPath),
|
||||
]);
|
||||
|
||||
const converted = ts.convertCompilerOptionsFromJson(
|
||||
config.compilerOptions ?? {},
|
||||
projectPath,
|
||||
`${projectPath}/tsconfig.json`,
|
||||
);
|
||||
|
||||
const options: tsNamespace.CompilerOptions = {
|
||||
// Defaults for browser projects without a tsconfig; overridden by the project's config
|
||||
target: ts.ScriptTarget.ES2020,
|
||||
module: ts.ModuleKind.ESNext,
|
||||
moduleResolution: ts.ModuleResolutionKind.Bundler,
|
||||
jsx: ts.JsxEmit.ReactJSX,
|
||||
esModuleInterop: true,
|
||||
resolveJsonModule: true,
|
||||
...converted.options,
|
||||
// Forced: check only, never emit; declarations acquired from the CDN are not authoritative
|
||||
noEmit: true,
|
||||
skipLibCheck: true,
|
||||
incremental: false,
|
||||
composite: false,
|
||||
declaration: false,
|
||||
emitDeclarationOnly: false,
|
||||
tsBuildInfoFile: undefined,
|
||||
};
|
||||
|
||||
const rootFiles = selectRootFiles(projectFiles, projectPath, config, options);
|
||||
const aliasPrefixes = aliasPrefixesFrom(options);
|
||||
|
||||
// Acquire type declarations for npm dependencies referenced by the project
|
||||
let packageJson: ProjectPackageJson = {};
|
||||
let packageLock: ProjectPackageLock = {};
|
||||
try {
|
||||
packageJson = JSON.parse(projectFiles.get(`${projectPath}/package.json`) ?? "{}");
|
||||
} catch {
|
||||
// Malformed package.json; acquire latest types instead of pinned versions
|
||||
}
|
||||
try {
|
||||
packageLock = JSON.parse(projectFiles.get(`${projectPath}/package-lock.json`) ?? "{}");
|
||||
} catch {
|
||||
// Malformed lockfile; fall back to package.json ranges
|
||||
}
|
||||
|
||||
const rootTexts = rootFiles.map((path) => projectFiles.get(path) ?? "");
|
||||
const entrySource = buildAtaEntrySource(ts, rootTexts, packageJson, packageLock, aliasPrefixes);
|
||||
|
||||
let acquiredTypes = new Map<string, string>();
|
||||
if (entrySource) {
|
||||
try {
|
||||
acquiredTypes = await acquireTypes(ts, entrySource);
|
||||
} catch {
|
||||
// Offline or CDN failure: check what we can without external types
|
||||
}
|
||||
}
|
||||
|
||||
// Assemble the virtual filesystem for the compiler
|
||||
const files = new Map<string, string>(libFiles);
|
||||
for (const [path, text] of acquiredTypes) {
|
||||
files.set(normalizePath(`${projectPath}${path}`), text);
|
||||
}
|
||||
for (const [path, text] of projectFiles) {
|
||||
files.set(path, text);
|
||||
}
|
||||
|
||||
// Provide Vite ambient types (asset imports, import.meta.env) if the real
|
||||
// vite/client declarations were not acquired
|
||||
const rootNames = [...rootFiles];
|
||||
if (!files.has(`${projectPath}/node_modules/vite/client.d.ts`)) {
|
||||
files.set(SHIM_PATH, VITE_SHIM);
|
||||
rootNames.push(SHIM_PATH);
|
||||
}
|
||||
|
||||
const host = createCompilerHost(ts, files, projectPath);
|
||||
const program = ts.createProgram({ rootNames, options, host });
|
||||
const diagnostics = [...converted.errors, ...ts.getPreEmitDiagnostics(program)];
|
||||
|
||||
const errors: TypecheckDiagnostic[] = [];
|
||||
const missingTypes = new Set<string>();
|
||||
|
||||
for (const diagnostic of diagnostics) {
|
||||
if (diagnostic.category !== ts.DiagnosticCategory.Error) continue;
|
||||
|
||||
const fileName = diagnostic.file?.fileName;
|
||||
if (fileName && (fileName.includes("/node_modules/") || fileName.startsWith(LIB_DIR))) continue;
|
||||
|
||||
const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
|
||||
|
||||
// Missing declarations for npm packages are reported separately, not as
|
||||
// errors: the CDN may simply not have types for that package
|
||||
if (MISSING_MODULE_CODES.has(diagnostic.code)) {
|
||||
const specifier = message.match(/'([^']+)'/)?.[1];
|
||||
if (specifier && isBareSpecifier(specifier, aliasPrefixes)) {
|
||||
missingTypes.add(packageNameFromSpecifier(specifier));
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
const error: TypecheckDiagnostic = { code: diagnostic.code, message };
|
||||
if (diagnostic.file && diagnostic.start !== undefined) {
|
||||
const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
|
||||
error.file = diagnostic.file.fileName.startsWith(`${projectPath}/`)
|
||||
? diagnostic.file.fileName.slice(projectPath.length + 1)
|
||||
: diagnostic.file.fileName;
|
||||
error.line = line + 1;
|
||||
error.column = character + 1;
|
||||
}
|
||||
errors.push(error);
|
||||
}
|
||||
|
||||
return {
|
||||
errors,
|
||||
checkedFileCount: rootFiles.length,
|
||||
missingTypes: [...missingTypes].sort(),
|
||||
};
|
||||
}
|
||||
@@ -109,9 +109,8 @@ export function AISettings() {
|
||||
baseURL: preset.baseURL,
|
||||
};
|
||||
|
||||
const key = apiKey.trim() || preset.apiKey;
|
||||
if (key) {
|
||||
newProvider.apiKey = key;
|
||||
if (apiKey.trim()) {
|
||||
newProvider.apiKey = apiKey.trim();
|
||||
}
|
||||
if (typeof preset.nostr === 'boolean') {
|
||||
newProvider.nostr = preset.nostr;
|
||||
|
||||
@@ -7,16 +7,13 @@ import { useDeploySettings } from '@/hooks/useDeploySettings';
|
||||
import { useNetlifyOAuth } from '@/hooks/useNetlifyOAuth';
|
||||
import { useVercelOAuth } from '@/hooks/useVercelOAuth';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import type { DeployProvider, NpanelProvider } from '@/contexts/DeploySettingsContext';
|
||||
import type { DeployProvider } from '@/contexts/DeploySettingsContext';
|
||||
import type { PresetDeployProvider } from '@/lib/deploy/types';
|
||||
import { PRESET_DEPLOY_PROVIDERS, DEFAULT_NPANEL_PROVIDER, DEFAULT_NSITE_PROVIDER } from '@/lib/deployProviderPresets';
|
||||
import { PRESET_DEPLOY_PROVIDERS, DEFAULT_NSITE_PROVIDER } from '@/lib/deployProviderPresets';
|
||||
import { ExternalFavicon } from '@/components/ExternalFavicon';
|
||||
import { ProviderConfigDialog } from '@/components/ProviderConfigDialog';
|
||||
import { AddDeployProviderDialog } from '@/components/AddDeployProviderDialog';
|
||||
import { AddCustomProviderDialog } from '@/components/AddCustomProviderDialog';
|
||||
import { NpanelMigrationDialog } from '@/components/deploy/NpanelMigrationDialog';
|
||||
import { useNpanelClaimCount } from '@/hooks/useNpanelClaims';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
DndContext,
|
||||
closestCenter,
|
||||
@@ -153,7 +150,6 @@ export function DeploySettings() {
|
||||
const [selectedPreset, setSelectedPreset] = useState<PresetDeployProvider | null>(null);
|
||||
const [addDialogOpen, setAddDialogOpen] = useState(false);
|
||||
const [customProviderDialogOpen, setCustomProviderDialogOpen] = useState(false);
|
||||
const [migratingProvider, setMigratingProvider] = useState<NpanelProvider | null>(null);
|
||||
|
||||
// Drag and drop sensors
|
||||
const sensors = useSensors(
|
||||
@@ -186,20 +182,25 @@ export function DeploySettings() {
|
||||
};
|
||||
|
||||
const handleAddPresetProvider = (preset: PresetDeployProvider, apiKey: string, accountId?: string, organizationId?: string) => {
|
||||
// Nostr-authenticated providers need a login rather than a key
|
||||
// For Shakespeare, just check if user is logged in
|
||||
if (preset.requiresNostr && !user) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Everything else is reached with an API key, except plain nsite
|
||||
// For non-Shakespeare/non-nsite providers, require API key
|
||||
if (!preset.requiresNostr && preset.type !== 'nsite' && !apiKey?.trim()) {
|
||||
return;
|
||||
}
|
||||
|
||||
let newProvider: DeployProvider;
|
||||
|
||||
if (preset.type === 'npanel') {
|
||||
newProvider = { ...DEFAULT_NPANEL_PROVIDER, id: preset.id, name: preset.name };
|
||||
if (preset.type === 'shakespeare') {
|
||||
newProvider = {
|
||||
id: preset.id, // Use preset ID for presets
|
||||
name: preset.name,
|
||||
type: 'shakespeare',
|
||||
...(preset.proxy && { proxy: true }),
|
||||
};
|
||||
} else if (preset.type === 'nsite') {
|
||||
newProvider = { ...DEFAULT_NSITE_PROVIDER };
|
||||
} else if (preset.type === 'netlify') {
|
||||
@@ -345,24 +346,6 @@ export function DeploySettings() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{user && settings.providers.map((provider) => (
|
||||
provider.type === 'npanel' ? (
|
||||
<HeldSites
|
||||
key={`migrate-${provider.id}`}
|
||||
provider={provider}
|
||||
onOpen={() => setMigratingProvider(provider)}
|
||||
/>
|
||||
) : null
|
||||
))}
|
||||
|
||||
{migratingProvider && (
|
||||
<NpanelMigrationDialog
|
||||
open
|
||||
onOpenChange={(open) => !open && setMigratingProvider(null)}
|
||||
provider={migratingProvider}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Provider Config Dialog */}
|
||||
{selectedProviderIndex !== null && settings.providers[selectedProviderIndex] && (
|
||||
<ProviderConfigDialog
|
||||
@@ -427,45 +410,4 @@ export function DeploySettings() {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sites held for their previous owner on a gateway that took over a domain.
|
||||
*
|
||||
* The count is asked for on load, rather than the card standing there saying
|
||||
* "you may have sites waiting" to everyone forever. Almost nobody does, and a
|
||||
* card that cannot tell them apart is one most people learn to ignore before
|
||||
* it ever applies to them — while the person it does apply to has a few names
|
||||
* being served from an archive under a key that is not theirs, which is worth
|
||||
* one signature to say out loud.
|
||||
*
|
||||
* It is only the count: {@link useNpanelClaimCount} is two counted rows, not
|
||||
* the deploy-by-deploy read the dialog does when somebody opens it.
|
||||
*/
|
||||
function HeldSites({ provider, onOpen }: { provider: NpanelProvider; onOpen: () => void }) {
|
||||
const { data } = useNpanelClaimCount(provider);
|
||||
|
||||
// Nothing to say until the gateway says there is something, so a gateway with
|
||||
// no migration behind it — every gateway but the one — shows nothing at all.
|
||||
if (!data?.waiting) return null;
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-dashed p-4 flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="space-y-1">
|
||||
<h4 className="text-sm font-medium">
|
||||
{data.waiting === 1
|
||||
? `One name is waiting for you on ${provider.domain}`
|
||||
: `${data.waiting} names are waiting for you on ${provider.domain}`}
|
||||
</h4>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
You published {data.waiting === 1 ? 'it' : 'them'} before {provider.domain} moved to{' '}
|
||||
{provider.name}. {data.waiting === 1 ? 'It is' : 'They are'} being served from an archive
|
||||
until you take {data.waiting === 1 ? 'it' : 'them'} back.
|
||||
</p>
|
||||
</div>
|
||||
<Button variant="outline" onClick={onOpen}>
|
||||
Take back sites
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default DeploySettings;
|
||||
@@ -34,81 +34,6 @@ class LocalStorageMock implements Storage {
|
||||
|
||||
global.localStorage = new LocalStorageMock();
|
||||
|
||||
// The @nostrify/react 0.6.6 NostrLoginProvider resolves stored logins on a
|
||||
// microtask: it renders a null `fallback` on the first synchronous paint and
|
||||
// only mounts its children once storage resolves. Component/hook tests render
|
||||
// synchronously and query immediately, so they'd observe an empty tree (this is
|
||||
// the sole cause of the render breakage introduced by the upgrade). Replace the
|
||||
// provider — and the hook that reads its context — with a synchronous
|
||||
// equivalent for tests, importing everything else (NLogin.nostrconnect and the
|
||||
// connect helpers, whose handshake enforcement is the point of the upgrade;
|
||||
// NUser) from the real module untouched.
|
||||
vi.mock('@nostrify/react/login', async (importActual) => {
|
||||
const actual = await importActual<typeof import('@nostrify/react/login')>();
|
||||
const { createContext, useContext, useReducer, useEffect, createElement } = await import('react');
|
||||
|
||||
const NostrLoginContext = createContext<unknown>(undefined);
|
||||
|
||||
type Login = { id: string };
|
||||
type LoginAction =
|
||||
| { type: 'login.add'; login: Login; set?: boolean }
|
||||
| { type: 'login.remove'; id: string }
|
||||
| { type: 'login.set'; id: string }
|
||||
| { type: 'login.clear' };
|
||||
|
||||
function reducer(state: Login[], action: LoginAction): Login[] {
|
||||
switch (action.type) {
|
||||
case 'login.add': {
|
||||
const filtered = state.filter((l) => l.id !== action.login.id);
|
||||
return action.set ? [action.login, ...filtered] : [...filtered, action.login];
|
||||
}
|
||||
case 'login.remove':
|
||||
return state.filter((l) => l.id !== action.id);
|
||||
case 'login.set': {
|
||||
const login = state.find((l) => l.id === action.id);
|
||||
if (!login) return state;
|
||||
return [login, ...state.filter((l) => l.id !== action.id)];
|
||||
}
|
||||
case 'login.clear':
|
||||
return [];
|
||||
default:
|
||||
return state;
|
||||
}
|
||||
}
|
||||
|
||||
const NostrLoginProvider = ({ children, storageKey, storage = localStorage }: {
|
||||
children: React.ReactNode;
|
||||
storageKey: string;
|
||||
storage?: Storage;
|
||||
}) => {
|
||||
const [state, dispatch] = useReducer(reducer, undefined, (): Login[] => {
|
||||
const stored = storage.getItem(storageKey);
|
||||
return typeof stored === 'string' ? (JSON.parse(stored) as Login[]) : [];
|
||||
});
|
||||
useEffect(() => {
|
||||
storage.setItem(storageKey, JSON.stringify(state));
|
||||
}, [state, storageKey, storage]);
|
||||
const value = {
|
||||
logins: state,
|
||||
addLogin: (login: Login) => dispatch({ type: 'login.add', login }),
|
||||
removeLogin: (id: string) => dispatch({ type: 'login.remove', id }),
|
||||
setLogin: (id: string) => dispatch({ type: 'login.set', id }),
|
||||
clearLogins: () => dispatch({ type: 'login.clear' }),
|
||||
};
|
||||
return createElement(NostrLoginContext.Provider, { value }, children);
|
||||
};
|
||||
|
||||
function useNostrLogin() {
|
||||
const context = useContext(NostrLoginContext);
|
||||
if (!context) {
|
||||
throw new Error('useNostrLogin must be used within a NostrLoginProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
return { ...actual, NostrLoginProvider, useNostrLogin };
|
||||
});
|
||||
|
||||
// Mock CSS imports
|
||||
vi.mock('*.css', () => ({}));
|
||||
vi.mock('*.scss', () => ({}));
|
||||
|
||||
Reference in new issue
Block a user