mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
431b8ec6bb | ||
|
|
77b2be7a3b | ||
|
|
90d02c42d6 | ||
|
|
d3cceb56ee | ||
|
|
fd23c10f20 | ||
|
|
0d73c79d4c | ||
|
|
f951f21535 | ||
|
|
a20fab1ab4 | ||
|
|
97714079d3 | ||
|
|
01d20c5743 | ||
|
|
f2612831c6 | ||
|
|
278b7cd3b2 | ||
|
|
a824677fe2 | ||
|
|
0eb8693d10 | ||
|
|
9557356ff5 | ||
|
|
dbbdcc32eb | ||
|
|
acde1d8a3a | ||
|
|
5d02627cff | ||
|
|
317c923532 | ||
|
|
18815f0649 | ||
|
|
98985c29de | ||
|
|
ba422b2d9e | ||
|
|
9313d2e0ee | ||
|
|
0013ece013 | ||
|
|
0da339c214 |
No files matched your search
+2
-1
@@ -42,8 +42,9 @@ deploy:
|
||||
- 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 --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
|
||||
|
||||
@@ -0,0 +1,120 @@
|
||||
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. 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.
|
||||
# nsyte is baked into the coordinator's CI image, alongside zsp and
|
||||
# the rest (armada's .ngit/ci-image/Dockerfile). Downloading it at
|
||||
# job time is the fallback for a coordinator that does not have it,
|
||||
# and is exactly what kept failing here: the 115 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.
|
||||
if command -v nsyte >/dev/null 2>&1; then
|
||||
echo "using the nsyte baked into the runner image"
|
||||
else
|
||||
NSYTE_URL=https://github.com/sandwichfarm/nsyte/releases/download/v0.27.2/nsyte-linux-0.27.2
|
||||
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
|
||||
@@ -0,0 +1,31 @@
|
||||
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
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"$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"
|
||||
}
|
||||
@@ -1,5 +1,27 @@
|
||||
# Changelog
|
||||
|
||||
## [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
|
||||
- Log in with a remote signer by scanning a QR code — connect your NIP-46 mobile signer to Shakespeare without copying and pasting bunker strings
|
||||
|
||||
### Changed
|
||||
- Unified the login dialog into a single, streamlined experience across sign-in methods
|
||||
|
||||
### Fixed
|
||||
- Custom fonts now load correctly in previews instead of triggering a runtime error
|
||||
- Builds no longer fail when a project depends on types-only packages
|
||||
- Resolved all known security vulnerabilities in dependencies
|
||||
|
||||
## [9.13.2] - 2026-04-29
|
||||
|
||||
### Changed
|
||||
|
||||
Generated
+665
-679
File diff suppressed because it is too large.
Load diff
+4
-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.13.2",
|
||||
"version": "9.15.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.51.1",
|
||||
"@nostrify/react": "^0.4.1",
|
||||
"@nostrify/nostrify": "^0.54.1",
|
||||
"@nostrify/react": "^0.6.6",
|
||||
"@opensecret/react": "^1.5.4",
|
||||
"@plausible-analytics/tracker": "^0.4.4",
|
||||
"@radix-ui/react-accordion": "^1.2.0",
|
||||
@@ -151,6 +151,6 @@
|
||||
"typescript-eslint": "^8.0.1",
|
||||
"vite": "^6.3.5",
|
||||
"vite-plugin-pwa": "^1.1.0",
|
||||
"vitest": "^3.1.4"
|
||||
"vitest": "^4.1.8"
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,27 @@
|
||||
# Changelog
|
||||
|
||||
## [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
|
||||
- Log in with a remote signer by scanning a QR code — connect your NIP-46 mobile signer to Shakespeare without copying and pasting bunker strings
|
||||
|
||||
### Changed
|
||||
- Unified the login dialog into a single, streamlined experience across sign-in methods
|
||||
|
||||
### Fixed
|
||||
- Custom fonts now load correctly in previews instead of triggering a runtime error
|
||||
- Builds no longer fail when a project depends on types-only packages
|
||||
- Resolved all known security vulnerabilities in dependencies
|
||||
|
||||
## [9.13.2] - 2026-04-29
|
||||
|
||||
### Changed
|
||||
|
||||
@@ -63,6 +63,7 @@ const defaultConfig: AppConfig = {
|
||||
relays: [
|
||||
{ url: 'wss://git.shakespeare.diy/' },
|
||||
{ url: 'wss://relay.ngit.dev/' },
|
||||
{ url: 'wss://git.nostrhub.io/' },
|
||||
],
|
||||
updatedAt: 0,
|
||||
},
|
||||
|
||||
@@ -21,6 +21,7 @@ import GitHubOAuth from "./pages/GitHubOAuth";
|
||||
import NetlifyOAuth from "./pages/NetlifyOAuth";
|
||||
import VercelOAuth from "./pages/VercelOAuth";
|
||||
import OpenRouterOAuth from "./pages/OpenRouterOAuth";
|
||||
import RemoteLoginSuccess from "./pages/RemoteLoginSuccess";
|
||||
import { NIP19Page } from "./pages/NIP19Page";
|
||||
import NotFound from "./pages/NotFound";
|
||||
import { ProjectView } from "./pages/ProjectView";
|
||||
@@ -43,6 +44,7 @@ export function AppRouter() {
|
||||
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
|
||||
<Route path="/oauth/vercel" element={<VercelOAuth />} />
|
||||
<Route path="/oauth/openrouter" element={<OpenRouterOAuth />} />
|
||||
<Route path="/remoteloginsuccess" element={<RemoteLoginSuccess />} />
|
||||
<Route path="/settings" element={<SettingsLayout />}>
|
||||
<Route index element={<Settings />} />
|
||||
<Route path="preferences" element={<Preferences />} />
|
||||
|
||||
@@ -156,7 +156,7 @@ export function AddAIProviderDialog({
|
||||
value={apiKey}
|
||||
onChange={(e) => setApiKey(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && apiKey.trim() && termsAgreed) {
|
||||
if (e.key === 'Enter' && apiKey.trim() && (termsAgreed || !preset.tosURL)) {
|
||||
handleAdd();
|
||||
}
|
||||
}}
|
||||
@@ -165,20 +165,20 @@ export function AddAIProviderDialog({
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* 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 ? (
|
||||
{/* 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 })}{' '}
|
||||
<a
|
||||
href={preset.tosURL}
|
||||
target="_blank"
|
||||
@@ -188,11 +188,9 @@ export function AddAIProviderDialog({
|
||||
>
|
||||
{t('termsOfService')}
|
||||
</a>
|
||||
) : (
|
||||
t('termsOfService')
|
||||
)}
|
||||
</label>
|
||||
</div>
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
@@ -205,7 +203,7 @@ export function AddAIProviderDialog({
|
||||
<Button
|
||||
onClick={handleAdd}
|
||||
disabled={
|
||||
!termsAgreed ||
|
||||
(!!preset.tosURL && !termsAgreed) ||
|
||||
(!!preset.apiKeysURL && !apiKey.trim())
|
||||
}
|
||||
>
|
||||
|
||||
@@ -1,8 +1,26 @@
|
||||
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;
|
||||
@@ -42,6 +60,16 @@ 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 (
|
||||
|
||||
@@ -0,0 +1,344 @@
|
||||
import git from 'isomorphic-git';
|
||||
import { Loader2, Zap } from 'lucide-react';
|
||||
import { DropdownMenuItem } from '@/components/ui/dropdown-menu';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { toast } from '@/hooks/useToast';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
|
||||
/**
|
||||
* "Optimize Repository" entry for the project dropdown.
|
||||
*
|
||||
* Fully self-contained recovery action: clicking it consolidates the
|
||||
* project's git pack files into a single pack containing every reachable
|
||||
* object, deletes the old packs and redundant loose objects, and reports
|
||||
* the size reduction in a toast. A spinner toast is shown while it runs.
|
||||
*
|
||||
* Everything (UI, gc algorithm, state) lives in this one file so the
|
||||
* feature can be removed by deleting this file and its single render
|
||||
* line in ProjectTitleMenu.
|
||||
*/
|
||||
|
||||
/** Projects with an optimization currently in flight (reentrancy guard). */
|
||||
const running = new Set<string>();
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Repository optimization (simplified `git gc` for isomorphic-git repos)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** Yield to the event loop so the UI can paint between batches of work. */
|
||||
function yieldToMain(): Promise<void> {
|
||||
return new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
/** Recursively sum the size of all files under `path`. */
|
||||
async function dirSize(fs: JSRuntimeFS, path: string): Promise<number> {
|
||||
let total = 0;
|
||||
let entries: string[];
|
||||
try {
|
||||
entries = await fs.readdir(path);
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
for (const name of entries) {
|
||||
const child = `${path}/${name}`;
|
||||
try {
|
||||
const stat = await fs.stat(child);
|
||||
if (stat.isDirectory()) {
|
||||
total += await dirSize(fs, child);
|
||||
} else {
|
||||
total += stat.size ?? 0;
|
||||
}
|
||||
} catch {
|
||||
// Skip unreadable entries.
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
/**
|
||||
* Recursively walk a tree, adding every blob/tree OID to `reachable`.
|
||||
* Returns the number of objects that could not be read.
|
||||
*/
|
||||
async function walkTree(
|
||||
fs: JSRuntimeFS,
|
||||
gitdir: string,
|
||||
treeOid: string,
|
||||
reachable: Set<string>,
|
||||
visitedTrees: Set<string>,
|
||||
): Promise<number> {
|
||||
if (visitedTrees.has(treeOid)) return 0;
|
||||
visitedTrees.add(treeOid);
|
||||
|
||||
let tree: Awaited<ReturnType<typeof git.readTree>>;
|
||||
try {
|
||||
tree = await git.readTree({ fs, gitdir, oid: treeOid });
|
||||
} catch {
|
||||
return 1;
|
||||
}
|
||||
reachable.add(treeOid);
|
||||
|
||||
let errors = 0;
|
||||
for (const entry of tree.tree) {
|
||||
if (entry.type === 'tree') {
|
||||
errors += await walkTree(fs, gitdir, entry.oid, reachable, visitedTrees);
|
||||
} else if (entry.type === 'blob') {
|
||||
reachable.add(entry.oid);
|
||||
}
|
||||
// entry.type === 'commit' is a submodule gitlink; skip.
|
||||
}
|
||||
return errors;
|
||||
}
|
||||
|
||||
interface OptimizeResult {
|
||||
bytesBefore: number;
|
||||
bytesAfter: number;
|
||||
/** True when some objects could not be read, so the repo was left untouched. */
|
||||
incomplete: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Consolidate all reachable objects into one new pack, then delete the old
|
||||
* packs and redundant loose objects.
|
||||
*
|
||||
* Non-destructive: every object reachable from any ref or HEAD is preserved.
|
||||
* If any object fails to read during the reachability walk, or the new pack
|
||||
* would be larger than the files it replaces, the repository is left
|
||||
* completely untouched.
|
||||
*/
|
||||
async function optimizeRepository(fs: JSRuntimeFS, dir: string): Promise<OptimizeResult> {
|
||||
const gitdir = `${dir}/.git`;
|
||||
const objectsDir = `${gitdir}/objects`;
|
||||
const packDir = `${objectsDir}/pack`;
|
||||
|
||||
const bytesBefore = await dirSize(fs, objectsDir);
|
||||
|
||||
let oldPackEntries: string[];
|
||||
try {
|
||||
oldPackEntries = await fs.readdir(packDir);
|
||||
} catch {
|
||||
oldPackEntries = [];
|
||||
}
|
||||
|
||||
// 1. Collect ref tips (branches, tags, remotes, stash, HEAD).
|
||||
const tips = new Set<string>();
|
||||
let refs: string[] = [];
|
||||
try {
|
||||
refs = await git.listRefs({ fs, gitdir, filepath: 'refs' });
|
||||
} catch {
|
||||
refs = [];
|
||||
}
|
||||
for (const ref of refs) {
|
||||
try {
|
||||
tips.add(await git.resolveRef({ fs, gitdir, ref: `refs/${ref}` }));
|
||||
} catch {
|
||||
// Broken ref; skip.
|
||||
}
|
||||
}
|
||||
try {
|
||||
tips.add(await git.resolveRef({ fs, gitdir, ref: 'HEAD' }));
|
||||
} catch {
|
||||
// No HEAD (fresh repo).
|
||||
}
|
||||
|
||||
// 2. Walk reachability from every tip.
|
||||
const reachable = new Set<string>();
|
||||
const visitedTrees = new Set<string>();
|
||||
const stack = [...tips];
|
||||
let walkErrors = 0;
|
||||
let steps = 0;
|
||||
|
||||
while (stack.length > 0) {
|
||||
const oid = stack.pop()!;
|
||||
if (reachable.has(oid)) continue;
|
||||
|
||||
let parsed: Awaited<ReturnType<typeof git.readObject>>;
|
||||
try {
|
||||
parsed = await git.readObject({ fs, gitdir, oid, format: 'parsed' });
|
||||
} catch {
|
||||
walkErrors++;
|
||||
continue;
|
||||
}
|
||||
|
||||
reachable.add(oid);
|
||||
|
||||
if (parsed.type === 'commit') {
|
||||
const commit = parsed.object as { tree: string; parent: string[] };
|
||||
for (const parent of commit.parent) stack.push(parent);
|
||||
walkErrors += await walkTree(fs, gitdir, commit.tree, reachable, visitedTrees);
|
||||
} else if (parsed.type === 'tag') {
|
||||
stack.push((parsed.object as { object: string }).object);
|
||||
} else if (parsed.type === 'tree') {
|
||||
walkErrors += await walkTree(fs, gitdir, oid, reachable, visitedTrees);
|
||||
}
|
||||
|
||||
if (++steps % 64 === 0) await yieldToMain();
|
||||
}
|
||||
|
||||
if (walkErrors > 0 || reachable.size === 0) {
|
||||
// Damaged repo (or empty repo) — change nothing.
|
||||
return { bytesBefore, bytesAfter: bytesBefore, incomplete: walkErrors > 0 };
|
||||
}
|
||||
|
||||
// 3. Write the consolidated pack and its index.
|
||||
await yieldToMain();
|
||||
const { filename } = await git.packObjects({
|
||||
fs,
|
||||
gitdir,
|
||||
oids: [...reachable],
|
||||
write: true,
|
||||
});
|
||||
await git.indexPack({ fs, dir, gitdir, filepath: `.git/objects/pack/${filename}` });
|
||||
|
||||
// 4. Safety check: isomorphic-git writes undeltified packs, which can be
|
||||
// larger than the (server-deltified) packs they replace. Only proceed if
|
||||
// deleting the old packs and loose copies reclaims more than the new pack
|
||||
// costs; otherwise remove the new pack and leave the repo exactly as-is.
|
||||
const fileSize = async (path: string): Promise<number> => {
|
||||
try {
|
||||
return (await fs.stat(path)).size ?? 0;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
};
|
||||
const newBase = filename!.replace(/\.pack$/, '');
|
||||
const newPackBytes =
|
||||
(await fileSize(`${packDir}/${filename}`)) + (await fileSize(`${packDir}/${newBase}.idx`));
|
||||
let reclaimableBytes = 0;
|
||||
for (const name of oldPackEntries) {
|
||||
if (name.startsWith(`${newBase}.`)) continue;
|
||||
if (!/\.(pack|idx)$/.test(name)) continue;
|
||||
reclaimableBytes += await fileSize(`${packDir}/${name}`);
|
||||
}
|
||||
steps = 0;
|
||||
for (const oid of reachable) {
|
||||
reclaimableBytes += await fileSize(`${objectsDir}/${oid.slice(0, 2)}/${oid.slice(2)}`);
|
||||
if (++steps % 64 === 0) await yieldToMain();
|
||||
}
|
||||
if (newPackBytes >= reclaimableBytes) {
|
||||
for (const name of [filename!, `${newBase}.idx`]) {
|
||||
try {
|
||||
await fs.unlink(`${packDir}/${name}`);
|
||||
} catch {
|
||||
// Best-effort.
|
||||
}
|
||||
}
|
||||
return { bytesBefore, bytesAfter: bytesBefore, incomplete: false };
|
||||
}
|
||||
|
||||
// 5. Delete the old pack files.
|
||||
for (const name of oldPackEntries) {
|
||||
if (name.startsWith(`${newBase}.`)) continue;
|
||||
if (!/\.(pack|idx)$/.test(name)) continue;
|
||||
try {
|
||||
await fs.unlink(`${packDir}/${name}`);
|
||||
} catch {
|
||||
// Best-effort.
|
||||
}
|
||||
}
|
||||
|
||||
// 6. Delete loose copies of objects now stored in the new pack.
|
||||
const touchedDirs = new Set<string>();
|
||||
steps = 0;
|
||||
for (const oid of reachable) {
|
||||
const looseDir = `${objectsDir}/${oid.slice(0, 2)}`;
|
||||
try {
|
||||
await fs.unlink(`${looseDir}/${oid.slice(2)}`);
|
||||
touchedDirs.add(looseDir);
|
||||
} catch {
|
||||
// Object wasn't loose; nothing to do.
|
||||
}
|
||||
if (++steps % 64 === 0) await yieldToMain();
|
||||
}
|
||||
|
||||
// Remove now-empty loose object shards.
|
||||
for (const looseDir of touchedDirs) {
|
||||
try {
|
||||
if ((await fs.readdir(looseDir)).length === 0) await fs.rmdir(looseDir);
|
||||
} catch {
|
||||
// Best-effort.
|
||||
}
|
||||
}
|
||||
|
||||
const bytesAfter = await dirSize(fs, objectsDir);
|
||||
return { bytesBefore, bytesAfter, incomplete: false };
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// UI
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function formatBytes(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
const units = ['KB', 'MB', 'GB'];
|
||||
let value = bytes;
|
||||
let unit = 'B';
|
||||
for (const next of units) {
|
||||
if (value < 1024) break;
|
||||
value /= 1024;
|
||||
unit = next;
|
||||
}
|
||||
return `${value.toFixed(1)} ${unit}`;
|
||||
}
|
||||
|
||||
async function run(fs: JSRuntimeFS, dir: string, projectId: string) {
|
||||
if (running.has(projectId)) return;
|
||||
running.add(projectId);
|
||||
|
||||
const progress = toast({
|
||||
description: (
|
||||
<span className="flex items-center gap-2">
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
Optimizing repository…
|
||||
</span>
|
||||
),
|
||||
duration: Infinity,
|
||||
});
|
||||
|
||||
try {
|
||||
const result = await optimizeRepository(fs, dir);
|
||||
const saved = result.bytesBefore - result.bytesAfter;
|
||||
|
||||
progress.update({
|
||||
id: progress.id,
|
||||
title: 'Repository optimized',
|
||||
description: result.incomplete
|
||||
? 'Some objects could not be read, so the repository was left untouched for safety.'
|
||||
: saved > 0
|
||||
? `${formatBytes(result.bytesBefore)} → ${formatBytes(result.bytesAfter)} (saved ${formatBytes(saved)})`
|
||||
: `No size reduction (${formatBytes(result.bytesAfter)})`,
|
||||
duration: 10000,
|
||||
});
|
||||
} catch (error) {
|
||||
progress.update({
|
||||
id: progress.id,
|
||||
title: 'Repository optimization failed',
|
||||
description: error instanceof Error ? error.message : String(error),
|
||||
variant: 'destructive',
|
||||
duration: 10000,
|
||||
});
|
||||
} finally {
|
||||
running.delete(projectId);
|
||||
}
|
||||
}
|
||||
|
||||
interface OptimizeRepositoryMenuItemProps {
|
||||
projectId: string;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export function OptimizeRepositoryMenuItem({ projectId, disabled }: OptimizeRepositoryMenuItemProps) {
|
||||
const { fs } = useFS();
|
||||
const { projectsPath } = useFSPaths();
|
||||
|
||||
return (
|
||||
<DropdownMenuItem
|
||||
onClick={() => run(fs, `${projectsPath}/${projectId}`, projectId)}
|
||||
disabled={disabled}
|
||||
className="gap-2"
|
||||
>
|
||||
<Zap className="h-4 w-4" />
|
||||
Optimize Repository
|
||||
</DropdownMenuItem>
|
||||
);
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { OptimizeRepositoryMenuItem } from '@/components/OptimizeRepositoryMenuItem';
|
||||
|
||||
interface ProjectTitleMenuProps {
|
||||
projectId: string;
|
||||
@@ -119,6 +120,8 @@ export function ProjectTitleMenu({
|
||||
Rollback
|
||||
</DropdownMenuItem>
|
||||
|
||||
<OptimizeRepositoryMenuItem projectId={projectId} disabled={isAnyLoading} />
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={onNewChat}
|
||||
disabled={isAnyLoading}
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
// NOTE: This file is stable and usually should not be modified.
|
||||
// It is important that all functionality in this file is preserved, and should only be modified if explicitly requested.
|
||||
|
||||
import React, { useRef, useState, useEffect } from 'react';
|
||||
import { Shield, Upload, AlertTriangle, UserPlus, KeyRound, Sparkles, Cloud } from 'lucide-react';
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Shield, AlertTriangle, UserPlus, Sparkles } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogDescription } from "@/components/ui/dialog";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||
import { cn } from '@/lib/utils';
|
||||
import LoginPanel from '@/components/auth/LoginPanel';
|
||||
|
||||
interface LoginDialogProps {
|
||||
isOpen: boolean;
|
||||
@@ -18,47 +17,21 @@ interface LoginDialogProps {
|
||||
onSignup?: () => void;
|
||||
}
|
||||
|
||||
const validateNsec = (nsec: string) => {
|
||||
return /^nsec1[a-zA-Z0-9]{58}$/.test(nsec);
|
||||
};
|
||||
|
||||
const validateBunkerUri = (uri: string) => {
|
||||
return uri.startsWith('bunker://');
|
||||
};
|
||||
|
||||
const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onSignup }) => {
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isFileLoading, setIsFileLoading] = useState(false);
|
||||
const [nsec, setNsec] = useState('');
|
||||
const [bunkerUri, setBunkerUri] = useState('');
|
||||
const [errors, setErrors] = useState<{
|
||||
nsec?: string;
|
||||
bunker?: string;
|
||||
file?: string;
|
||||
extension?: string;
|
||||
}>({});
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [isExtensionLoading, setIsExtensionLoading] = useState(false);
|
||||
const [extensionError, setExtensionError] = useState<string | null>(null);
|
||||
const login = useLoginActions();
|
||||
|
||||
// Reset all state when dialog opens/closes
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
// Reset state when dialog opens
|
||||
setIsLoading(false);
|
||||
setIsFileLoading(false);
|
||||
setNsec('');
|
||||
setBunkerUri('');
|
||||
setErrors({});
|
||||
// Reset file input
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = '';
|
||||
}
|
||||
setIsExtensionLoading(false);
|
||||
setExtensionError(null);
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
const handleExtensionLogin = async () => {
|
||||
setIsLoading(true);
|
||||
setErrors(prev => ({ ...prev, extension: undefined }));
|
||||
setIsExtensionLoading(true);
|
||||
setExtensionError(null);
|
||||
|
||||
try {
|
||||
if (!('nostr' in window)) {
|
||||
@@ -69,107 +42,15 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
||||
onClose();
|
||||
} catch (e: unknown) {
|
||||
const error = e as Error;
|
||||
console.error('Bunker login failed:', error);
|
||||
console.error('Nsec login failed:', error);
|
||||
console.error('Extension login failed:', error);
|
||||
setErrors(prev => ({
|
||||
...prev,
|
||||
extension: error instanceof Error ? error.message : 'Extension login failed'
|
||||
}));
|
||||
setExtensionError(
|
||||
error instanceof Error ? error.message : 'Extension login failed',
|
||||
);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
setIsExtensionLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const executeLogin = (key: string) => {
|
||||
setIsLoading(true);
|
||||
setErrors({});
|
||||
|
||||
// Use a timeout to allow the UI to update before the synchronous login call
|
||||
setTimeout(() => {
|
||||
try {
|
||||
login.nsec(key);
|
||||
onLogin();
|
||||
onClose();
|
||||
} catch {
|
||||
setErrors({ nsec: "Failed to login with this key. Please check that it's correct." });
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, 50);
|
||||
};
|
||||
|
||||
const handleKeyLogin = () => {
|
||||
if (!nsec.trim()) {
|
||||
setErrors(prev => ({ ...prev, nsec: 'Please enter your secret key' }));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!validateNsec(nsec)) {
|
||||
setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' }));
|
||||
return;
|
||||
}
|
||||
executeLogin(nsec);
|
||||
};
|
||||
|
||||
const handleBunkerLogin = async () => {
|
||||
if (!bunkerUri.trim()) {
|
||||
setErrors(prev => ({ ...prev, bunker: 'Please enter a bunker URI' }));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!validateBunkerUri(bunkerUri)) {
|
||||
setErrors(prev => ({ ...prev, bunker: 'Invalid bunker URI format. Must start with bunker://' }));
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setErrors(prev => ({ ...prev, bunker: undefined }));
|
||||
|
||||
try {
|
||||
await login.bunker(bunkerUri);
|
||||
onLogin();
|
||||
onClose();
|
||||
// Clear the URI from memory
|
||||
setBunkerUri('');
|
||||
} catch {
|
||||
setErrors(prev => ({
|
||||
...prev,
|
||||
bunker: 'Failed to connect to bunker. Please check the URI.'
|
||||
}));
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
setIsFileLoading(true);
|
||||
setErrors({});
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
setIsFileLoading(false);
|
||||
const content = event.target?.result as string;
|
||||
if (content) {
|
||||
const trimmedContent = content.trim();
|
||||
if (validateNsec(trimmedContent)) {
|
||||
executeLogin(trimmedContent);
|
||||
} else {
|
||||
setErrors({ file: 'File does not contain a valid secret key.' });
|
||||
}
|
||||
} else {
|
||||
setErrors({ file: 'Could not read file content.' });
|
||||
}
|
||||
};
|
||||
reader.onerror = () => {
|
||||
setIsFileLoading(false);
|
||||
setErrors({ file: 'Failed to read file.' });
|
||||
};
|
||||
reader.readAsText(file);
|
||||
};
|
||||
|
||||
const handleSignupClick = () => {
|
||||
onClose();
|
||||
if (onSignup) {
|
||||
@@ -177,7 +58,12 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
||||
}
|
||||
};
|
||||
|
||||
const defaultTab = 'nostr' in window ? 'extension' : 'key';
|
||||
const handleLoggedIn = () => {
|
||||
onLogin();
|
||||
onClose();
|
||||
};
|
||||
|
||||
const hasExtension = typeof window !== 'undefined' && 'nostr' in window;
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
@@ -225,148 +111,29 @@ const LoginDialog: React.FC<LoginDialogProps> = ({ isOpen, onClose, onLogin, onS
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Login Methods */}
|
||||
<Tabs defaultValue={defaultTab} className="w-full">
|
||||
<TabsList className="grid w-full grid-cols-3 bg-muted/80 rounded-lg mb-4">
|
||||
<TabsTrigger value="extension" className="flex items-center gap-2">
|
||||
<Shield className="w-4 h-4" />
|
||||
<span>Extension</span>
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="key" className="flex items-center gap-2">
|
||||
<KeyRound className="w-4 h-4" />
|
||||
<span>Key</span>
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="bunker" className="flex items-center gap-2">
|
||||
<Cloud className="w-4 h-4" />
|
||||
<span>Bunker</span>
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value='extension' className='space-y-3 bg-muted'>
|
||||
{errors.extension && (
|
||||
{/* Unified login panel — QR + nsec/bunker input + file upload */}
|
||||
<LoginPanel onLoggedIn={handleLoggedIn} />
|
||||
|
||||
{/* Extension login (only shown when a NIP-07 extension is present) */}
|
||||
{hasExtension && (
|
||||
<div className='rounded-lg bg-muted p-3 space-y-2'>
|
||||
{extensionError && (
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription>{errors.extension}</AlertDescription>
|
||||
<AlertDescription>{extensionError}</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
<div className='text-center p-4 rounded-lg bg-gray-50 dark:bg-gray-800'>
|
||||
<Shield className='w-12 h-12 mx-auto mb-3 text-primary' />
|
||||
<p className='text-sm text-gray-600 dark:text-gray-300 mb-4'>
|
||||
Login with one click using the browser extension
|
||||
</p>
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
className='w-full rounded-full py-4'
|
||||
onClick={handleExtensionLogin}
|
||||
disabled={isLoading}
|
||||
>
|
||||
{isLoading ? 'Logging in...' : 'Login with Extension'}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value='key' className='space-y-4'>
|
||||
<div className='space-y-4'>
|
||||
<div className='space-y-2'>
|
||||
<label htmlFor='nsec' className='text-sm font-medium'>
|
||||
Secret Key (nsec)
|
||||
</label>
|
||||
<Input
|
||||
id='nsec'
|
||||
type="password"
|
||||
value={nsec}
|
||||
onChange={(e) => {
|
||||
setNsec(e.target.value);
|
||||
if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined }));
|
||||
}}
|
||||
className={`rounded-lg ${
|
||||
errors.nsec ? 'border-red-500 focus-visible:ring-red-500' : ''
|
||||
}`}
|
||||
placeholder='nsec1...'
|
||||
autoComplete="off"
|
||||
/>
|
||||
{errors.nsec && (
|
||||
<p className="text-sm text-red-500">{errors.nsec}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Button
|
||||
className='w-full rounded-full py-3'
|
||||
onClick={handleKeyLogin}
|
||||
disabled={isLoading || !nsec.trim()}
|
||||
>
|
||||
{isLoading ? 'Verifying...' : 'Log In'}
|
||||
</Button>
|
||||
|
||||
<div className='relative'>
|
||||
<div className='absolute inset-0 flex items-center'>
|
||||
<div className='w-full border-t border-muted'></div>
|
||||
</div>
|
||||
<div className='relative flex justify-center text-xs'>
|
||||
<span className='px-2 bg-background text-muted-foreground'>
|
||||
or
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className='text-center'>
|
||||
<input
|
||||
type='file'
|
||||
accept='.txt'
|
||||
className='hidden'
|
||||
ref={fileInputRef}
|
||||
onChange={handleFileUpload}
|
||||
/>
|
||||
<Button
|
||||
variant='outline'
|
||||
className='w-full'
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={isLoading || isFileLoading}
|
||||
>
|
||||
<Upload className='w-4 h-4 mr-2' />
|
||||
{isFileLoading ? 'Reading File...' : 'Upload Your Key File'}
|
||||
</Button>
|
||||
{errors.file && (
|
||||
<p className="text-sm text-red-500 mt-2">{errors.file}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value='bunker' className='space-y-3 bg-muted'>
|
||||
<div className='space-y-2'>
|
||||
<label htmlFor='bunkerUri' className='text-sm font-medium text-gray-700 dark:text-gray-400'>
|
||||
Bunker URI
|
||||
</label>
|
||||
<Input
|
||||
id='bunkerUri'
|
||||
value={bunkerUri}
|
||||
onChange={(e) => {
|
||||
setBunkerUri(e.target.value);
|
||||
if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined }));
|
||||
}}
|
||||
className={`rounded-lg border-gray-300 dark:border-gray-700 focus-visible:ring-primary ${
|
||||
errors.bunker ? 'border-red-500' : ''
|
||||
}`}
|
||||
placeholder='bunker://'
|
||||
autoComplete="off"
|
||||
/>
|
||||
{errors.bunker && (
|
||||
<p className="text-sm text-red-500">{errors.bunker}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
className='w-full rounded-full py-4'
|
||||
onClick={handleBunkerLogin}
|
||||
disabled={isLoading || !bunkerUri.trim()}
|
||||
>
|
||||
{isLoading ? 'Connecting...' : 'Login with Bunker'}
|
||||
</Button>
|
||||
</div>
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
<Button
|
||||
variant='outline'
|
||||
className='w-full rounded-full'
|
||||
onClick={handleExtensionLogin}
|
||||
disabled={isExtensionLoading}
|
||||
>
|
||||
<Shield className='w-4 h-4 mr-2' />
|
||||
{isExtensionLoading ? 'Logging in…' : 'Sign in with browser extension'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
import React, { useCallback, useEffect, useRef, useState } from 'react';
|
||||
import QRCode from 'qrcode';
|
||||
import { ExternalLink, Loader2, Upload } from 'lucide-react';
|
||||
import {
|
||||
generateNostrConnectParams,
|
||||
generateNostrConnectURI,
|
||||
type NostrConnectParams,
|
||||
} from '@nostrify/react/login';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
|
||||
interface LoginPanelProps {
|
||||
/** Called after a successful login (nostrconnect QR, nsec, bunker URI, or key file). */
|
||||
onLoggedIn: () => void;
|
||||
}
|
||||
|
||||
const NSEC_REGEX = /^nsec1[a-zA-Z0-9]{58}$/;
|
||||
|
||||
type InputKind = 'nsec' | 'bunker' | 'unknown';
|
||||
|
||||
const detectInputKind = (value: string): InputKind => {
|
||||
const trimmed = value.trim();
|
||||
if (NSEC_REGEX.test(trimmed)) return 'nsec';
|
||||
if (trimmed.startsWith('bunker://')) return 'bunker';
|
||||
return 'unknown';
|
||||
};
|
||||
|
||||
// UA-based mobile check. Distinct from the viewport-based `useIsMobile` —
|
||||
// here we care whether the platform can deep-link into a signer app, not
|
||||
// whether the window is narrow.
|
||||
const isMobileDevice = (): boolean => {
|
||||
if (typeof navigator === 'undefined') return false;
|
||||
return /Android|iPhone|iPad|iPod/i.test(navigator.userAgent);
|
||||
};
|
||||
|
||||
/**
|
||||
* Unified login panel for all string-based methods:
|
||||
* - `nostrconnect://` flow gated behind a button. Desktop reveals a QR code;
|
||||
* mobile redirects to a signer-app deep-link.
|
||||
* - A single paste input that accepts either an `nsec1…` secret key OR a
|
||||
* `bunker://` URI — the type is detected from the string on submit.
|
||||
* - File upload for plain-text nsec / bunker URI files.
|
||||
*
|
||||
* The nostrconnect session is only opened when the user clicks the button
|
||||
* (so the dialog doesn't open a relay subscription for users who just want
|
||||
* to paste a key). Panel unmount aborts any in-flight listener.
|
||||
*/
|
||||
export const LoginPanel: React.FC<LoginPanelProps> = ({ onLoggedIn }) => {
|
||||
const login = useLoginActions();
|
||||
const { config } = useAppContext();
|
||||
|
||||
// Session is gated: stays idle until the user clicks the remote-signer
|
||||
// button. Bumping `sessionToken` while started restarts the session
|
||||
// (used by "Try again").
|
||||
const [sessionStarted, setSessionStarted] = useState(false);
|
||||
const [sessionToken, setSessionToken] = useState(0);
|
||||
const [nostrConnectUri, setNostrConnectUri] = useState('');
|
||||
const [qrDataUrl, setQrDataUrl] = useState('');
|
||||
const [connectError, setConnectError] = useState<string | null>(null);
|
||||
const [hasOpenedSigner, setHasOpenedSigner] = useState(false);
|
||||
// Mobile-only: tracks "user pressed Open signer app but the URI isn't
|
||||
// generated yet — navigate as soon as it is."
|
||||
const [pendingNavigate, setPendingNavigate] = useState(false);
|
||||
|
||||
// Unified text input — accepts nsec or bunker URI, type detected on submit.
|
||||
const [input, setInput] = useState('');
|
||||
const [inputError, setInputError] = useState<string | null>(null);
|
||||
const [isInputLoggingIn, setIsInputLoggingIn] = useState(false);
|
||||
const [isFileLoading, setIsFileLoading] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
|
||||
const abortControllerRef = useRef<AbortController | null>(null);
|
||||
// Refs so the listener effect can read the latest values without
|
||||
// re-running on every parent re-render. `config` is rebuilt every render
|
||||
// by AppProvider, so we must NOT depend on it in the effect's dep array —
|
||||
// otherwise the in-flight subscription is torn down on each parent render.
|
||||
const loginRef = useRef(login);
|
||||
const onLoggedInRef = useRef(onLoggedIn);
|
||||
const configRef = useRef(config);
|
||||
|
||||
useEffect(() => {
|
||||
loginRef.current = login;
|
||||
onLoggedInRef.current = onLoggedIn;
|
||||
configRef.current = config;
|
||||
});
|
||||
|
||||
const isMobile = isMobileDevice();
|
||||
|
||||
// Open a nostrconnect session and start listening for the signer. Runs
|
||||
// only after the user clicks the start button (`sessionStarted=true`),
|
||||
// and re-runs when `sessionToken` is bumped by "Try again".
|
||||
useEffect(() => {
|
||||
if (!sessionStarted) return;
|
||||
|
||||
let cancelled = false;
|
||||
const controller = new AbortController();
|
||||
abortControllerRef.current?.abort();
|
||||
abortControllerRef.current = controller;
|
||||
|
||||
const run = async () => {
|
||||
const relayUrls = (configRef.current.relayMetadata?.relays ?? [])
|
||||
.filter((r) => r.write !== false)
|
||||
.map((r) => r.url);
|
||||
|
||||
if (relayUrls.length === 0) {
|
||||
if (!cancelled) {
|
||||
setConnectError(
|
||||
'No relays configured. Add a relay in settings to use this login method.',
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const params: NostrConnectParams = generateNostrConnectParams(relayUrls);
|
||||
const uri = generateNostrConnectURI(params, {
|
||||
name: 'Shakespeare',
|
||||
callback: isMobileDevice()
|
||||
? `${window.location.origin}/remoteloginsuccess`
|
||||
: undefined,
|
||||
});
|
||||
|
||||
// Publish the URI ASAP so a pending mobile navigate can fire while
|
||||
// the QR renders in the background.
|
||||
if (cancelled) return;
|
||||
setNostrConnectUri(uri);
|
||||
setConnectError(null);
|
||||
|
||||
// Desktop renders a QR; mobile redirects, so skip the work there.
|
||||
if (!isMobileDevice()) {
|
||||
try {
|
||||
const dataUrl = await QRCode.toDataURL(uri, {
|
||||
width: 400,
|
||||
margin: 2,
|
||||
color: { dark: '#000000', light: '#FFFFFF' },
|
||||
});
|
||||
if (cancelled) return;
|
||||
setQrDataUrl(dataUrl);
|
||||
} catch (e) {
|
||||
console.error('Failed to render nostrconnect QR:', e);
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await loginRef.current.nostrconnect(params, controller.signal);
|
||||
if (cancelled || controller.signal.aborted) return;
|
||||
onLoggedInRef.current();
|
||||
} catch (error) {
|
||||
if (cancelled || controller.signal.aborted) return;
|
||||
if (error instanceof Error && error.name === 'AbortError') return;
|
||||
console.error('nostrconnect failed:', error);
|
||||
setConnectError(
|
||||
error instanceof Error ? error.message : 'Failed to connect to signer.',
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
void run();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
controller.abort();
|
||||
};
|
||||
// Intentional: deps limited to `sessionStarted` + `sessionToken` so
|
||||
// parent re-renders don't tear down the in-flight subscription. Config
|
||||
// + login are read via refs that are updated each render.
|
||||
}, [sessionStarted, sessionToken]);
|
||||
|
||||
// Mobile: once the URI is ready and the user already tapped "Open signer
|
||||
// app", navigate to the deep-link. Runs once per click; the flag is
|
||||
// consumed here.
|
||||
useEffect(() => {
|
||||
if (!pendingNavigate || !nostrConnectUri || connectError) return;
|
||||
setPendingNavigate(false);
|
||||
setHasOpenedSigner(true);
|
||||
window.location.href = nostrConnectUri;
|
||||
}, [pendingNavigate, nostrConnectUri, connectError]);
|
||||
|
||||
const handleStartDesktopSession = () => {
|
||||
setSessionStarted(true);
|
||||
};
|
||||
|
||||
const handleOpenSignerApp = () => {
|
||||
// Mobile: arm the navigate-when-ready effect and start the session.
|
||||
// If the session is already running (e.g. retry after error), this
|
||||
// just navigates with the existing URI.
|
||||
setPendingNavigate(true);
|
||||
setSessionStarted(true);
|
||||
};
|
||||
|
||||
const handleConnectRetry = useCallback(() => {
|
||||
setNostrConnectUri('');
|
||||
setQrDataUrl('');
|
||||
setConnectError(null);
|
||||
setHasOpenedSigner(false);
|
||||
setPendingNavigate(false);
|
||||
setSessionToken((t) => t + 1);
|
||||
}, []);
|
||||
|
||||
const submitInput = async (rawValue: string) => {
|
||||
const trimmed = rawValue.trim();
|
||||
if (!trimmed) {
|
||||
setInputError('Enter a secret key or bunker URI');
|
||||
return;
|
||||
}
|
||||
|
||||
const kind = detectInputKind(trimmed);
|
||||
if (kind === 'unknown') {
|
||||
setInputError('Unrecognized format. Expected nsec1… or bunker://…');
|
||||
return;
|
||||
}
|
||||
|
||||
setIsInputLoggingIn(true);
|
||||
setInputError(null);
|
||||
|
||||
try {
|
||||
if (kind === 'nsec') {
|
||||
// login.nsec is synchronous but throws on bad keys.
|
||||
login.nsec(trimmed);
|
||||
} else {
|
||||
await login.bunker(trimmed);
|
||||
}
|
||||
onLoggedIn();
|
||||
} catch {
|
||||
setInputError(
|
||||
kind === 'nsec'
|
||||
? "Failed to log in with this key. Please check that it's correct."
|
||||
: 'Failed to connect to bunker. Please check the URI.',
|
||||
);
|
||||
} finally {
|
||||
setIsInputLoggingIn(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleSubmit = () => {
|
||||
void submitInput(input);
|
||||
};
|
||||
|
||||
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
setIsFileLoading(true);
|
||||
setInputError(null);
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
setIsFileLoading(false);
|
||||
const content = event.target?.result as string;
|
||||
if (!content) {
|
||||
setInputError('Could not read file content.');
|
||||
return;
|
||||
}
|
||||
const trimmed = content.trim();
|
||||
if (detectInputKind(trimmed) === 'unknown') {
|
||||
setInputError('File does not contain a valid nsec or bunker URI.');
|
||||
return;
|
||||
}
|
||||
setInput(trimmed);
|
||||
void submitInput(trimmed);
|
||||
};
|
||||
reader.onerror = () => {
|
||||
setIsFileLoading(false);
|
||||
setInputError('Failed to read file.');
|
||||
};
|
||||
reader.readAsText(file);
|
||||
// Reset so the same file can be selected again after a failure.
|
||||
if (fileInputRef.current) fileInputRef.current.value = '';
|
||||
};
|
||||
|
||||
const renderRemoteSignerSection = () => {
|
||||
// Idle: just a button. Clicking it generates the session and either
|
||||
// reveals the QR (desktop) or deep-links to a signer app (mobile).
|
||||
if (!sessionStarted) {
|
||||
return (
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={isMobile ? handleOpenSignerApp : handleStartDesktopSession}
|
||||
className="w-full h-12"
|
||||
>
|
||||
<ExternalLink className="w-5 h-5 mr-2" />
|
||||
{isMobile ? 'Open signer app' : 'Login with remote signer'}
|
||||
</Button>
|
||||
);
|
||||
}
|
||||
|
||||
if (connectError) {
|
||||
return (
|
||||
<div className="flex flex-col items-center space-y-3 py-4 w-full">
|
||||
<Alert variant="destructive">
|
||||
<AlertDescription>{connectError}</AlertDescription>
|
||||
</Alert>
|
||||
<Button variant="outline" onClick={handleConnectRetry}>
|
||||
Try again
|
||||
</Button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isMobile && hasOpenedSigner) {
|
||||
return (
|
||||
<div className="flex flex-col items-center space-y-4 py-6 w-full">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-primary" />
|
||||
<p className="text-sm text-muted-foreground text-center">
|
||||
Waiting for signer…
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleConnectRetry}
|
||||
className="text-sm text-primary hover:underline underline-offset-4 font-medium"
|
||||
>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!isMobile && qrDataUrl) {
|
||||
return (
|
||||
<div className="flex flex-col items-center space-y-4 w-full">
|
||||
<div className="p-3 bg-white rounded-xl">
|
||||
<img
|
||||
src={qrDataUrl}
|
||||
alt="nostrconnect QR code"
|
||||
width={200}
|
||||
height={200}
|
||||
className="block"
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground text-center max-w-[260px]">
|
||||
Scan this QR code with your Nostr signer app to log in.
|
||||
</p>
|
||||
<button
|
||||
type="button"
|
||||
onClick={handleConnectRetry}
|
||||
className="text-xs text-muted-foreground hover:text-foreground underline underline-offset-4"
|
||||
>
|
||||
Generate a new code
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Mobile pre-navigate or desktop pre-QR — short transient state.
|
||||
return (
|
||||
<div className="flex items-center justify-center h-[120px]">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-muted-foreground" />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{renderRemoteSignerSection()}
|
||||
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<div className="w-full border-t"></div>
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase">
|
||||
<span className="bg-background px-2 text-muted-foreground">
|
||||
or paste a key or URI
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Input
|
||||
type="password"
|
||||
value={input}
|
||||
onChange={(e) => {
|
||||
setInput(e.target.value);
|
||||
if (inputError) setInputError(null);
|
||||
}}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && input.trim() && !isInputLoggingIn) {
|
||||
e.preventDefault();
|
||||
handleSubmit();
|
||||
}
|
||||
}}
|
||||
placeholder="nsec1… or bunker://…"
|
||||
className={inputError ? 'border-red-500' : ''}
|
||||
autoComplete="off"
|
||||
/>
|
||||
{inputError && (
|
||||
<p className="text-sm text-red-500">{inputError}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex space-x-2">
|
||||
<Button
|
||||
onClick={handleSubmit}
|
||||
disabled={isInputLoggingIn || isFileLoading || !input.trim()}
|
||||
className="flex-1"
|
||||
>
|
||||
{isInputLoggingIn ? 'Adding…' : 'Add account'}
|
||||
</Button>
|
||||
|
||||
<input
|
||||
type="file"
|
||||
accept=".txt"
|
||||
className="hidden"
|
||||
ref={fileInputRef}
|
||||
onChange={handleFileUpload}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={isInputLoggingIn || isFileLoading}
|
||||
className="px-3"
|
||||
title="Upload a file containing an nsec or bunker URI"
|
||||
>
|
||||
{isFileLoading ? (
|
||||
<Loader2 className="w-4 h-4 animate-spin" />
|
||||
) : (
|
||||
<Upload className="w-4 h-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default LoginPanel;
|
||||
@@ -1,13 +1,7 @@
|
||||
import React, { useState, useEffect, useRef } from 'react';
|
||||
import { Cloud, Upload } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
|
||||
// Alert components removed as they're not used in the simplified design
|
||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
// Only using key-add step now
|
||||
import LoginPanel from '@/components/auth/LoginPanel';
|
||||
|
||||
interface SimpleLoginDialogProps {
|
||||
isOpen: boolean;
|
||||
@@ -16,55 +10,27 @@ interface SimpleLoginDialogProps {
|
||||
onSignup?: () => void;
|
||||
}
|
||||
|
||||
const validateNsec = (nsec: string) => {
|
||||
return /^nsec1[a-zA-Z0-9]{58}$/.test(nsec);
|
||||
};
|
||||
|
||||
const validateBunkerUri = (uri: string) => {
|
||||
return uri.startsWith('bunker://');
|
||||
};
|
||||
|
||||
const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
||||
isOpen,
|
||||
onClose,
|
||||
onLogin,
|
||||
onSignup
|
||||
}) => {
|
||||
// Removed step state - we only have one step now
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const [isFileLoading, setIsFileLoading] = useState(false);
|
||||
const [nsec, setNsec] = useState('');
|
||||
const [bunkerUri, setBunkerUri] = useState('');
|
||||
const [activeTab, setActiveTab] = useState<'nsec' | 'bunker'>('nsec');
|
||||
const [errors, setErrors] = useState<{
|
||||
nsec?: string;
|
||||
bunker?: string;
|
||||
extension?: string;
|
||||
file?: string;
|
||||
}>({});
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const [isExtensionLoading, setIsExtensionLoading] = useState(false);
|
||||
const [extensionError, setExtensionError] = useState<string | null>(null);
|
||||
|
||||
const login = useLoginActions();
|
||||
|
||||
// Reset state when dialog opens/closes
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
setIsLoading(false);
|
||||
setIsFileLoading(false);
|
||||
setNsec('');
|
||||
setBunkerUri('');
|
||||
setActiveTab('nsec');
|
||||
setErrors({});
|
||||
// Reset file input
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = '';
|
||||
}
|
||||
setIsExtensionLoading(false);
|
||||
setExtensionError(null);
|
||||
}
|
||||
}, [isOpen]);
|
||||
|
||||
const handleExtensionLogin = async () => {
|
||||
setIsLoading(true);
|
||||
setErrors(prev => ({ ...prev, extension: undefined }));
|
||||
setIsExtensionLoading(true);
|
||||
setExtensionError(null);
|
||||
|
||||
try {
|
||||
if (!('nostr' in window)) {
|
||||
@@ -75,103 +41,12 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
||||
onClose();
|
||||
} catch (e: unknown) {
|
||||
const error = e as Error;
|
||||
setErrors(prev => ({
|
||||
...prev,
|
||||
extension: error instanceof Error ? error.message : 'Extension login failed'
|
||||
}));
|
||||
setExtensionError(error instanceof Error ? error.message : 'Extension login failed');
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
setIsExtensionLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleKeyLogin = () => {
|
||||
if (!nsec.trim()) {
|
||||
setErrors(prev => ({ ...prev, nsec: 'Please enter your secret key' }));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!validateNsec(nsec)) {
|
||||
setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' }));
|
||||
return;
|
||||
}
|
||||
executeLogin(nsec);
|
||||
};
|
||||
|
||||
const handleBunkerLogin = async () => {
|
||||
if (!bunkerUri.trim()) {
|
||||
setErrors(prev => ({ ...prev, bunker: 'Please enter a bunker URI' }));
|
||||
return;
|
||||
}
|
||||
|
||||
if (!validateBunkerUri(bunkerUri)) {
|
||||
setErrors(prev => ({ ...prev, bunker: 'Invalid bunker URI format. Must start with bunker://' }));
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
setErrors(prev => ({ ...prev, bunker: undefined }));
|
||||
|
||||
try {
|
||||
await login.bunker(bunkerUri);
|
||||
onLogin();
|
||||
onClose();
|
||||
setBunkerUri('');
|
||||
} catch {
|
||||
setErrors(prev => ({
|
||||
...prev,
|
||||
bunker: 'Failed to connect to bunker. Please check the URI.'
|
||||
}));
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
const executeLogin = (key: string) => {
|
||||
setIsLoading(true);
|
||||
setErrors({});
|
||||
|
||||
// Use a timeout to allow the UI to update before the synchronous login call
|
||||
setTimeout(() => {
|
||||
try {
|
||||
login.nsec(key);
|
||||
onLogin();
|
||||
onClose();
|
||||
} catch {
|
||||
setErrors({ nsec: "Failed to login with this key. Please check that it's correct." });
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, 50);
|
||||
};
|
||||
|
||||
const handleFileUpload = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
|
||||
setIsFileLoading(true);
|
||||
setErrors({});
|
||||
|
||||
const reader = new FileReader();
|
||||
reader.onload = (event) => {
|
||||
setIsFileLoading(false);
|
||||
const content = event.target?.result as string;
|
||||
if (content) {
|
||||
const trimmedContent = content.trim();
|
||||
if (validateNsec(trimmedContent)) {
|
||||
executeLogin(trimmedContent);
|
||||
} else {
|
||||
setErrors({ file: 'File does not contain a valid secret key.' });
|
||||
}
|
||||
} else {
|
||||
setErrors({ file: 'Could not read file content.' });
|
||||
}
|
||||
};
|
||||
reader.onerror = () => {
|
||||
setIsFileLoading(false);
|
||||
setErrors({ file: 'Failed to read file.' });
|
||||
};
|
||||
reader.readAsText(file);
|
||||
};
|
||||
|
||||
const handleSignupClick = () => {
|
||||
onClose();
|
||||
if (onSignup) {
|
||||
@@ -179,6 +54,11 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
||||
}
|
||||
};
|
||||
|
||||
const handleLoggedIn = () => {
|
||||
onLogin();
|
||||
onClose();
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={isOpen} onOpenChange={onClose}>
|
||||
<DialogContent className="max-w-sm">
|
||||
@@ -186,159 +66,41 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
||||
<DialogTitle className="text-center">Log in</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex flex-col items-center space-y-6 py-6">
|
||||
<div className="flex flex-col items-center space-y-6 py-4">
|
||||
<div className="text-center">
|
||||
<h3 className="font-semibold mb-2">Welcome back to Shakespeare</h3>
|
||||
<p className="text-sm text-muted-foreground">Sign in to your existing account</p>
|
||||
</div>
|
||||
|
||||
<div className="w-40 h-40 flex items-center justify-center">
|
||||
<div className="w-40 h-40 bg-primary/10 rounded-full flex items-center justify-center">
|
||||
<span className="text-8xl">🔑</span>
|
||||
</div>
|
||||
<div className="w-full">
|
||||
<LoginPanel onLoggedIn={handleLoggedIn} />
|
||||
</div>
|
||||
|
||||
<div className="w-full space-y-4">
|
||||
{/* Tab selector */}
|
||||
<div className="flex space-x-1 bg-muted rounded-lg p-1">
|
||||
<button
|
||||
onClick={() => setActiveTab('nsec')}
|
||||
className={cn(
|
||||
"flex-1 px-3 py-2 text-sm font-medium rounded-md transition-colors",
|
||||
activeTab === 'nsec'
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
)}
|
||||
>
|
||||
Secret Key
|
||||
</button>
|
||||
<button
|
||||
onClick={() => setActiveTab('bunker')}
|
||||
className={cn(
|
||||
"flex-1 px-3 py-2 text-sm font-medium rounded-md transition-colors",
|
||||
activeTab === 'bunker'
|
||||
? "bg-background text-foreground shadow-sm"
|
||||
: "text-muted-foreground hover:text-foreground"
|
||||
)}
|
||||
>
|
||||
Bunker
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{activeTab === 'nsec' && (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Input
|
||||
type="password"
|
||||
value={nsec}
|
||||
onChange={(e) => {
|
||||
setNsec(e.target.value);
|
||||
if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined }));
|
||||
}}
|
||||
placeholder="nsec1..."
|
||||
className={errors.nsec ? 'border-red-500' : ''}
|
||||
/>
|
||||
{errors.nsec && (
|
||||
<p className="text-sm text-red-500">{errors.nsec}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex space-x-2">
|
||||
<Button
|
||||
size="lg"
|
||||
onClick={handleKeyLogin}
|
||||
disabled={isLoading || !nsec.trim()}
|
||||
className="flex-1"
|
||||
>
|
||||
{isLoading ? 'Verifying...' : 'Add Key'}
|
||||
</Button>
|
||||
|
||||
<input
|
||||
type="file"
|
||||
accept=".txt"
|
||||
className="hidden"
|
||||
ref={fileInputRef}
|
||||
onChange={handleFileUpload}
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="lg"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={isLoading || isFileLoading}
|
||||
className="px-3"
|
||||
>
|
||||
<Upload className="w-4 h-4" />
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{errors.file && (
|
||||
<p className="text-sm text-red-500 text-center">{errors.file}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{activeTab === 'bunker' && (
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Input
|
||||
value={bunkerUri}
|
||||
onChange={(e) => {
|
||||
setBunkerUri(e.target.value);
|
||||
if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined }));
|
||||
}}
|
||||
placeholder="bunker://"
|
||||
className={errors.bunker ? 'border-red-500' : ''}
|
||||
/>
|
||||
{errors.bunker && (
|
||||
<p className="text-sm text-red-500">{errors.bunker}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<Button
|
||||
size="lg"
|
||||
onClick={handleBunkerLogin}
|
||||
disabled={isLoading || !bunkerUri.trim()}
|
||||
className="w-full"
|
||||
{window.nostr && (
|
||||
<div className="w-full rounded-lg bg-muted p-3">
|
||||
<p className="text-xs text-center">
|
||||
<button
|
||||
onClick={handleExtensionLogin}
|
||||
className="text-blue-500 hover:underline disabled:opacity-50"
|
||||
disabled={isExtensionLoading}
|
||||
>
|
||||
<Cloud className="w-4 h-4 mr-2" />
|
||||
{isLoading ? 'Connecting...' : 'Connect'}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="relative">
|
||||
<div className="absolute inset-0 flex items-center">
|
||||
<div className="w-full border-t"></div>
|
||||
</div>
|
||||
<div className="relative flex justify-center text-xs uppercase">
|
||||
<span className="bg-background px-2 text-muted-foreground">or</span>
|
||||
</div>
|
||||
{isExtensionLoading ? 'Connecting…' : 'Sign in with browser extension'}
|
||||
</button>
|
||||
</p>
|
||||
{extensionError && (
|
||||
<p className="text-xs text-red-500 text-center mt-2">{extensionError}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Extension indicator - only show if extension is detected */}
|
||||
{window.nostr && (
|
||||
<div className="rounded-lg bg-muted p-3">
|
||||
<p className="text-xs text-center">
|
||||
<button
|
||||
onClick={handleExtensionLogin}
|
||||
className="text-blue-500 hover:underline"
|
||||
disabled={isLoading}
|
||||
>
|
||||
Sign in with browser extension
|
||||
</button>
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-center space-x-2 text-xs">
|
||||
<span className="text-muted-foreground">New to Shakespeare?</span>
|
||||
<button
|
||||
onClick={handleSignupClick}
|
||||
className="text-blue-500 hover:underline"
|
||||
>
|
||||
Create Account
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex justify-center space-x-2 text-xs">
|
||||
<span className="text-muted-foreground">New to Shakespeare?</span>
|
||||
<button
|
||||
onClick={handleSignupClick}
|
||||
className="text-blue-500 hover:underline"
|
||||
>
|
||||
Create Account
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</DialogContent>
|
||||
@@ -346,4 +108,4 @@ const SimpleLoginDialog: React.FC<SimpleLoginDialogProps> = ({
|
||||
);
|
||||
};
|
||||
|
||||
export default SimpleLoginDialog;
|
||||
export default SimpleLoginDialog;
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { NLogin, useNostrLogin } from '@nostrify/react/login';
|
||||
import type { NostrConnectParams } from '@nostrify/react/login';
|
||||
|
||||
// NOTE: This file should not be edited except for adding new login methods.
|
||||
|
||||
@@ -18,6 +19,14 @@ export function useLoginActions() {
|
||||
const login = await NLogin.fromBunker(uri, nostr);
|
||||
addLogin(login);
|
||||
},
|
||||
// Login via client-initiated NIP-46 ("nostrconnect://" QR code).
|
||||
// Caller generates params with `generateNostrConnectParams`, renders the
|
||||
// URI as a QR/deep-link, and awaits this promise — it resolves when the
|
||||
// remote signer connects back over the relay.
|
||||
async nostrconnect(params: NostrConnectParams, signal?: AbortSignal): Promise<void> {
|
||||
const login = await NLogin.fromNostrConnect(params, nostr, { signal });
|
||||
addLogin(login);
|
||||
},
|
||||
// Login with a NIP-07 browser extension
|
||||
async extension(): Promise<void> {
|
||||
const login = await NLogin.fromExtension();
|
||||
|
||||
+11
-1
@@ -2,6 +2,7 @@ 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;
|
||||
@@ -159,12 +160,21 @@ export function useNWCInternal() {
|
||||
// Send payment using the SDK
|
||||
const sendPayment = useCallback(async (
|
||||
connection: NWCConnection,
|
||||
invoice: string
|
||||
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,
|
||||
): 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);
|
||||
|
||||
+54
-8
@@ -11,6 +11,8 @@ 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[],
|
||||
@@ -180,12 +182,19 @@ export function useZaps(
|
||||
return;
|
||||
}
|
||||
|
||||
// Get zap endpoint using the old reliable method
|
||||
const zapEndpoint = await nip57.getZapEndpoint(author.data.event);
|
||||
if (!zapEndpoint) {
|
||||
// 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) {
|
||||
toast({
|
||||
title: 'Zap endpoint not found',
|
||||
description: 'Could not find a zap endpoint for the author.',
|
||||
description: endpointError instanceof Error
|
||||
? endpointError.message
|
||||
: 'Could not find a zap endpoint for the author.',
|
||||
variant: 'destructive',
|
||||
});
|
||||
setIsZapping(false);
|
||||
@@ -194,6 +203,20 @@ 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);
|
||||
@@ -209,9 +232,14 @@ export function useZaps(
|
||||
throw new Error('No signer available');
|
||||
}
|
||||
const signedZapRequest = await user.signer.signEvent(zapRequest);
|
||||
const zapRequestJson = JSON.stringify(signedZapRequest);
|
||||
|
||||
try {
|
||||
const res = await fetch(`${zapEndpoint}?amount=${zapAmount}&nostr=${encodeURI(JSON.stringify(signedZapRequest))}`);
|
||||
const zapUrl = new URL(lnurlParams.callback);
|
||||
zapUrl.searchParams.set('amount', String(zapAmount));
|
||||
zapUrl.searchParams.set('nostr', zapRequestJson);
|
||||
|
||||
const res = await fetch(zapUrl.toString());
|
||||
const responseData = await res.json();
|
||||
|
||||
if (!res.ok) {
|
||||
@@ -223,13 +251,31 @@ 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);
|
||||
await sendPayment(currentNWCConnection, newInvoice, zapAmount);
|
||||
|
||||
// Clear states immediately on success
|
||||
setIsZapping(false);
|
||||
@@ -237,7 +283,7 @@ export function useZaps(
|
||||
|
||||
toast({
|
||||
title: 'Zap successful!',
|
||||
description: `You sent ${amount} sats via NWC to the author.`,
|
||||
description: `You sent ${paidSats} sats via NWC to the author.`,
|
||||
});
|
||||
|
||||
// Invalidate zap queries to refresh counts
|
||||
@@ -269,7 +315,7 @@ export function useZaps(
|
||||
|
||||
toast({
|
||||
title: 'Zap successful!',
|
||||
description: `You sent ${amount} sats to the author.`,
|
||||
description: `You sent ${paidSats} sats to the author.`,
|
||||
});
|
||||
|
||||
// Invalidate zap queries to refresh counts
|
||||
|
||||
@@ -7,6 +7,8 @@ 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[] = [
|
||||
@@ -106,4 +108,12 @@ 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",
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,115 @@
|
||||
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);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,258 @@
|
||||
/**
|
||||
* 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,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
import { describe, it, expect, vi, afterEach } from "vitest";
|
||||
import {
|
||||
isEffectivelyEmptyModule,
|
||||
resolveEmptyModuleFallback,
|
||||
stripAssetUrlWildcard,
|
||||
} from "./esmPlugin";
|
||||
|
||||
describe("stripAssetUrlWildcard", () => {
|
||||
it("strips esm.sh's leading /* wildcard prefix from asset URLs", () => {
|
||||
expect(
|
||||
stripAssetUrlWildcard(
|
||||
"https://esm.sh/*@fontsource/[email protected]/files/x.woff2",
|
||||
),
|
||||
).toBe("https://esm.sh/@fontsource/[email protected]/files/x.woff2");
|
||||
});
|
||||
|
||||
it("preserves the query string (e.g. the lp breadcrumb)", () => {
|
||||
expect(
|
||||
stripAssetUrlWildcard(
|
||||
"https://esm.sh/*@fontsource/foo@1/files/y.woff?lp=node_modules%252F%2540fontsource%252Ffoo",
|
||||
),
|
||||
).toBe(
|
||||
"https://esm.sh/@fontsource/foo@1/files/y.woff?lp=node_modules%252F%2540fontsource%252Ffoo",
|
||||
);
|
||||
});
|
||||
|
||||
it("leaves URLs without a wildcard prefix unchanged", () => {
|
||||
const url = "https://esm.sh/@fontsource/foo@1/files/y.woff2?lp=abc";
|
||||
expect(stripAssetUrlWildcard(url)).toBe(url);
|
||||
});
|
||||
|
||||
it("only strips a leading /* in the path, not a * elsewhere", () => {
|
||||
const url = "https://esm.sh/@scope/pkg@1/a*b/file.woff2";
|
||||
expect(stripAssetUrlWildcard(url)).toBe(url);
|
||||
});
|
||||
|
||||
it("returns the input unchanged when it is not a valid URL", () => {
|
||||
expect(stripAssetUrlWildcard("not a url")).toBe("not a url");
|
||||
});
|
||||
|
||||
it("produces a url() value with no literal /* (the Tailwind tokenizer trap)", () => {
|
||||
const fixed = stripAssetUrlWildcard(
|
||||
"https://esm.sh/*@fontsource/[email protected]/files/x.woff2",
|
||||
);
|
||||
expect(`src: url(${fixed})`).not.toContain("/*");
|
||||
});
|
||||
});
|
||||
|
||||
describe("isEffectivelyEmptyModule", () => {
|
||||
it("treats a file with only source-map comments as empty", () => {
|
||||
const source =
|
||||
"\n//# sourceMappingURL=index.browser.mjs.map\n//# sourceMappingURL=index.browser.mjs.map";
|
||||
expect(isEffectivelyEmptyModule(source)).toBe(true);
|
||||
});
|
||||
|
||||
it("treats a jsDelivr-bannered empty bundle as empty", () => {
|
||||
const source = [
|
||||
"/**",
|
||||
" * Bundled by jsDelivr using Rollup v2.79.2 and Terser v5.48.0.",
|
||||
" * Original file: /npm/@solana/[email protected]/dist/index.browser.mjs",
|
||||
" */",
|
||||
"//# sourceMappingURL=/sm/abc.map",
|
||||
].join("\n");
|
||||
expect(isEffectivelyEmptyModule(source)).toBe(true);
|
||||
});
|
||||
|
||||
it("treats a 'use strict' prologue with no code as empty", () => {
|
||||
expect(isEffectivelyEmptyModule("'use strict';\n//# sourceMappingURL=x.map")).toBe(true);
|
||||
});
|
||||
|
||||
it("treats a bare `export {};` as empty", () => {
|
||||
expect(isEffectivelyEmptyModule("export {};")).toBe(true);
|
||||
});
|
||||
|
||||
it("does not treat a module with real exports as empty", () => {
|
||||
expect(isEffectivelyEmptyModule("export const x = 1;")).toBe(false);
|
||||
});
|
||||
|
||||
it("does not treat a module with imports as empty", () => {
|
||||
expect(isEffectivelyEmptyModule("import './side-effect.js';")).toBe(false);
|
||||
});
|
||||
|
||||
it("does not treat a module with executable code as empty", () => {
|
||||
expect(isEffectivelyEmptyModule("console.log('hi');")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveEmptyModuleFallback", () => {
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("synthesizes an empty module when jsDelivr runtime is empty", async () => {
|
||||
const fetchMock = vi.fn(async () => ({
|
||||
ok: true,
|
||||
text: async () => "\n//# sourceMappingURL=index.browser.mjs.map",
|
||||
})) as unknown as typeof fetch;
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const result = await resolveEmptyModuleFallback(
|
||||
"https://esm.sh/*@solana/rpc-parsed-types?target=esnext",
|
||||
new Map(),
|
||||
);
|
||||
|
||||
expect(result).toBe("export {};\n");
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"https://cdn.jsdelivr.net/npm/@solana/rpc-parsed-types/+esm",
|
||||
);
|
||||
});
|
||||
|
||||
it("recovers the version from the lockfile index", async () => {
|
||||
const fetchMock = vi.fn(async () => ({
|
||||
ok: true,
|
||||
text: async () => "//# sourceMappingURL=x.map",
|
||||
})) as unknown as typeof fetch;
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const nameVersionToPaths = new Map<string, string[]>([
|
||||
["@solana/[email protected]", ["node_modules/@solana/rpc-parsed-types"]],
|
||||
]);
|
||||
|
||||
await resolveEmptyModuleFallback(
|
||||
"https://esm.sh/*@solana/rpc-parsed-types?target=esnext",
|
||||
nameVersionToPaths,
|
||||
);
|
||||
|
||||
expect(fetchMock).toHaveBeenCalledWith(
|
||||
"https://cdn.jsdelivr.net/npm/@solana/[email protected]/+esm",
|
||||
);
|
||||
});
|
||||
|
||||
it("returns undefined for a non-empty package (does not mask real failures)", async () => {
|
||||
const fetchMock = vi.fn(async () => ({
|
||||
ok: true,
|
||||
text: async () => "export const isNumber = () => true;",
|
||||
})) as unknown as typeof fetch;
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const result = await resolveEmptyModuleFallback(
|
||||
"https://esm.sh/*[email protected]?target=esnext",
|
||||
new Map(),
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("returns undefined when the jsDelivr fallback also fails", async () => {
|
||||
const fetchMock = vi.fn(async () => ({
|
||||
ok: false,
|
||||
text: async () => "",
|
||||
})) as unknown as typeof fetch;
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const result = await resolveEmptyModuleFallback(
|
||||
"https://esm.sh/*@solana/rpc-parsed-types?target=esnext",
|
||||
new Map(),
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
it("does not attempt recovery for non-JS asset requests", async () => {
|
||||
const fetchMock = vi.fn();
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
|
||||
const result = await resolveEmptyModuleFallback(
|
||||
"https://esm.sh/[email protected]/styles.css?target=esnext",
|
||||
new Map(),
|
||||
);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
+144
-2
@@ -416,7 +416,10 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
|
||||
const ext = extname(fullURL.pathname).slice(1);
|
||||
if (ext && !["ts", "tsx", "js", "jsx", "mjs", "cjs", "css", "json"].includes(ext)) {
|
||||
return {
|
||||
path: fullURL.toString(),
|
||||
// Strip esm.sh's `/*` wildcard prefix so the URL is safe to embed
|
||||
// verbatim in CSS `url()` (a literal `/*` there is misread as a CSS
|
||||
// comment by some parsers, including the Tailwind v4 runtime).
|
||||
path: stripAssetUrlWildcard(fullURL.toString()),
|
||||
external: true,
|
||||
};
|
||||
}
|
||||
@@ -447,6 +450,20 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
|
||||
}
|
||||
|
||||
if (!res.ok) {
|
||||
// Some packages ship only TypeScript types with an effectively-empty
|
||||
// runtime JS file (e.g. `@solana/rpc-parsed-types`). esm.sh's build
|
||||
// pipeline rejects these zero-export modules with an HTTP 500, even
|
||||
// though the package is perfectly valid — consumers only import its
|
||||
// types at compile time. When that happens, fall back to a raw CDN
|
||||
// (jsDelivr) to inspect the actual runtime. If the runtime is indeed
|
||||
// empty (no exports/imports/code), synthesize an empty ES module so
|
||||
// the build can proceed. Genuine failures (non-empty modules that
|
||||
// failed for other reasons) are re-thrown unchanged.
|
||||
const empty = await resolveEmptyModuleFallback(args.path, nameVersionToPaths);
|
||||
if (empty !== undefined) {
|
||||
return { contents: empty, loader: "js" };
|
||||
}
|
||||
|
||||
throw new Error(`Failed to fetch ${args.path}`);
|
||||
}
|
||||
|
||||
@@ -477,8 +494,11 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
|
||||
|
||||
// Convert `?url` imports to URL strings pointing to the ESM CDN
|
||||
build.onLoad({ filter: /.*/, namespace: "esm-file-external" }, (args) => {
|
||||
// Strip esm.sh's `/*` wildcard prefix: these URLs are asset references
|
||||
// that may be embedded in CSS, where a literal `/*` in `url()` breaks
|
||||
// some CSS parsers (including the Tailwind v4 runtime).
|
||||
return {
|
||||
contents: `export default ${JSON.stringify(args.path)};`,
|
||||
contents: `export default ${JSON.stringify(stripAssetUrlWildcard(args.path))};`,
|
||||
loader: "js",
|
||||
};
|
||||
});
|
||||
@@ -509,3 +529,125 @@ function extractPackageName(esmURL: string): { pkg?: string; version?: string }
|
||||
|
||||
return { pkg, version };
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove esm.sh's leading `/*` wildcard prefix from an asset URL's path.
|
||||
*
|
||||
* Shakespeare resolves CDN modules through esm.sh's `*` ("externalize all
|
||||
* dependencies") prefix, e.g. `https://esm.sh/*@fontsource/x@1/...`. That `*`
|
||||
* only influences how esm.sh builds JavaScript modules; for raw static assets
|
||||
* (fonts, images, wasm, …) it is meaningless and esm.sh serves the identical
|
||||
* file with or without it.
|
||||
*
|
||||
* The prefix is harmful when the asset URL is written verbatim into CSS:
|
||||
* `src: url(https://esm.sh/*@fontsource/...woff2)` contains a literal `/*`
|
||||
* inside an unquoted `url()`, which several CSS parsers (notably the in-browser
|
||||
* Tailwind v4 tokenizer) misread as the start of a CSS comment. The
|
||||
* tokenizer then scans past the rule's closing `}`, leaving the `@font-face`
|
||||
* rule unterminated and throwing "Missing closing } at font-face".
|
||||
*
|
||||
* Stripping the wildcard from asset URLs keeps the emitted CSS parseable by all
|
||||
* CSS parsers. JS module URLs are left untouched (they are not passed through
|
||||
* this helper) since they legitimately rely on the `*` prefix.
|
||||
*/
|
||||
export function stripAssetUrlWildcard(urlStr: string): string {
|
||||
try {
|
||||
const url = new URL(urlStr);
|
||||
if (!url.pathname.startsWith("/*")) return urlStr;
|
||||
url.pathname = url.pathname.replace(/^\/\*/, "/");
|
||||
return url.toString();
|
||||
} catch {
|
||||
return urlStr;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether a chunk of JavaScript is an "empty" runtime module — i.e.
|
||||
* it contains no executable code and no ES `import`/`export` statements once
|
||||
* comments and whitespace are stripped. This is the signature of a types-only
|
||||
* package whose compiled JS is intentionally empty.
|
||||
*/
|
||||
export function isEffectivelyEmptyModule(source: string): boolean {
|
||||
const stripped = source
|
||||
// Block comments (including jsDelivr/esm.sh banners and sourceMappingURL)
|
||||
.replace(/\/\*[\s\S]*?\*\//g, "")
|
||||
// Line comments (covers `//# sourceMappingURL=...`)
|
||||
.replace(/^\s*\/\/.*$/gm, "")
|
||||
// Directive prologues like `'use strict';` / `"use strict";`
|
||||
.replace(/^\s*(['"])use strict\1\s*;?\s*$/gm, "")
|
||||
.trim();
|
||||
|
||||
if (stripped.length === 0) return true;
|
||||
|
||||
// If there's any leftover content, only treat it as empty when it carries no
|
||||
// imports, exports, or other meaningful tokens. A bare `export {};` counts as
|
||||
// empty (it exports nothing), but anything else is a real module.
|
||||
if (/^export\s*\{\s*\}\s*;?$/.test(stripped)) return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* When esm.sh fails to build a module, attempt to recover by inspecting the
|
||||
* package's actual runtime via jsDelivr's `+esm` endpoint. If that runtime is
|
||||
* effectively empty (a types-only package), return an empty ES module string.
|
||||
* Returns `undefined` when the package is not empty (so the caller should treat
|
||||
* the original failure as fatal).
|
||||
*/
|
||||
export async function resolveEmptyModuleFallback(
|
||||
esmURL: string,
|
||||
nameVersionToPaths: Map<string, string[]>,
|
||||
): Promise<string | undefined> {
|
||||
let pkg: string | undefined;
|
||||
let version: string | undefined;
|
||||
|
||||
try {
|
||||
({ pkg, version } = extractPackageName(esmURL));
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
if (!pkg) return undefined;
|
||||
|
||||
// Only attempt the empty-module recovery for JavaScript module requests.
|
||||
// Asset/CSS/JSON failures are unrelated to the types-only-package problem and
|
||||
// should remain fatal.
|
||||
try {
|
||||
const ext = extname(new URL(esmURL).pathname).slice(1).toLowerCase();
|
||||
if (ext && !["js", "jsx", "mjs", "cjs", "ts", "tsx"].includes(ext)) {
|
||||
return undefined;
|
||||
}
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// The esm.sh URL for a transitive dependency often omits the version
|
||||
// (e.g. `*@solana/rpc-parsed-types?target=esnext`). Recover it from the
|
||||
// lockfile index when possible so the fallback fetch is deterministic.
|
||||
if (!version) {
|
||||
for (const key of nameVersionToPaths.keys()) {
|
||||
const at = key.lastIndexOf("@");
|
||||
if (at > 0 && key.slice(0, at) === pkg) {
|
||||
version = key.slice(at + 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const spec = version ? `${pkg}@${version}` : pkg;
|
||||
const fallbackURL = `https://cdn.jsdelivr.net/npm/${spec}/+esm`;
|
||||
|
||||
try {
|
||||
const res = await fetch(fallbackURL);
|
||||
if (!res.ok) return undefined;
|
||||
|
||||
const text = await res.text();
|
||||
if (isEffectivelyEmptyModule(text)) {
|
||||
return "export {};\n";
|
||||
}
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
@@ -388,11 +388,15 @@ describe('CurlCommand', () => {
|
||||
it('should handle timeout', async () => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
const abortFn = vi.fn();
|
||||
const mockController = {
|
||||
abort: vi.fn(),
|
||||
abort: abortFn,
|
||||
signal: { aborted: false }
|
||||
};
|
||||
global.AbortController = vi.fn(() => mockController) as unknown as typeof AbortController;
|
||||
global.AbortController = class {
|
||||
abort = abortFn;
|
||||
signal = mockController.signal;
|
||||
} as unknown as typeof AbortController;
|
||||
|
||||
// Mock fetch to reject with AbortError after timeout
|
||||
mockFetch.mockImplementation(() => {
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
/**
|
||||
* 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,
|
||||
};
|
||||
}
|
||||
@@ -24,11 +24,11 @@ vi.mock('nostr-tools', () => ({
|
||||
|
||||
// Mock NPool to avoid actual network calls
|
||||
vi.mock('@nostrify/nostrify', () => ({
|
||||
NPool: vi.fn().mockImplementation(() => ({
|
||||
event: vi.fn().mockResolvedValue(undefined),
|
||||
close: vi.fn().mockResolvedValue(undefined),
|
||||
})),
|
||||
NRelay1: vi.fn(),
|
||||
NPool: class {
|
||||
event = vi.fn().mockResolvedValue(undefined);
|
||||
close = vi.fn().mockResolvedValue(undefined);
|
||||
},
|
||||
NRelay1: class {},
|
||||
}));
|
||||
|
||||
describe('NostrPublishEventsTool', () => {
|
||||
|
||||
@@ -109,8 +109,9 @@ export function AISettings() {
|
||||
baseURL: preset.baseURL,
|
||||
};
|
||||
|
||||
if (apiKey.trim()) {
|
||||
newProvider.apiKey = apiKey.trim();
|
||||
const key = apiKey.trim() || preset.apiKey;
|
||||
if (key) {
|
||||
newProvider.apiKey = key;
|
||||
}
|
||||
if (typeof preset.nostr === 'boolean') {
|
||||
newProvider.nostr = preset.nostr;
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { useSeoMeta } from "@unhead/react";
|
||||
import { useEffect } from "react";
|
||||
import { CheckCircle2 } from "lucide-react";
|
||||
|
||||
// Callback target for mobile NIP-46 signer apps after they approve a
|
||||
// `nostrconnect://` request. The actual login completes via the relay
|
||||
// subscription in the original tab — this page just provides a friendly
|
||||
// landing if the signer opened it in a new tab/window.
|
||||
const RemoteLoginSuccess = () => {
|
||||
useSeoMeta({
|
||||
title: "Signer connected",
|
||||
description: "You can return to Shakespeare.",
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
// Best-effort: most signers open this in a new tab. Try to close it;
|
||||
// the manual link below is the fallback when the browser refuses.
|
||||
window.setTimeout(() => {
|
||||
try {
|
||||
window.close();
|
||||
} catch {
|
||||
// ignored
|
||||
}
|
||||
}, 500);
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-background px-4">
|
||||
<div className="text-center space-y-4 max-w-sm">
|
||||
<CheckCircle2 className="w-12 h-12 mx-auto text-green-500" />
|
||||
<h1 className="text-2xl font-semibold text-foreground">Signer connected</h1>
|
||||
<p className="text-muted-foreground">
|
||||
You can return to Shakespeare. Your login should complete automatically.
|
||||
</p>
|
||||
<a href="/" className="inline-block text-primary hover:text-primary/80 underline">
|
||||
Open Shakespeare
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default RemoteLoginSuccess;
|
||||
+91
-13
@@ -34,6 +34,81 @@ 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', () => ({}));
|
||||
@@ -72,21 +147,24 @@ Object.defineProperty(window, 'scrollTo', {
|
||||
Element.prototype.scrollIntoView = vi.fn();
|
||||
|
||||
// Mock IntersectionObserver
|
||||
global.IntersectionObserver = vi.fn().mockImplementation((_callback) => ({
|
||||
observe: vi.fn(),
|
||||
unobserve: vi.fn(),
|
||||
disconnect: vi.fn(),
|
||||
root: null,
|
||||
rootMargin: '',
|
||||
thresholds: [],
|
||||
}));
|
||||
class MockIntersectionObserver {
|
||||
root = null;
|
||||
rootMargin = '';
|
||||
thresholds: ReadonlyArray<number> = [];
|
||||
observe = vi.fn();
|
||||
unobserve = vi.fn();
|
||||
disconnect = vi.fn();
|
||||
takeRecords = vi.fn(() => []);
|
||||
}
|
||||
global.IntersectionObserver = MockIntersectionObserver as unknown as typeof IntersectionObserver;
|
||||
|
||||
// Mock ResizeObserver
|
||||
global.ResizeObserver = vi.fn().mockImplementation((_callback) => ({
|
||||
observe: vi.fn(),
|
||||
unobserve: vi.fn(),
|
||||
disconnect: vi.fn(),
|
||||
}));
|
||||
class MockResizeObserver {
|
||||
observe = vi.fn();
|
||||
unobserve = vi.fn();
|
||||
disconnect = vi.fn();
|
||||
}
|
||||
global.ResizeObserver = MockResizeObserver as unknown as typeof ResizeObserver;
|
||||
|
||||
// Mock indexedDB for LightningFS
|
||||
const mockIDBRequest = {
|
||||
|
||||
Reference in new issue
Block a user