Compare commits

..
11 Commits
Author SHA1 Message Date
Chad Curtis 431b8ec6bb release: v9.15.0 2026-08-19 12:52:59 -05:00
Chad Curtis 77b2be7a3b npm audit fix 2026-08-19 12:36:30 -05:00
Chad Curtis 90d02c42d6 Upgrade @nostrify/react to 0.6.6 to enforce the nostrconnect handshake secret
0.6.6 enforces the nostrconnect handshake secret. Previously a signer
could answer the connect request with result: "ack" and skip proving it
could decrypt the secret, so any relay-connected party who saw the
nostrconnect URI could claim the session and become the user's signer.

The 0.6.6 NostrLoginProvider now resolves stored logins on a microtask
(rendering a null fallback until storage resolves) rather than
synchronously. Component/hook tests render and query immediately, so
they observed an empty tree. Mock @nostrify/react/login in the test
setup with a synchronous provider and matching useNostrLogin hook,
passing every other export (NLogin, NUser, the connect helpers) through
from the real module untouched.
2026-08-19 12:34:08 -05:00
Chad Curtis d3cceb56ee Verify the LNURL invoice amount before paying a zap
Zapping asked the recipient's LNURL-pay server for an invoice and paid
whatever came back, checking only that it was a non-empty string. The
server is chosen by the recipient, so anyone who posts a note and runs
their own endpoint decided how much their victims paid — after the
victim had already approved a figure. The success toast reported the
requested amount rather than the paid one, so an overcharge left no
trace in the UI either.

Add a BOLT11 decoder (bech32 + tagged fields, on @scure/base and
@noble/hashes, both already bundled via nostr-tools) and require the
returned invoice to charge exactly the millisats the user approved.
Amountless invoices are rejected outright. The check runs before the
NWC, WebLN and QR paths alike, and useNWC's sendPayment now takes the
approved amount and re-checks it, so no future caller can hand the
wallet an unvetted invoice.

Resolve LNURL-pay in-repo instead of via nip57.getZapEndpoint, which
returns only the callback URL and discards everything used to validate
the response: HTTPS is now required for both the LNURL and the callback
it names, the advertised minSendable/maxSendable are honoured, and the
invoice's description hash is checked against the zap request (NIP-57)
or the endpoint metadata (LUD-06) when it carries one.

Report the decoded amount in the success toast so it can never
understate a spend.

Adapted from Alex Gleason's ditto commit 6e062450.
2026-08-19 12:16:08 -05:00
Alex Gleason fd23c10f20 Use the nsyte baked into the runner image
Falls back to downloading it, so the workflow still runs on a coordinator
whose image does not carry it.
2026-08-17 10:36:27 -05:00
Alex Gleason 0d73c79d4c Retry the whole nsyte download until the binary runs
From this coordinator the 115 MB release download fails about half the
time, mid-transfer, with an SSL record-mac error; curl's own --retry does
not help because each attempt breaks identically. Loop the fetch, force
HTTP/1.1, and run the binary before accepting it.

The durable fix is baking nsyte into the CI image.
2026-08-17 02:55:03 -05:00
Alex Gleason f951f21535 Retry the nsyte download
It has failed here with "SSL_read: decryption failed or bad record mac",
which curl does not treat as retryable. Also -f, so an HTTP error page is
never saved as the binary, and a version check to catch a truncated one.
2026-08-17 02:22:05 -05:00
Alex Gleason a20fab1ab4 Publish shakespeare.diy as an nsite from ngit-ci
Replaces the GitLab deploy and deploy-nsite jobs. The old nsite job published
under a personal npub; the signing pubkey is the site address, so this one
lives in the Team Soapbox namespace and is served by npanel.
2026-08-17 01:33:45 -05:00
Alex Gleason 97714079d3 Merge branch 'feat/meridian-provider' into 'main'
Feat/meridian provider

See merge request soapbox-pub/shakespeare!119
2026-07-24 01:12:13 +00:00
lemon 01d20c5743 Prefill Meridian placeholder API key, skip ToS checkbox, add purple Globe icon 2026-07-23 17:23:00 -07:00
lemon f2612831c6 Add Meridian local bridge to AI provider presets 2026-07-23 17:14:13 -07:00
22 changed files with 1087 additions and 887 deletions

No files matched your search

+120
View File
@@ -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
+31
View File
@@ -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
+20
View File
@@ -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 -2
View File
@@ -42,7 +42,6 @@ Shakespeare provides AI agents with specialized tools for project development (n
- **TextEditorWriteTool**: Create or overwrite files with new content
- **TextEditorStrReplaceTool**: Replace strings in files
- **BuildProjectTool**: Build and compile projects
- **TypecheckProjectTool**: Typecheck projects with the TypeScript compiler, similar to `tsc --noEmit`
- **NpmAddPackageTool**: Add npm packages to projects
- **NpmRemovePackageTool**: Remove npm packages from projects
- **GitCommitTool**: Commit changes to Git repositories
@@ -272,7 +271,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- Unix-style commands: `cat`, `cd`, `cp`, `find`, `grep`, `ls`, `mkdir`, `mv`, `rm`, etc.
- `/src/lib/tools/`: AI tool implementations for project development
- File operations: `TextEditorViewTool`, `TextEditorWriteTool`, `TextEditorStrReplaceTool`
- Project tools: `BuildProjectTool`, `TypecheckProjectTool`
- Project tools: `BuildProjectTool`
- Package management: `NpmAddPackageTool`, `NpmRemovePackageTool`
- Git integration: `GitCommitTool`
- Shell access: `ShellTool`
+9
View File
@@ -1,5 +1,14 @@
# 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
+183 -127
View File
@@ -21,8 +21,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",
@@ -55,7 +55,6 @@
"@sentry/react": "^10.22.0",
"@std/encoding": "npm:@jsr/std__encoding@^1.0.10",
"@tanstack/react-query": "^5.56.2",
"@typescript/ata": "^0.9.8",
"@unhead/addons": "^2.0.10",
"@unhead/react": "^2.0.10",
"acorn": "^8.16.0",
@@ -98,7 +97,6 @@
"tailwindcss-animate": "^1.0.7",
"tailwindcss-safe-area": "^0.8.0",
"turndown": "^7.2.1",
"typescript": "^5.8.3",
"uri-templates": "^0.2.0",
"use-stick-to-bottom": "^1.1.1",
"vaul": "^0.9.3",
@@ -136,6 +134,7 @@
"jsdom": "^26.1.0",
"postcss": "^8.4.47",
"tailwindcss": "^3.4.11",
"typescript": "^5.5.3",
"typescript-eslint": "^8.0.1",
"vite": "^6.3.5",
"vite-plugin-pwa": "^1.1.0",
@@ -191,9 +190,9 @@
}
},
"node_modules/@babel/compat-data": {
"version": "7.29.0",
"resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.0.tgz",
"integrity": "sha512-T1NCJqT/j9+cn8fvkt7jtwbLBfLC/1y1c7NtCeXFRgzGTsafi68MRv8yzkYSapBnFA6L3U2VSc02ciDzoAJhJg==",
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz",
"integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==",
"dev": true,
"license": "MIT",
"engines": {
@@ -201,21 +200,21 @@
}
},
"node_modules/@babel/core": {
"version": "7.29.0",
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.0.tgz",
"integrity": "sha512-CGOfOJqWjg2qW/Mb6zNsDm+u5vFQ8DxXfbM09z69p5Z6+mE1ikP2jUXw+j42Pf1XTYED2Rni5f95npYeuwMDQA==",
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz",
"integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/code-frame": "^7.29.0",
"@babel/generator": "^7.29.0",
"@babel/helper-compilation-targets": "^7.28.6",
"@babel/helper-module-transforms": "^7.28.6",
"@babel/helpers": "^7.28.6",
"@babel/parser": "^7.29.0",
"@babel/template": "^7.28.6",
"@babel/traverse": "^7.29.0",
"@babel/types": "^7.29.0",
"@babel/code-frame": "^7.29.7",
"@babel/generator": "^7.29.7",
"@babel/helper-compilation-targets": "^7.29.7",
"@babel/helper-module-transforms": "^7.29.7",
"@babel/helpers": "^7.29.7",
"@babel/parser": "^7.29.7",
"@babel/template": "^7.29.7",
"@babel/traverse": "^7.29.7",
"@babel/types": "^7.29.7",
"@jridgewell/remapping": "^2.3.5",
"convert-source-map": "^2.0.0",
"debug": "^4.1.0",
@@ -271,14 +270,14 @@
}
},
"node_modules/@babel/helper-compilation-targets": {
"version": "7.28.6",
"resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.28.6.tgz",
"integrity": "sha512-JYtls3hqi15fcx5GaSNL7SCTJ2MNmjrkHXg4FSpOA/grxK8KwyZ5bubHsCq8FXCkua6xhuaaBit+3b7+VZRfcA==",
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz",
"integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/compat-data": "^7.28.6",
"@babel/helper-validator-option": "^7.27.1",
"@babel/compat-data": "^7.29.7",
"@babel/helper-validator-option": "^7.29.7",
"browserslist": "^4.24.0",
"lru-cache": "^5.1.1",
"semver": "^6.3.1"
@@ -532,9 +531,9 @@
}
},
"node_modules/@babel/helper-validator-option": {
"version": "7.27.1",
"resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.27.1.tgz",
"integrity": "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==",
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz",
"integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==",
"dev": true,
"license": "MIT",
"engines": {
@@ -557,14 +556,14 @@
}
},
"node_modules/@babel/helpers": {
"version": "7.29.2",
"resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.2.tgz",
"integrity": "sha512-HoGuUs4sCZNezVEKdVcwqmZN8GoHirLUcLaYVNBK2J0DadGtdcqgr3BCbvH8+XUo4NGjNl3VOtSjEKNzqfFgKw==",
"version": "7.29.7",
"resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz",
"integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/template": "^7.28.6",
"@babel/types": "^7.29.0"
"@babel/template": "^7.29.7",
"@babel/types": "^7.29.7"
},
"engines": {
"node": ">=6.9.0"
@@ -2683,9 +2682,9 @@
}
},
"node_modules/@hono/node-server": {
"version": "1.19.14",
"resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.14.tgz",
"integrity": "sha512-GwtvgtXxnWsucXvbQXkRgqksiH2Qed37H9xHZocE5sA3N8O8O8/8FA3uclQXxXVzc9XBZuEOMK7+r02FmSpHtw==",
"version": "1.19.17",
"resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.17.tgz",
"integrity": "sha512-dSneS5qhiauZWGDCeK4o695Xd9nUNjviSZCMQrj10eetr8Uln1ucn6bbphOM6UynAMMtNIzZNSpL9vnASJwrPQ==",
"license": "MIT",
"engines": {
"node": ">=18.14.1"
@@ -3294,11 +3293,11 @@
}
},
"node_modules/@nostrify/nostrify": {
"version": "0.51.1",
"resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.51.1.tgz",
"integrity": "sha512-oPJhUiO1TlV5sGYizqAP4GvLijib34Uwh48wxlFimR/2MoCuSmab4AppcztGPNwxQoTKkJbLJwsSpl42V+WIXA==",
"version": "0.54.1",
"resolved": "https://registry.npmjs.org/@nostrify/nostrify/-/nostrify-0.54.1.tgz",
"integrity": "sha512-/iMRPBZdz+74pPXKHbQ7RsMwQtEXbJ/M21iNp1kbAMMvRh30hFjdV3ROU93rxGIDsOMSOpzeXXWT4Z+gXZW8Bg==",
"dependencies": {
"@nostrify/types": "0.36.9",
"@nostrify/types": "0.37.0",
"@scure/base": "^2.0.0",
"@smithy/util-base64": "^4.3.0",
"@smithy/util-hex-encoding": "^4.2.0",
@@ -3335,12 +3334,12 @@
"license": "MIT"
},
"node_modules/@nostrify/react": {
"version": "0.4.1",
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.4.1.tgz",
"integrity": "sha512-2JXxEl4e6FIFhbi96Dwv2knu5qAACYulo1a0oVell/aS8KCWsBTPd1+v0EUra0yqiUA3Q1nVLrk8mx7kQYH/yQ==",
"version": "0.6.6",
"resolved": "https://registry.npmjs.org/@nostrify/react/-/react-0.6.6.tgz",
"integrity": "sha512-WTWTT3dtw0BF5bZsFgOob9S3J9rWKOsPQ2LLKDsDhx3PxbjIFKSVqSQLw7jiN6LoVGom9OuVOG/PB6p9hAWDjQ==",
"dependencies": {
"@nostrify/nostrify": "0.51.1",
"@nostrify/types": "0.36.9"
"@nostrify/nostrify": "0.54.1",
"@nostrify/types": "0.37.0"
},
"peerDependencies": {
"@tanstack/react-query": "^5.69.0",
@@ -3350,9 +3349,9 @@
}
},
"node_modules/@nostrify/types": {
"version": "0.36.9",
"resolved": "https://registry.npmjs.org/@nostrify/types/-/types-0.36.9.tgz",
"integrity": "sha512-tMx/r0W+QoVRRgs8d6ltaSgrftasOXuFsi33kW8WirswCy2b3UR1tqRgc0iBU9zRa9XR0nlej/wJZW+6wUFi+Q=="
"version": "0.37.0",
"resolved": "https://registry.npmjs.org/@nostrify/types/-/types-0.37.0.tgz",
"integrity": "sha512-P0AKR+qcNeBBTA5UDnJM6SxLAQbgud2+ZcdVyheoP37XGQvi7rUncQUDKwebG+Ui5kswp/IPEmvqNtCMQpwRoA=="
},
"node_modules/@opensecret/react": {
"version": "1.5.4",
@@ -4901,9 +4900,9 @@
"license": "MIT"
},
"node_modules/@remix-run/router": {
"version": "1.23.3",
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.3.tgz",
"integrity": "sha512-4An71tdz9X8+3sI4Qqqd2LWd9vS39J7sqd9EU4Scw7TJE/qB10Flv/UuqbPVgfQV9XoK8Np6jNquZitnZq5i+Q==",
"version": "1.23.4",
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.4.tgz",
"integrity": "sha512-q7j5geK7xs3UJSdm9/iytUNclBnLmYx1EnSeCFXHPeutdqgIMeFeHtUZgS3EhlKxdBEAu8OwtJCwmLrEzpSs7Q==",
"license": "MIT",
"engines": {
"node": ">=14.0.0"
@@ -5053,6 +5052,7 @@
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5066,6 +5066,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5079,6 +5080,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5092,6 +5094,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5105,6 +5108,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5118,6 +5122,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5131,6 +5136,7 @@
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5144,6 +5150,7 @@
"cpu": [
"arm"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5157,6 +5164,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5170,6 +5178,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5183,6 +5192,7 @@
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5196,6 +5206,7 @@
"cpu": [
"loong64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5209,6 +5220,7 @@
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5222,6 +5234,7 @@
"cpu": [
"ppc64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5235,6 +5248,7 @@
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5248,6 +5262,7 @@
"cpu": [
"riscv64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5261,6 +5276,7 @@
"cpu": [
"s390x"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5274,6 +5290,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5287,6 +5304,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5300,6 +5318,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5313,6 +5332,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5326,6 +5346,7 @@
"cpu": [
"arm64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5339,6 +5360,7 @@
"cpu": [
"ia32"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5352,6 +5374,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -5365,6 +5388,7 @@
"cpu": [
"x64"
],
"dev": true,
"license": "MIT",
"optional": true,
"os": [
@@ -6605,9 +6629,9 @@
}
},
"node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": {
"version": "2.1.2",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.2.tgz",
"integrity": "sha512-w5JZcKgdhDOgOwm8H+KgbosopHMuGcl6qbulwjtz3SM7I7P3yW1eAjzMPLrIE+NQ9vjgANKHWeMHnrT0OXW1oA==",
"version": "2.1.4",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz",
"integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -6672,15 +6696,6 @@
"url": "https://opencollective.com/typescript-eslint"
}
},
"node_modules/@typescript/ata": {
"version": "0.9.8",
"resolved": "https://registry.npmjs.org/@typescript/ata/-/ata-0.9.8.tgz",
"integrity": "sha512-+M815CeDRJS5H5ciWfhFCKp25nNfF+LFWawWAaBhNlquFb2wS5IIMDI+2bKWN3GuU6mpj+FzySsOD29M4nG8Xg==",
"license": "MIT",
"peerDependencies": {
"typescript": ">=4.4.4"
}
},
"node_modules/@ungap/structured-clone": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/@ungap/structured-clone/-/structured-clone-1.3.0.tgz",
@@ -7345,20 +7360,20 @@
}
},
"node_modules/body-parser": {
"version": "2.2.2",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.2.2.tgz",
"integrity": "sha512-oP5VkATKlNwcgvxi0vM0p/D3n2C3EReYVX+DNYs5TjZFn/oQt2j+4sVJtSMr18pdRr8wjTcBl6LoV+FUwzPmNA==",
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/body-parser/-/body-parser-2.3.0.tgz",
"integrity": "sha512-2cGmJupaNgg+QUwVLAucDuWuoMZ6EX9iHDRswZ5lsNYEmwPaRknMPCLZz07yTzVq/83p4o/wzbDZbBrTvGGTIw==",
"license": "MIT",
"dependencies": {
"bytes": "^3.1.2",
"content-type": "^1.0.5",
"content-type": "^2.0.0",
"debug": "^4.4.3",
"http-errors": "^2.0.0",
"iconv-lite": "^0.7.0",
"http-errors": "^2.0.1",
"iconv-lite": "^0.7.2",
"on-finished": "^2.4.1",
"qs": "^6.14.1",
"raw-body": "^3.0.1",
"type-is": "^2.0.1"
"qs": "^6.15.2",
"raw-body": "^3.0.2",
"type-is": "^2.1.0"
},
"engines": {
"node": ">=18"
@@ -7368,6 +7383,19 @@
"url": "https://opencollective.com/express"
}
},
"node_modules/body-parser/node_modules/content-type": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz",
"integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==",
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/body-parser/node_modules/iconv-lite": {
"version": "0.7.2",
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.2.tgz",
@@ -7398,9 +7426,9 @@
}
},
"node_modules/brace-expansion": {
"version": "1.1.13",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.13.tgz",
"integrity": "sha512-9ZLprWS6EENmhEOpjCYW2c8VkmOvckIJZfkr7rBW6dObmfgJ/L1GpSYW5Hpo9lDz4D1+n0Ckz8rU7FwHDQiG/w==",
"version": "1.1.18",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz",
"integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -9221,9 +9249,9 @@
"license": "Apache-2.0"
},
"node_modules/fast-uri": {
"version": "3.1.2",
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz",
"integrity": "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==",
"version": "3.1.5",
"resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.5.tgz",
"integrity": "sha512-gHwA1O9LDIcKunMKhObS/HimwtehO1nPUECKAu5TpKgaO19fcWEl4bliWe1jWxVFvIXztJjjQ4L8XQ1EU9f7Jw==",
"funding": [
{
"type": "github",
@@ -9279,9 +9307,9 @@
}
},
"node_modules/filelist/node_modules/brace-expansion": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.1.tgz",
"integrity": "sha512-WR1cURNjuvBLMZBMbqM0UoE+WAfdUcEV1ccD8PVBVOI+Z3ND4+SZbN8RsfT2bMuG1qwz5RFvPukSZm5fF2D5eA==",
"version": "2.1.4",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz",
"integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -9638,9 +9666,9 @@
}
},
"node_modules/glob/node_modules/brace-expansion": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.3.tgz",
"integrity": "sha512-MCV/fYJEbqx68aE58kv2cA/kiky1G8vux3OR6/jbS+jIMe/6fJWa0DTzJU7dqijOWYwHi1t29FlfYI9uytqlpA==",
"version": "2.1.4",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.1.4.tgz",
"integrity": "sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==",
"license": "MIT",
"dependencies": {
"balanced-match": "^1.0.0"
@@ -9742,9 +9770,9 @@
}
},
"node_modules/gray-matter/node_modules/js-yaml": {
"version": "3.14.2",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.14.2.tgz",
"integrity": "sha512-PMSmkqxr106Xa156c2M265Z+FTrPl+oxd/rgOQy2tijQeK5TxQ43psO1ZCwhVOSdnn+RzkzlRz/eY4BgJBYVpg==",
"version": "3.15.1",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-3.15.1.tgz",
"integrity": "sha512-S99WuO3HlhO3XN41EtYUNl9zzXjoJx7QvmipxsJVxtCBT0YHEFy+iOJhjSvrmV12nYhWpZaM8lPHkJm0yUMbag==",
"license": "MIT",
"dependencies": {
"argparse": "^1.0.7",
@@ -10067,9 +10095,9 @@
"license": "MIT"
},
"node_modules/hono": {
"version": "4.12.23",
"resolved": "https://registry.npmjs.org/hono/-/hono-4.12.23.tgz",
"integrity": "sha512-eIaZ9qDgu7XV0pxOCrg7/WhnQ6Ivm22UcxhXx/A3dcbqbbYgBEkc6e/J/s7j2tS96zoB0S9VBdLwQNCWwUo4LA==",
"version": "4.13.3",
"resolved": "https://registry.npmjs.org/hono/-/hono-4.13.3.tgz",
"integrity": "sha512-r8AO2mYHoLxSHkgafNeC/BXyb2vWRxD3jem4Ts+ptav8oTG5FIRifAjuJEmZI4bSvvc2ns0GxmIYiZnHqN3mMw==",
"license": "MIT",
"engines": {
"node": ">=16.9.0"
@@ -10351,9 +10379,9 @@
}
},
"node_modules/ip-address": {
"version": "10.2.0",
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.2.0.tgz",
"integrity": "sha512-/+S6j4E9AHvW9SWMSEY9Xfy66O5PWvVEJ08O0y5JGyEKQpojb0K0GKpz/v5HJ/G0vi3D2sjGK78119oXZeE0qA==",
"version": "10.5.0",
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.5.0.tgz",
"integrity": "sha512-R5SnVLJmgYYvf2F2ZgwSBnelz5G4q5AxIC277GDfUaNbrZKNANcBC7RHqYYePlszf4kBolVkJauG0ZjHHFh55g==",
"license": "MIT",
"engines": {
"node": ">= 12"
@@ -11001,10 +11029,20 @@
"license": "MIT"
},
"node_modules/js-yaml": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz",
"integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==",
"version": "4.3.1",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.1.tgz",
"integrity": "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==",
"dev": true,
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/puzrin"
},
{
"type": "github",
"url": "https://github.com/sponsors/nodeca"
}
],
"license": "MIT",
"dependencies": {
"argparse": "^2.0.1"
@@ -12626,9 +12664,9 @@
}
},
"node_modules/nanoid": {
"version": "3.3.12",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz",
"integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==",
"version": "3.3.18",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",
"integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==",
"funding": [
{
"type": "github",
@@ -13215,9 +13253,9 @@
}
},
"node_modules/postcss": {
"version": "8.5.15",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz",
"integrity": "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==",
"version": "8.5.26",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.26.tgz",
"integrity": "sha512-u82N74LFzG8ca+dD8puPnplTXoGH4fTPpVGuIbt36G3qvNlkvfD0lEAZSxaly3KX8TS/L1A1gsCEmvKmBcVbkQ==",
"funding": [
{
"type": "opencollective",
@@ -13234,7 +13272,7 @@
],
"license": "MIT",
"dependencies": {
"nanoid": "^3.3.12",
"nanoid": "^3.3.17",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
},
@@ -13826,12 +13864,12 @@
}
},
"node_modules/react-router": {
"version": "6.30.4",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.4.tgz",
"integrity": "sha512-SVUsDe+DybHM/WmYKIVYhZh1o5Dcuf16yM6WjG02Q9XVFMZIJyHYhwrr6bFBXZkVP6z69kNkMyBCujt8FaFLJA==",
"version": "6.30.6",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.6.tgz",
"integrity": "sha512-5HfK7k5im7LTOB0EqCQmfvy4C13G92Ssj1VTmouTK3AJvyjKTnFuCV0vcMAD/JS+JC4DvDIBRrlAeJIFjh5VWg==",
"license": "MIT",
"dependencies": {
"@remix-run/router": "1.23.3"
"@remix-run/router": "1.23.4"
},
"engines": {
"node": ">=14.0.0"
@@ -13841,13 +13879,13 @@
}
},
"node_modules/react-router-dom": {
"version": "6.30.4",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.4.tgz",
"integrity": "sha512-q4HvNl+mmDdkS0g+MqiBZNteQJCuimWoOyHMy4T/RQLAn9Z29+E91QXRaxOujeMl2HTzRSS0KFPd7lxX3PjV0Q==",
"version": "6.30.6",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.6.tgz",
"integrity": "sha512-0RHKZz7wwffvkU+2MFVT2NnjK44ssLEV+m0CAJaS2Ksmorrwj7WxH00jO0SOCW26/tINUnJHToXblDs33I38YQ==",
"license": "MIT",
"dependencies": {
"@remix-run/router": "1.23.3",
"react-router": "6.30.4"
"@remix-run/router": "1.23.4",
"react-router": "6.30.6"
},
"engines": {
"node": ">=14.0.0"
@@ -14319,16 +14357,16 @@
}
},
"node_modules/rimraf/node_modules/brace-expansion": {
"version": "5.0.6",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.6.tgz",
"integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==",
"version": "5.0.9",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz",
"integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==",
"dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^4.0.2"
},
"engines": {
"node": "18 || 20 || >=22"
"node": "20 || >=22"
}
},
"node_modules/rimraf/node_modules/glob": {
@@ -15572,9 +15610,9 @@
}
},
"node_modules/tar": {
"version": "7.5.13",
"resolved": "https://registry.npmjs.org/tar/-/tar-7.5.13.tgz",
"integrity": "sha512-tOG/7GyXpFevhXVh8jOPJrmtRpOTsYqUIkVdVooZYJS/z8WhfQUX8RJILmeuJNinGAMSu1veBr4asSHFt5/hng==",
"version": "7.5.22",
"resolved": "https://registry.npmjs.org/tar/-/tar-7.5.22.tgz",
"integrity": "sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA==",
"dev": true,
"license": "BlueOak-1.0.0",
"dependencies": {
@@ -15961,17 +15999,34 @@
}
},
"node_modules/type-is": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-2.0.1.tgz",
"integrity": "sha512-OZs6gsjF4vMp32qrCbiVSkrFmXtG/AZhY3t0iAMrMBiAZyV9oALtXO8hsrHbMXF9x6L3grlFuwW2oAz7cav+Gw==",
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-2.1.0.tgz",
"integrity": "sha512-faYHw0anBbc/kWF3zFTEnxSFOAGUX9GFbOBthvDdLsIlEoWOFOtS0zgCiQYwIskL9iGXZL3kAXD8OoZ4GmMATA==",
"license": "MIT",
"dependencies": {
"content-type": "^1.0.5",
"content-type": "^2.0.0",
"media-typer": "^1.1.0",
"mime-types": "^3.0.0"
},
"engines": {
"node": ">= 0.6"
"node": ">= 18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/type-is/node_modules/content-type": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/content-type/-/content-type-2.1.0.tgz",
"integrity": "sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag==",
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/typed-array-buffer": {
@@ -16055,6 +16110,7 @@
"version": "5.8.3",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.8.3.tgz",
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
"devOptional": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
@@ -17186,16 +17242,16 @@
}
},
"node_modules/workbox-build/node_modules/brace-expansion": {
"version": "5.0.6",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.6.tgz",
"integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==",
"version": "5.0.9",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz",
"integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==",
"dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^4.0.2"
},
"engines": {
"node": "18 || 20 || >=22"
"node": "20 || >=22"
}
},
"node_modules/workbox-build/node_modules/glob": {
+4 -5
View File
@@ -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.14.0",
"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",
@@ -68,7 +68,6 @@
"@sentry/react": "^10.22.0",
"@std/encoding": "npm:@jsr/std__encoding@^1.0.10",
"@tanstack/react-query": "^5.56.2",
"@typescript/ata": "^0.9.8",
"@unhead/addons": "^2.0.10",
"@unhead/react": "^2.0.10",
"acorn": "^8.16.0",
@@ -111,7 +110,6 @@
"tailwindcss-animate": "^1.0.7",
"tailwindcss-safe-area": "^0.8.0",
"turndown": "^7.2.1",
"typescript": "^5.8.3",
"uri-templates": "^0.2.0",
"use-stick-to-bottom": "^1.1.1",
"vaul": "^0.9.3",
@@ -149,6 +147,7 @@
"jsdom": "^26.1.0",
"postcss": "^8.4.47",
"tailwindcss": "^3.4.11",
"typescript": "^5.5.3",
"typescript-eslint": "^8.0.1",
"vite": "^6.3.5",
"vite-plugin-pwa": "^1.1.0",
+9
View File
@@ -1,5 +1,14 @@
# 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
+19 -21
View File
@@ -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())
}
>
+28
View File
@@ -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 (
-2
View File
@@ -27,7 +27,6 @@ import { NpmAddPackageTool } from '@/lib/tools/NpmAddPackageTool';
import { NpmRemovePackageTool } from '@/lib/tools/NpmRemovePackageTool';
import { GitCommitTool } from '@/lib/tools/GitCommitTool';
import { BuildProjectTool } from '@/lib/tools/BuildProjectTool';
import { TypecheckProjectTool } from '@/lib/tools/TypecheckProjectTool';
import { NostrReadNipTool } from '@/lib/tools/NostrReadNipTool';
import { NostrFetchEventTool } from '@/lib/tools/NostrFetchEventTool';
import { NostrReadKindTool } from '@/lib/tools/NostrReadKindTool';
@@ -214,7 +213,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
npm_add_package: new NpmAddPackageTool(fs, cwd),
npm_remove_package: new NpmRemovePackageTool(fs, cwd),
build_project: new BuildProjectTool(fs, cwd, esmUrlRef.current),
typecheck: new TypecheckProjectTool(fs, cwd),
nostr_read_nip: new NostrReadNipTool(),
nostr_fetch_event: new NostrFetchEventTool(),
nostr_read_kind: new NostrReadKindTool(),
-9
View File
@@ -29,7 +29,6 @@ import {
Search,
Clipboard,
AppWindow,
FileCheck,
} from 'lucide-react';
import { cn } from '@/lib/utils';
import { VFSImage } from '@/components/VFSImage';
@@ -241,14 +240,6 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
errorTitle: 'Failed to build project',
};
case 'typecheck':
return {
icon: FileCheck,
title: 'Typechecked project',
callingTitle: 'Typechecking project',
errorTitle: 'Found type errors',
};
case 'nostr_read_nip':
return {
icon: BookOpen,
+11 -1
View File
@@ -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
View File
@@ -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
+11 -1
View File
@@ -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",
},
];
+115
View File
@@ -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);
});
});
+258
View File
@@ -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,
);
}
+136
View File
@@ -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,
};
}
-56
View File
@@ -1,56 +0,0 @@
import type { Tool, ToolResult } from "./Tool";
import type { JSRuntimeFS } from "../JSRuntime";
import { typecheckProject, type TypecheckDiagnostic } from "../typecheck";
const MAX_REPORTED_ERRORS = 50;
function formatDiagnostic(diagnostic: TypecheckDiagnostic): string {
const location = diagnostic.file
? `${diagnostic.file}(${diagnostic.line},${diagnostic.column}): `
: "";
return `${location}error TS${diagnostic.code}: ${diagnostic.message}`;
}
export class TypecheckProjectTool implements Tool<void> {
private fs: JSRuntimeFS;
private cwd: string;
readonly description = "Typecheck the project with the TypeScript compiler, similar to running `tsc --noEmit`. Reports type errors across the codebase without emitting any files. Use this tool to verify that your changes are type-safe.";
constructor(fs: JSRuntimeFS, cwd: string) {
this.fs = fs;
this.cwd = cwd;
}
async execute(): Promise<ToolResult> {
const result = await typecheckProject({
fs: this.fs,
projectPath: this.cwd,
});
const notes: string[] = [];
if (result.missingTypes.length > 0) {
notes.push(`⚠️ Type declarations could not be found for: ${result.missingTypes.join(", ")}. Imports from these packages were treated as untyped and not checked.`);
}
if (result.errors.length === 0) {
return {
content: [
`✅ No type errors found. Checked ${result.checkedFileCount} files.`,
...notes,
].join("\n\n"),
};
}
const lines = result.errors.slice(0, MAX_REPORTED_ERRORS).map(formatDiagnostic);
if (result.errors.length > MAX_REPORTED_ERRORS) {
lines.push(`... and ${result.errors.length - MAX_REPORTED_ERRORS} more errors`);
}
throw new Error([
`❌ Found ${result.errors.length} type error${result.errors.length === 1 ? "" : "s"}:`,
lines.join("\n"),
...notes,
].join("\n\n"));
}
}
-653
View File
@@ -1,653 +0,0 @@
import * as JSONC from "jsonc-parser";
import { setupTypeAcquisition } from "@typescript/ata";
import type tsNamespace from "typescript";
import type { JSRuntimeFS } from "@/lib/JSRuntime";
type TS = typeof tsNamespace;
export interface TypecheckProjectOptions {
fs: JSRuntimeFS;
projectPath: string;
}
export interface TypecheckDiagnostic {
/** Path relative to the project root, or undefined for global diagnostics */
file?: string;
/** 1-based line number */
line?: number;
/** 1-based column number */
column?: number;
code: number;
message: string;
}
export interface TypecheckResult {
errors: TypecheckDiagnostic[];
checkedFileCount: number;
/** npm packages whose type declarations could not be acquired; imports from them were not checked */
missingTypes: string[];
}
/** Virtual directory where TypeScript's bundled lib.*.d.ts files are mounted */
const LIB_DIR = "/__typescript_libs__";
/** Virtual file providing Vite-style ambient declarations for asset imports */
const SHIM_PATH = `${LIB_DIR}/__vite_shim__.d.ts`;
const EXCLUDED_DIRS = new Set(["node_modules", "dist", "coverage"]);
const SOURCE_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts"];
const JS_EXTENSIONS = [".js", ".jsx", ".mjs", ".cjs"];
/** Diagnostic codes produced when a module's declarations cannot be found */
const MISSING_MODULE_CODES = new Set([
2307, // Cannot find module 'X' or its corresponding type declarations.
2688, // Cannot find type definition file for 'X'.
7016, // Could not find a declaration file for module 'X'.
]);
/**
* Ambient declarations for Vite-specific imports (assets, CSS, import.meta.env).
* Only used when the project's `vite` types could not be acquired; mirrors a
* subset of `vite/client`. Lives in a .d.ts file, so `skipLibCheck` suppresses
* any conflicts if the real vite/client types are also present.
*/
const VITE_SHIM = `
declare module "*.module.css" { const classes: { readonly [key: string]: string }; export default classes; }
declare module "*.css" { const css: string; export default css; }
declare module "*.scss" { const css: string; export default css; }
declare module "*.sass" { const css: string; export default css; }
declare module "*.less" { const css: string; export default css; }
declare module "*.svg" { const src: string; export default src; }
declare module "*.png" { const src: string; export default src; }
declare module "*.jpg" { const src: string; export default src; }
declare module "*.jpeg" { const src: string; export default src; }
declare module "*.gif" { const src: string; export default src; }
declare module "*.webp" { const src: string; export default src; }
declare module "*.avif" { const src: string; export default src; }
declare module "*.ico" { const src: string; export default src; }
declare module "*.bmp" { const src: string; export default src; }
declare module "*.mp3" { const src: string; export default src; }
declare module "*.wav" { const src: string; export default src; }
declare module "*.ogg" { const src: string; export default src; }
declare module "*.flac" { const src: string; export default src; }
declare module "*.aac" { const src: string; export default src; }
declare module "*.mp4" { const src: string; export default src; }
declare module "*.webm" { const src: string; export default src; }
declare module "*.woff" { const src: string; export default src; }
declare module "*.woff2" { const src: string; export default src; }
declare module "*.ttf" { const src: string; export default src; }
declare module "*.otf" { const src: string; export default src; }
declare module "*.eot" { const src: string; export default src; }
declare module "*.wasm" { const src: string; export default src; }
declare module "*.pdf" { const src: string; export default src; }
declare module "*.txt" { const src: string; export default src; }
declare module "*?raw" { const content: string; export default content; }
declare module "*?url" { const url: string; export default url; }
declare module "*?inline" { const content: string; export default content; }
declare module "*?worker" {
const workerConstructor: { new (options?: { name?: string }): Worker };
export default workerConstructor;
}
interface ImportMeta {
readonly env: Record<string, any>;
readonly hot?: Record<string, any>;
glob(pattern: string | string[], options?: Record<string, unknown>): Record<string, any>;
}
`;
interface RawTsConfig {
extends?: string;
compilerOptions?: Record<string, unknown>;
include?: string[];
exclude?: string[];
files?: string[];
references?: { path: string }[];
}
interface ProjectPackageJson {
dependencies?: Record<string, string>;
devDependencies?: Record<string, string>;
peerDependencies?: Record<string, string>;
}
interface ProjectPackageLock {
packages?: Record<string, { version?: string } | undefined>;
}
/**
* Run async tasks with a maximum number in flight at once. The browser fails
* requests with ERR_INSUFFICIENT_RESOURCES if too many start simultaneously.
*/
function createLimiter(limit: number): <T>(task: () => Promise<T>) => Promise<T> {
let active = 0;
const queue: (() => void)[] = [];
const next = () => {
active--;
queue.shift()?.();
};
return async (task) => {
if (active >= limit) {
await new Promise<void>((resolve) => queue.push(resolve));
}
active++;
try {
return await task();
} finally {
next();
}
};
}
/** Concurrency cap for all network activity performed during a typecheck */
const limit = createLimiter(16);
/** fetch wrapper passed to ATA so dependency downloads don't flood the browser */
const limitedFetch: typeof fetch = (input, init) => limit(() => fetch(input, init));
/**
* Lazy loaders for TypeScript's bundled default library files. Each file
* becomes its own chunk, loaded on first typecheck and cached afterwards.
*/
const libFileLoaders = import.meta.glob<string>(
"/node_modules/typescript/lib/lib*.d.ts",
{ query: "?raw", import: "default" },
);
let libFilesPromise: Promise<Map<string, string>> | undefined;
function loadLibFiles(): Promise<Map<string, string>> {
libFilesPromise ??= (async () => {
const entries = await Promise.all(
Object.entries(libFileLoaders).map(async ([path, load]) => {
const name = path.slice(path.lastIndexOf("/") + 1);
return [`${LIB_DIR}/${name}`, await limit(load)] as const;
}),
);
return new Map(entries);
})();
return libFilesPromise;
}
/** Cache of acquired type declarations, keyed by the synthetic ATA entry source */
const typeAcquisitionCache = new Map<string, Promise<Map<string, string>>>();
const silentLogger = {
log: () => {},
error: () => {},
groupCollapsed: () => {},
groupEnd: () => {},
};
/**
* Download type declarations for the project's npm dependencies from jsdelivr
* using TypeScript's Automatic Type Acquisition. Returns a map of
* `/node_modules/...` paths to file contents.
*/
function acquireTypes(ts: TS, entrySource: string): Promise<Map<string, string>> {
const cached = typeAcquisitionCache.get(entrySource);
if (cached) return cached;
const promise = (async () => {
const files = new Map<string, string>();
const ata = setupTypeAcquisition({
projectName: "shakespeare",
typescript: ts,
logger: silentLogger,
fetcher: limitedFetch,
delegate: {
// First write wins: version-pinned packages are requested up front, so
// they must not be overwritten by transitively-discovered "latest" types
receivedFile: (code, path) => {
if (!files.has(path)) files.set(path, code);
},
errorMessage: () => {},
},
});
await ata(entrySource);
return files;
})();
// Don't cache failures (e.g. network errors) so a retry can succeed
promise.catch(() => typeAcquisitionCache.delete(entrySource));
typeAcquisitionCache.set(entrySource, promise);
return promise;
}
/** Resolve "." and ".." segments and collapse duplicate slashes */
function normalizePath(path: string): string {
const isAbsolute = path.startsWith("/");
const out: string[] = [];
for (const part of path.split("/")) {
if (part === "" || part === ".") continue;
if (part === "..") {
out.pop();
continue;
}
out.push(part);
}
return (isAbsolute ? "/" : "") + out.join("/");
}
function extensionOf(name: string): string {
const dot = name.lastIndexOf(".");
return dot === -1 ? "" : name.slice(dot).toLowerCase();
}
/** Extract the npm package name from a bare module specifier */
function packageNameFromSpecifier(specifier: string): string {
const parts = specifier.split("/");
return specifier.startsWith("@") ? parts.slice(0, 2).join("/") : parts[0];
}
/** Prefixes from tsconfig `paths` (e.g. "@/") used to distinguish aliases from npm packages */
function aliasPrefixesFrom(options: tsNamespace.CompilerOptions): string[] {
return Object.keys(options.paths ?? {}).map((key) => key.replace(/\*.*$/, ""));
}
function isBareSpecifier(specifier: string, aliasPrefixes: string[]): boolean {
if (specifier.startsWith(".") || specifier.startsWith("/")) return false;
if (specifier.includes(":")) return false; // node:, https:, virtual:, etc.
return !aliasPrefixes.some((prefix) => prefix !== "" && specifier.startsWith(prefix));
}
/** DefinitelyTyped package name for an npm package (e.g. "@foo/bar" -> "@types/foo__bar") */
function dtPackageName(name: string): string {
return `@types/${name.startsWith("@") ? name.slice(1).replace("/", "__") : name}`;
}
function declaredRange(packageJson: ProjectPackageJson, name: string): string | undefined {
return (
packageJson.dependencies?.[name] ??
packageJson.devDependencies?.[name] ??
packageJson.peerDependencies?.[name]
);
}
/**
* Best version to request from jsdelivr for a package: the exact locked
* version if available, otherwise the package.json range with any leading
* operator stripped. ATA only supports exact versions or single-segment
* ranges like "18", so ranges such as "^18.3.1" must be reduced.
*/
function pinnedVersion(
packageJson: ProjectPackageJson,
packageLock: ProjectPackageLock,
name: string,
): string | undefined {
const locked = packageLock.packages?.[`node_modules/${name}`]?.version;
if (locked) return locked;
const range = declaredRange(packageJson, name);
if (!range) return undefined;
const stripped = range.replace(/^[\s~^>=<v]+/, "");
return /^\d/.test(stripped) ? stripped : undefined;
}
/**
* Build a synthetic TypeScript source file that imports every npm package the
* project references, pinned via ATA's `// types: <version>` comment
* convention. When the project declares a matching `@types/*` package, that
* package is requested directly at its pinned version, because ATA's own
* DefinitelyTyped fallback always downloads the latest version.
*/
function buildAtaEntrySource(
ts: TS,
sourceTexts: string[],
packageJson: ProjectPackageJson,
packageLock: ProjectPackageLock,
aliasPrefixes: string[],
): string {
const packages = new Map<string, string | undefined>();
const add = (name: string) => {
if (packages.has(name)) return;
packages.set(name, pinnedVersion(packageJson, packageLock, name));
};
for (const text of sourceTexts) {
const meta = ts.preProcessFile(text, true, true);
const refs = [...meta.importedFiles, ...meta.typeReferenceDirectives];
for (const ref of refs) {
if (!isBareSpecifier(ref.fileName, aliasPrefixes)) continue;
const name = packageNameFromSpecifier(ref.fileName);
if (!name) continue;
const dtName = dtPackageName(name);
if (!name.startsWith("@types/") && declaredRange(packageJson, dtName)) {
add(dtName);
} else {
add(name);
}
}
}
return [...packages.entries()]
.sort(([a], [b]) => a.localeCompare(b))
.map(([name, version]) => (version ? `import "${name}" // types: ${version}` : `import "${name}"`))
.join("\n");
}
/** Read a tsconfig file, following local `extends` chains */
async function readRawConfig(fs: JSRuntimeFS, path: string, depth = 0): Promise<RawTsConfig | undefined> {
if (depth > 5) return undefined;
let text: string;
try {
text = await fs.readFile(path, "utf8");
} catch {
return undefined;
}
const config = (JSONC.parse(text) ?? {}) as RawTsConfig;
if (typeof config.extends === "string" && config.extends.startsWith(".")) {
const dir = path.slice(0, path.lastIndexOf("/"));
const extendsPath = config.extends.endsWith(".json") ? config.extends : `${config.extends}.json`;
const parent = await readRawConfig(fs, normalizePath(`${dir}/${extendsPath}`), depth + 1);
if (parent) {
return {
...parent,
...config,
compilerOptions: { ...parent.compilerOptions, ...config.compilerOptions },
};
}
}
return config;
}
/**
* Resolve the effective tsconfig for the project. Handles Vite-style project
* references (tsconfig.json + tsconfig.app.json) by preferring the app config.
*/
async function resolveConfig(fs: JSRuntimeFS, projectPath: string): Promise<RawTsConfig> {
const root = await readRawConfig(fs, `${projectPath}/tsconfig.json`);
if (!root) return {};
const hasOwnScope = Boolean(root.include?.length || root.files?.length);
if (hasOwnScope || !root.references?.length) return root;
const candidates = [
"tsconfig.app.json",
...root.references.map((ref) => (ref.path.endsWith(".json") ? ref.path : `${ref.path}/tsconfig.json`)),
];
for (const candidate of candidates) {
const config = await readRawConfig(fs, normalizePath(`${projectPath}/${candidate}`));
if (config && (config.include?.length || config.files?.length)) return config;
}
return root;
}
/** Recursively read all source-relevant project files into memory */
async function readProjectFiles(fs: JSRuntimeFS, projectPath: string): Promise<Map<string, string>> {
const files = new Map<string, string>();
const relevantExtensions = new Set([...SOURCE_EXTENSIONS, ...JS_EXTENSIONS, ".json"]);
async function walk(dir: string): Promise<void> {
let entries;
try {
entries = await fs.readdir(dir, { withFileTypes: true });
} catch {
return;
}
await Promise.all(
entries.map(async (entry) => {
const path = `${dir}/${entry.name}`;
if (entry.isDirectory()) {
if (EXCLUDED_DIRS.has(entry.name) || entry.name.startsWith(".")) return;
await walk(path);
} else if (relevantExtensions.has(extensionOf(entry.name))) {
try {
files.set(path, await fs.readFile(path, "utf8"));
} catch {
// Skip unreadable files
}
}
}),
);
}
await walk(projectPath);
return files;
}
/** Convert tsconfig include/exclude patterns to simple directory/file prefixes */
function patternPrefixes(patterns: string[] | undefined): string[] | undefined {
if (!patterns?.length) return undefined;
return patterns.map((pattern) => {
let prefix = pattern.replace(/^\.\//, "");
const globIndex = prefix.search(/[*?[{]/);
if (globIndex !== -1) {
prefix = prefix.slice(0, globIndex);
prefix = prefix.slice(0, prefix.lastIndexOf("/") + 1);
}
return prefix.replace(/\/+$/, "");
});
}
function matchesPrefix(relativePath: string, prefixes: string[]): boolean {
return prefixes.some(
(prefix) => prefix === "" || relativePath === prefix || relativePath.startsWith(`${prefix}/`),
);
}
/** Select the program root files based on the tsconfig include/exclude/files settings */
function selectRootFiles(
projectFiles: Map<string, string>,
projectPath: string,
config: RawTsConfig,
options: tsNamespace.CompilerOptions,
): string[] {
const include = patternPrefixes(config.include);
const exclude = patternPrefixes(config.exclude);
const checkedExtensions = new Set(options.allowJs ? [...SOURCE_EXTENSIONS, ...JS_EXTENSIONS] : SOURCE_EXTENSIONS);
const rootFiles = new Set<string>();
for (const path of projectFiles.keys()) {
if (!checkedExtensions.has(extensionOf(path))) continue;
const relativePath = path.slice(projectPath.length + 1);
if (include && !matchesPrefix(relativePath, include)) continue;
if (exclude && matchesPrefix(relativePath, exclude)) continue;
rootFiles.add(path);
}
for (const file of config.files ?? []) {
const path = normalizePath(`${projectPath}/${file}`);
if (projectFiles.has(path)) rootFiles.add(path);
}
return [...rootFiles].sort();
}
function createCompilerHost(
ts: TS,
files: Map<string, string>,
projectPath: string,
): tsNamespace.CompilerHost {
const directories = new Set<string>(["/"]);
for (const path of files.keys()) {
let dir = path.slice(0, path.lastIndexOf("/"));
while (dir && !directories.has(dir)) {
directories.add(dir);
dir = dir.slice(0, dir.lastIndexOf("/"));
}
}
const sourceFileCache = new Map<string, tsNamespace.SourceFile>();
return {
fileExists: (path) => files.has(normalizePath(path)),
readFile: (path) => files.get(normalizePath(path)),
directoryExists: (path) => directories.has(normalizePath(path)),
getDirectories: (path) => {
const prefix = normalizePath(path);
const base = prefix === "/" ? "/" : `${prefix}/`;
const result = new Set<string>();
for (const dir of directories) {
if (dir.startsWith(base) && dir !== prefix) {
const first = dir.slice(base.length).split("/")[0];
if (first) result.add(first);
}
}
return [...result];
},
getSourceFile: (fileName, languageVersionOrOptions) => {
const path = normalizePath(fileName);
const cached = sourceFileCache.get(path);
if (cached) return cached;
const text = files.get(path);
if (text === undefined) return undefined;
const sourceFile = ts.createSourceFile(path, text, languageVersionOrOptions, true);
sourceFileCache.set(path, sourceFile);
return sourceFile;
},
getDefaultLibLocation: () => LIB_DIR,
getDefaultLibFileName: (options) => `${LIB_DIR}/${ts.getDefaultLibFileName(options)}`,
writeFile: () => {},
getCurrentDirectory: () => projectPath,
getCanonicalFileName: (fileName) => fileName,
useCaseSensitiveFileNames: () => true,
getNewLine: () => "\n",
};
}
/**
* Typecheck a project in the virtual filesystem with the TypeScript compiler,
* equivalent to running `tsc --noEmit`. Type declarations for npm dependencies
* are downloaded from jsdelivr (the VFS has no node_modules) and cached for
* the session.
*/
export async function typecheckProject({ fs, projectPath }: TypecheckProjectOptions): Promise<TypecheckResult> {
const tsModule = await import("typescript");
const ts = (tsModule.default ?? tsModule) as TS;
const [libFiles, projectFiles, config] = await Promise.all([
loadLibFiles(),
readProjectFiles(fs, projectPath),
resolveConfig(fs, projectPath),
]);
const converted = ts.convertCompilerOptionsFromJson(
config.compilerOptions ?? {},
projectPath,
`${projectPath}/tsconfig.json`,
);
const options: tsNamespace.CompilerOptions = {
// Defaults for browser projects without a tsconfig; overridden by the project's config
target: ts.ScriptTarget.ES2020,
module: ts.ModuleKind.ESNext,
moduleResolution: ts.ModuleResolutionKind.Bundler,
jsx: ts.JsxEmit.ReactJSX,
esModuleInterop: true,
resolveJsonModule: true,
...converted.options,
// Forced: check only, never emit; declarations acquired from the CDN are not authoritative
noEmit: true,
skipLibCheck: true,
incremental: false,
composite: false,
declaration: false,
emitDeclarationOnly: false,
tsBuildInfoFile: undefined,
};
const rootFiles = selectRootFiles(projectFiles, projectPath, config, options);
const aliasPrefixes = aliasPrefixesFrom(options);
// Acquire type declarations for npm dependencies referenced by the project
let packageJson: ProjectPackageJson = {};
let packageLock: ProjectPackageLock = {};
try {
packageJson = JSON.parse(projectFiles.get(`${projectPath}/package.json`) ?? "{}");
} catch {
// Malformed package.json; acquire latest types instead of pinned versions
}
try {
packageLock = JSON.parse(projectFiles.get(`${projectPath}/package-lock.json`) ?? "{}");
} catch {
// Malformed lockfile; fall back to package.json ranges
}
const rootTexts = rootFiles.map((path) => projectFiles.get(path) ?? "");
const entrySource = buildAtaEntrySource(ts, rootTexts, packageJson, packageLock, aliasPrefixes);
let acquiredTypes = new Map<string, string>();
if (entrySource) {
try {
acquiredTypes = await acquireTypes(ts, entrySource);
} catch {
// Offline or CDN failure: check what we can without external types
}
}
// Assemble the virtual filesystem for the compiler
const files = new Map<string, string>(libFiles);
for (const [path, text] of acquiredTypes) {
files.set(normalizePath(`${projectPath}${path}`), text);
}
for (const [path, text] of projectFiles) {
files.set(path, text);
}
// Provide Vite ambient types (asset imports, import.meta.env) if the real
// vite/client declarations were not acquired
const rootNames = [...rootFiles];
if (!files.has(`${projectPath}/node_modules/vite/client.d.ts`)) {
files.set(SHIM_PATH, VITE_SHIM);
rootNames.push(SHIM_PATH);
}
const host = createCompilerHost(ts, files, projectPath);
const program = ts.createProgram({ rootNames, options, host });
const diagnostics = [...converted.errors, ...ts.getPreEmitDiagnostics(program)];
const errors: TypecheckDiagnostic[] = [];
const missingTypes = new Set<string>();
for (const diagnostic of diagnostics) {
if (diagnostic.category !== ts.DiagnosticCategory.Error) continue;
const fileName = diagnostic.file?.fileName;
if (fileName && (fileName.includes("/node_modules/") || fileName.startsWith(LIB_DIR))) continue;
const message = ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n");
// Missing declarations for npm packages are reported separately, not as
// errors: the CDN may simply not have types for that package
if (MISSING_MODULE_CODES.has(diagnostic.code)) {
const specifier = message.match(/'([^']+)'/)?.[1];
if (specifier && isBareSpecifier(specifier, aliasPrefixes)) {
missingTypes.add(packageNameFromSpecifier(specifier));
continue;
}
}
const error: TypecheckDiagnostic = { code: diagnostic.code, message };
if (diagnostic.file && diagnostic.start !== undefined) {
const { line, character } = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
error.file = diagnostic.file.fileName.startsWith(`${projectPath}/`)
? diagnostic.file.fileName.slice(projectPath.length + 1)
: diagnostic.file.fileName;
error.line = line + 1;
error.column = character + 1;
}
errors.push(error);
}
return {
errors,
checkedFileCount: rootFiles.length,
missingTypes: [...missingTypes].sort(),
};
}
+3 -2
View File
@@ -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;
+75
View File
@@ -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', () => ({}));