242 Commits
Author SHA1 Message Date
Alex Gleason 9d43fdbcc3 Use window.nostr.connect, getSigner and disconnect where the extension offers them
Din's and Tenna's NIP-07 providers add three optional methods, after NIP-46's
names. Logging in through an extension now asks connect() for an account
(skipping the Welcome back preview, since the extension shows the account),
each extension login signs through getSigner(pubkey) so switching accounts
in the extension doesn't change who the app signs as, and logging out calls
disconnect(pubkey). Each is feature-detected on its own; extensions without
them work as before. The onchain-bitcoin skill's NBrowserSignerBtc now
builds on the same signer.
2026-11-28 16:50:29 -06:00
Alex Gleason 67eb5f2a1c Rewrite the README for the template as it is now
Drop the Stacks/Dork CLI, the nonexistent npm run deploy, the expired
Vercel demo links and the outdated stack versions. Document the scripts,
why a fresh copy fails npm test, the agent skills and deployment.
2026-11-28 16:44:52 -06:00
Alex Gleason 4cea0394d8 Trim .gitignore to what this project produces 2026-11-28 16:40:49 -06:00
Alex Gleason cd80e588cc Remove host- and editor-specific files
Drop the Netlify _redirects file, the GitLab CI and GitHub Pages deploy
configs, and the .vscode settings. Generated apps pick their own host and
editor.
2026-11-28 16:40:49 -06:00
Alex Gleason a09d1aba1b Remove dead config
React Router 7 has no future-flag warnings to filter, and npm run build
already writes 404.html.
2026-11-28 16:32:28 -06:00
Alex Gleason 51222e00d1 Remove "use client" directives
They are a React Server Components marker for Next.js and do nothing in a
Vite app.
2026-11-28 16:32:16 -06:00
Alex Gleason e9bec18edf Drop redundant @radix-ui/react-toast and unhead dependencies
Toast comes from the unified radix-ui package like every other primitive,
and unhead is a dependency of @unhead/react, which is all the app imports.
2026-11-28 16:31:56 -06:00
Alex Gleason 75944a4711 Upgrade to DayPicker 10 (@daypicker/react) 2026-11-28 16:29:03 -06:00
Alex Gleason 033ec637c0 Upgrade html-eslint to 0.69 2026-11-28 16:28:25 -06:00
Alex Gleason b33271df67 Upgrade to Vitest 5, jest-dom 8 and jsdom 31 2026-11-28 16:28:16 -06:00
Alex Gleason 94d21d68de Update dependencies within semver ranges, fixing npm audit 2026-11-28 16:27:44 -06:00
Alex Gleason 97d116ff7b Skip client tag on localhost, *.localhost, and IP addresses 2026-09-27 11:42:45 -05:00
Alex Gleason c2556b9b2d npm audit fix 2026-09-18 21:29:32 -05:00
Alex Gleason f7f1acb6e1 Upgrade Nostrify 2026-09-03 11:45:43 -05:00
Alex Gleason f8cda28f7c Use import.meta.dirname in vite.config.ts
Silences the Vite warning about `__dirname` being unsupported by
`configLoader: 'native'`, which is planned to become the default.
2026-08-29 16:33:44 -05:00
Alex Gleason 5ee25d2e6a Upgrade Nostrify 2026-08-19 14:50:49 -05:00
Alex Gleason ef2e31ed04 Warn that deep links are attacker-triggerable navigations
Any web page can open a custom-scheme URL, and `DeepLinkHandler` turns
that into a `navigate()` call — so a route that acts on mount (publishing,
following, paying, deleting) is an action any website can fire silently,
with no user intent beyond a tap on an unrelated page. The `appUrlOpen`
event gives no way to tell a verified universal link from a custom scheme,
so the destination has to be treated as attacker-chosen.

Document the constraint where it will be read, rather than filtering to
`https:` in the component: this skill documents custom schemes as a
supported setup, and filtering would silently break them.
2026-08-19 10:44:10 -05:00
Alex Gleason 1f37bf4aa7 Reject implausible fee rates in the onchain-bitcoin skill
`getFeeRates` coerced the remote response with `Math.ceil(data['1'] || 1)`.
`||` only catches falsy values, so a missing key was safe but a truthy
non-number — `{"1": "5"}`, `{"1": {"fee": 5}}`, what an API-version
mismatch produces — yielded NaN.

NaN then passed every downstream guard, because they are all `<` / `>=`
comparisons and every comparison with NaN is false: no change output was
added, the balance check passed, nothing threw, and the UI showed
"Fee 0" because `!NaN` is true. The wallet built a valid, broadcastable
transaction paying its entire balance to miners.

Sanitize each rate to a finite number in [1, 5000], and make `estimateFee`
throw on a non-finite rate rather than propagate NaN into the builder.
2026-08-19 10:41:01 -05:00
Alex Gleason 47d2d02c44 Validate zap invoice amounts in the nwc skill
The LNURL-pay endpoint is chosen by the recipient, so a hostile author
decides what invoice their zappers are handed — including how much it
charges. Nothing in the old flow ever read the invoice: `useZaps` passed
the string straight to `sendPayment` or WebLN, so a user who approved
776 sats could be billed 5,000,000 with no indication anything was off.

Decode the BOLT11 and require it to charge exactly the approved amount
before any wallet is touched, and re-assert in `sendPayment` so no future
caller can bypass the check. Amountless invoices are rejected outright.

Resolving the endpoint moves off `nip57.getZapEndpoint`, which discards
the `minSendable`/`maxSendable` bounds and the `metadata` string needed
to confirm the invoice was issued for this request; `lib/lnurlPay.ts`
keeps them and pins both the LNURL and its callback to HTTPS. Building
the callback query with `URLSearchParams` also fixes comments
containing `&`, `+` or `#` corrupting the request under `encodeURI`.
2026-08-19 10:40:53 -05:00
Alex Gleason e1d6a5f687 Upgrade Nostrify 2026-08-19 09:54:05 -05:00
Alex Gleason 2c21ed2daa Update dependencies to patch npm audit vulnerabilities
npm audit reported 9 vulnerabilities (6 high, 2 moderate, 1 low),
including a react-router open redirect and DoS, a vite server.fs.deny
bypass, path traversal in postcss sourcemap loading, and a batch of
undici request/cache handling issues.

All fixes fell within existing semver ranges, so package.json is
untouched and only the lockfile moves: react-router 7.18.2, vite 8.2.1,
postcss 8.5.26, nanoid 3.3.18, undici 7.29.0, valibot 1.4.2,
@babel/core 7.29.7, brace-expansion 5.0.9.

npm audit now reports 0 vulnerabilities.
2026-08-08 13:01:39 -05:00
Alex Gleason aa8614630f Merge branch 'replace-damus-relay' into 'main'
Replace relay.damus.io with nos.lol in default relays

Closes #22

See merge request soapbox-pub/mkstack!31
2026-07-28 14:53:21 +00:00
Derek Ross b5da5127da Replace damus relay examples in skill docs
relay.damus.io is shutting down; the nostr-relay-pools and
relay-management skills still used it as an illustrative URL, which
would teach a dead relay to anything generating code from them.

Use relay.ditto.pub instead. The relay group example already listed
nos.lol, so ditto avoids duplicating an entry there.
2026-07-28 10:19:06 -04:00
Derek Ross ac7a6d9435 Replace relay.damus.io with nos.lol in default relays
relay.damus.io is shutting down at the end of July 2026. It ships in
APP_RELAYS, so every app bootstrapped from MKStack would include a dead
relay out of the box. Swap in nos.lol, keeping read: false / write: true
so the outbox strategy is unchanged.

Also refresh the AGENTS.md copy of the default relay list, which had
drifted from src/lib/appRelays.ts and still named damus.

Closes #22
2026-07-28 10:09:52 -04:00
Alex Gleason 9776c727bb Dedicate MKStack to the public domain in README
Fixes https://gitlab.com/soapbox-pub/mkstack/-/work_items/21
2026-07-11 14:10:29 -05:00
Alex Gleason 05202229a5 Validate gift-wrap event id even when skipping Schnorr verify
Returning true unconditionally for wrap kinds also skipped the event id
(content hash) check. The id is what we index and dedupe on, so it must
still match the event's contents. Recompute the hash and compare it while
continuing to skip only the redundant outer signature verification.
2026-07-09 15:17:57 -05:00
Alex Gleason 17be8730f5 Skip redundant Schnorr verify on gift-wrap ingest
The outer signature on a NIP-59 gift-wrap (1059/21059) is cryptographically
meaningless to the client: wraps are signed by a single-use ephemeral key
(direct invites) or, in Concord V2, by a group-shared derived stream key any
member can sign with, so the outer sig establishes no sender identity.
Authenticity comes from NIP-44 authenticated encryption plus the inner seal
signature check and rumor-pubkey/id bindings in the decrypt path.

Pass a kind-scoped verifyEvent to NRelay1 that skips the Schnorr verify for
wrap kinds only while keeping full verification for every other kind, whose
identity does rest on its outer signature.
2026-07-09 12:29:44 -05:00
Alex Gleason 49fbba6f98 Show all accounts in switcher; current user links to profile 2026-06-25 12:22:24 +03:00
Alex Gleason b50dbdb2dc Add NIP-07 quick login and redesign login dialog 2026-06-23 22:06:10 +03:00
Alex Gleason 9a9616be29 Add damus and primal as write-only relays 2026-06-19 10:23:27 +03:00
Alex Gleason c4b2c1ddbe Swap out Damus relay for Dreamith relay 2026-06-12 10:38:58 -05:00
Alex Gleason fd9068f598 Fix react-router DoS vulnerability via npm audit fix 2026-06-05 09:46:01 -05:00
Alex Gleason 772479e232 Update AI context for Tailwind v4 and React 19
- AGENTS.md: describe ui components as React 19 ref-as-prop function
  components using data-slot and the unified radix-ui package
- theming skill: register fonts and color tokens via @theme in
  src/index.css (no tailwind.config.ts); fix color values to use the
  hsl() wrapper that matches the real index.css
- ai-chat skill: import VisuallyHidden from the unified radix-ui package
- nwc skill: convert ZapDialog/WalletModal forwardRef to ref-as-prop
- edit-profile skill: drop React.FC in favor of plain function typing
2026-06-05 09:43:15 -05:00
Alex Gleason 459221305f Upgrade Nostrify 2026-06-01 20:38:34 +02:00
Alex Gleason 74c8445f4c Upgrade Nostrify 2026-05-31 02:55:30 +02:00
Alex Gleason a9a378b568 Make signup/login dialog language Nostr-specific
Match Agora's wording in the AuthDialog welcome step and generate
step title to be more explicit that accounts are Nostr accounts:

- 'Create new account' -> 'Create a new Nostr account'
- 'I already have an account' -> 'Log in to an existing account'
- 'Create account' (step title) -> 'Create a Nostr account'
2026-05-30 18:54:35 +02:00
Alex Gleason 2b7d6655af Remove remaining genUserName references from docs and skill templates 2026-05-30 18:44:53 +02:00
Alex Gleason 881629a746 Remove genUserName, use Anonymous fallback directly 2026-05-30 02:06:38 +02:00
Alex Gleason 4878f9414c Switch to the newly added account when logging in
addLogin appends to the end of the logins array, but the current user
is logins[0]. So when an already-logged-in user opened "Add another
account" and chose any login method, the new account silently landed
at the back of the queue while the prior account remained current.

Most damaging on the signup path: login.nsec(nsec) was called before
the profile step, then publishEvent({ kind: 0, ... }) signed kind 0
metadata with the *previous* user's signer — overwriting their profile.

- useLoginActions: wrap each addLogin in addAndActivate, which also
  calls setLogin(login.id) to promote the new login to logins[0].
- AuthDialog.finishSignup: defensive guard that verifies the active
  signer matches the just-generated nsec before publishing kind 0;
  refuse and toast otherwise. Belt and suspenders against any future
  regression in the switch logic.
- Add a targeted regression test for the auto-switch behavior.
2026-05-24 17:50:59 -05:00
Alex Gleason 3f69f84d19 Skeletonize account UI while metadata is loading
While the kind-0 metadata query for logged-in accounts is in flight, we
were rendering the genUserName-derived animal name (and its first
letter as the avatar fallback) before falling back to the real display
name once the profile arrived. That made the AccountSwitcher trigger
flash a meaningless 'Brave Otter' / 'B' before settling on the real
identity.

Expose isLoading from useLoggedInAccounts and, while it is still true
and we have no metadata.name yet, render Skeletons in place of:
  - the avatar fallback letter (in the AccountSwitcher trigger and the
    other-accounts dropdown rows),
  - the displayed name in the dropdown rows.

Once the query settles, behavior is unchanged: a real name renders if
present, otherwise the genUserName fallback fills in.
2026-05-11 18:16:59 -05:00
Alex Gleason 2357913037 Add onchain-bitcoin skill 2026-05-11 10:09:05 -07:00
Alex Gleason 46119367c8 Use APP_RELAYS as nostrconnect fallback
When the user has no NIP-65 write relays configured, getRelayUrls() was
building the nostrconnect:// URI with a single relay (wss://relay.ditto.pub).
Fall back to the full APP_RELAYS write list instead so the remote signer
has more connection options during the handshake.

Extract the default relay list into src/lib/appRelays.ts as a single
source of truth, shared between App.tsx (defaultConfig) and
useLoginActions.ts (nostrconnect fallback).
2026-05-06 14:08:59 -05:00
Alex Gleason f9673379d7 Speed up npm run test with eslint/tsc caching
Ignore .agents skill bundles from eslint (template files not part of
the build), enable eslint --cache and tsc --incremental so warm re-runs
skip unchanged files.
2026-05-05 19:00:54 -05:00
Alex Gleason e289c67a70 Show live progress during the nostrconnect login handshake
When a user tapped "Open signer app", the dialog previously stayed
frozen on the same screen — same button, same copy-URI fallback, no
feedback — until the login either succeeded (and the dialog dismissed)
or timed out after two minutes. With slow or flaky signers (Amber's
current listening-REQ bug being the immediate trigger, but any NIP-46
signer that takes more than a second or two to respond hits the same
hole) this looked indistinguishable from a hang. Users retapped the
button, closed the dialog, gave up.

Now the dialog swaps the QR / Open signer app area for a centered
spinner with a live status line as the handshake advances:

- "Waiting for signer connection…" while the signer app has the user
  and we're listening on kind 24133 for the connect-ack.
- "Getting public key…" once the connect-ack arrives and we're
  issuing the NIP-46 get_public_key RPC.

On mobile the swap happens synchronously when the user taps "Open
signer app" so they see the progress state the moment they return
from the signer. On desktop the QR stays visible through the
awaiting-connect phase (they may still be scanning with a different
device) and only swaps in once the signer has acknowledged.

The progress view includes a Cancel link that aborts the in-flight
subscription and regenerates fresh connect params.

Also fix a related effect-lifecycle bug: the listening effect
previously depended on `onClose` and `isWaitingForConnect`. Since
parents pass inline arrow functions for onClose, the effect re-ran
on every parent render and its cleanup flipped a local `cancelled`
flag — if the signer's response arrived on a re-rendered instance,
the success branch silently swallowed the login. The effect now
depends only on `nostrConnectParams` with stable refs for
onClose/login, gates the success branch on `controller.signal.aborted`
instead of a teardown flag, and handles cancellation explicitly in
the dialog-close and retry paths.

The handshake phases are surfaced via the new `onStatus` callback on
`NLogin.fromNostrConnect` in @nostrify/react 0.6.0. Bumps
@nostrify/react to ^0.6.0.

Also switches the fallback relay used for NIP-46 communication from
wss://relay.damus.io to wss://relay.ditto.pub. Only applies when the
user has no writable relays in their metadata.

Incidental cleanup while editing the dialog: the Copy URI button and
the "Open your signer app to connect." / "Scan with your signer app."
caption lines are removed. The primary Open signer app button is
self-explanatory on mobile, and the QR on desktop doesn't need a
caption.
2026-05-04 21:51:06 -05:00
Alex Gleason 551928849a AGENTS tweak 2026-05-04 09:15:29 -05:00
Alex Gleason 4e910ed1f0 Add Blossom server list to app config (kind 10063)
Blossom servers now live in AppConfig alongside the NIP-65 relay list:
- blossomServerMetadata (BUD-03 server list) and useAppBlossomServers flag
- src/lib/appBlossom.ts provides APP_BLOSSOM_SERVERS defaults
  (blossom.ditto.pub, blossom.dreamith.to, blossom.primal.net),
  parseBlossomServerList, and getEffectiveBlossomServers
- NostrSync hydrates the user's kind 10063 event on login
- useUploadFile reads effective servers from config
2026-05-04 09:09:51 -05:00
Alex Gleason 4e8aedde9c Update AGENTS.md to reflect TailwindCSS 4.x upgrade 2026-04-26 23:14:21 -05:00
Alex Gleason 009265b017 Add lockdown-mode skill 2026-04-26 22:52:50 -05:00
Alex Gleason 9e230f45d3 Upgrade all dependencies to latest versions
Bumps every dependency to its current latest, including several majors
(react-router-dom 6→7, lucide-react 0.x→1.x, tailwind-merge 2→3,
typescript 5→6, jsdom 26→29, @unhead/react 2→3, @nostrify/react 0.4→0.5,
@types/node 22→24 to match the Node 24 runtime).

Drops the deprecated @unhead/addons package in favor of importing
InferSeoMetaPlugin directly from unhead/plugins.

package-lock.json regenerated from a clean node_modules to prune stale
transitive entries.
2026-04-26 22:41:37 -05:00
Alex Gleason 4efc3c7273 Modernize ESLint setup to v10 with defineConfig
Replaces the deprecated `tseslint.config(...)` helper with ESLint core's
`defineConfig()` (available since ESLint 9.22, recommended in 10.x) and
upgrades the lint stack to the latest majors:

  eslint                      9.39  -> 10.2
  @eslint/js                  10.0  -> 10.0
  typescript-eslint            8.0  -> 8.59
  eslint-plugin-react-hooks    5.1  -> 7.1
  eslint-plugin-react-refresh  0.4  -> 0.5
  @html-eslint/{eslint-plugin,parser}  0.41 -> 0.59
  globals                     15.9  -> 17.5

Config changes:
- Use `defineConfig` + `globalIgnores()` instead of `tseslint.config`.
- Adopt `reactHooks.configs.flat.recommended` (adds React Compiler rules:
  purity, refs, set-state-in-effect, etc.).
- Adopt `reactRefresh.configs.vite` (matches the Vite setup exactly).
- Adopt `@html-eslint` `flat/recommended` (adds indent, quotes,
  use-baseline, require-closing-tags, etc.).
- Disable `@html-eslint/use-baseline` for the `rel="manifest"` false
  positive.

Custom rule fixes for ESLint 10:
- `context.getSourceCode()` -> `context.sourceCode`
- `context.getFilename()`   -> `context.filename`

Code fixes for the stricter new presets:
- NostrProvider: lazy-init NPool via `useState(() => new NPool(...))` and
  move `ref.current = x` assignments into effects to satisfy the new
  `react-hooks/refs` rule.
- useIsMobile: drop the redundant setState-in-effect by initialising
  `useState` from the media query synchronously.
- AuthDialog: move `loginRef.current = login` into an effect.
- sidebar.tsx: derive skeleton width from `useId()` instead of
  `Math.random()` so the render is pure.
- index.html: reindent to 4 spaces to satisfy `@html-eslint/indent`.
- .agents/skills/**: add `{ cause: err }` to `throw new Error(...)` calls
  inside catch blocks (new `preserve-caught-error` rule) and a handful
  of targeted `eslint-disable` comments for legitimate external-system
  sync / state-reset-on-prop-change patterns.

The six intentional template failures (missing manifest, missing title /
description / OG tags, two FIXME comments) are unchanged -- they're the
template's way of nudging downstream users to fill the site in.

Re: "someday maybe tseslint won't be needed" -- still in the future.
ESLint 10 now loads `eslint.config.ts` natively (via jiti or Node's
`--experimental-strip-types`), but that only parses the config file. For
linting .ts/.tsx source you still need @typescript-eslint/parser and its
rules, which the `typescript-eslint` package bundles together. So the
"typescript" prefix is gone from rule names in practice, but the package
stays.
2026-04-26 22:33:39 -05:00
Alex Gleason 75598c45b1 Tighten capacitor skill (434 -> 184 lines)
The skill was the longest in the repo; most of the bulk was narrative
duplication of content that already ships in the JSDoc headers of the
files users copy in. Material changes:

- Drop the per-package bullet list (17 lines of 'what is @capacitor/*')
  in favor of a single-line pointer to Capacitor's own docs.
- Drop the 'Using the APIs' section (~110 lines of Haptics /
  Download / SecureStorage / useSecureLocalStorage walkthroughs). Each
  source file has thorough @example blocks in its JSDoc — the skill
  now shows a short import+call tour and directs readers to the file
  headers for the rest.
- Collapse the three 'Files Provided by This Skill' tables (source /
  project-root / optional) into one table with inline notes. Same
  information, a third of the vertical space.
- Merge the former ten setup steps into seven: trivial steps like 'run
  npx cap add/sync/open' are one code block now; removed the cap:sync
  package.json snippet (a convenience script the user can trivially
  add themselves).
- Shrink the safe-area utilities table to a bulleted highlight list
  with a link to the plugin README for the full utility surface.
- Replace the four standalone safe-area example snippets with a single
  four-line example block.
- Trim troubleshooting to the five most common issues, noting that the
  remaining edge cases (secureStorage per-bundle-id behavior, custom-
  theme status-bar sync) are documented in the relevant file headers.

No API changes, no Tailwind-v4 regressions — all the instructions from
the previous revision are preserved or pushed down into the copied
files' JSDoc where they belong.
2026-04-26 22:01:49 -05:00
Alex Gleason 924d430310 Update capacitor skill for Tailwind v4 safe-area plugin
The previous version pinned tailwindcss-safe-area to 0.8.0 and walked
through registering it in a tailwind.config.ts plugins array. mkstack
now ships Tailwind v4 with CSS-first config (@import "tailwindcss"
in src/index.css, no tailwind.config.ts), and the plugin's v1.x line
has switched from a JS plugin entry point to a plain CSS file consumed
via @import — using @plugin fails to resolve.

Updates:
- Install step now pulls the latest tailwindcss-safe-area (1.x) with
  a note that v3 projects still need 0.8.0 + plugins array.
- Step 3 replaces the tailwind.config.ts edit with an @import line in
  src/index.css, placed after @import "tailwindcss".
- Troubleshooting entries for WebView <140 and 'pt-safe does not
  exist' rewritten to reference the CSS import model.
- Utilities table refreshed to match the v4 README (adds border-*-safe,
  h-svh-safe/h-lvh-safe/h-vh-safe/h-fill-safe, start/end logical
  variants, and the safe/safe-none enable-disable toggles).
- safe-area-shim.css header updated to show the v4 import order
  (@import "tailwindcss-safe-area"; then @import "./safe-area-shim.css")
  instead of the old @tailwind utilities directive.
2026-04-26 22:00:13 -05:00
Alex Gleason e0f6a061b4 Tighten nostr-security skill (321 -> 152 lines)
Removes redundancy without losing substance:
- Drops the verbatim CSP meta tag (already in index.html) in favor of a
  prose summary of what's enforced and the style-src caveat.
- Collapses the 'three attack surfaces' table of contents; section
  headers already serve that purpose.
- Merges the §2 duplicate 'addressable events' example (covered by the
  bullet rules and the spoof example above).
- Consolidates the 'safe pattern' + 'mitigation' + 'rule of thumb'
  triad in §2 into one example and one guideline sentence.
- Tightens the NIP-72 walkthrough by removing narrative duplication
  between the prose and the code comments.
- Drops the 'Remember: decode npub' aside (nip19-routing skill's job).

The pre-merge checklist, the sanitizeUrl/sanitizeCssString helpers,
the spoof-vs-authors example, and the full NIP-72 query sequence are
all preserved verbatim.
2026-04-26 21:57:54 -05:00
Alex Gleason bc0206c911 Drop 'Encourage NIP-07/NIP-46' framing from nostr-security skill
The previous subsection ranked login methods by safety, which misstates
the threat: NIP-07 extensions have their own attack surface (malicious
or compromised extensions can silently sign arbitrary events) and NIP-46
relies on a separate signer's security posture. Either way, an XSS on
the app's origin can ask an active signer to sign anything, drain funds
via zap requests, or scrape DMs as they're decrypted.

Replace with a single sentence noting that remote-signer flows don't
change the XSS mitigation story — same defenses apply regardless of
login method.
2026-04-26 21:56:17 -05:00
Alex Gleason 7de955ff87 Lead with XSS threat model in Nostr security guidance
The single most important thing to understand about a web Nostr client
is that nsec keys live in plaintext in localStorage, so any XSS =
permanent, unrecoverable key theft. The previous framing led with
author filtering (important but lower-stakes) and only mentioned XSS
implicitly via URL sanitization.

Restructures both the AGENTS.md section and the nostr-security skill
so the key-storage reality and XSS mitigations come first, CSP is
explained as defense-in-depth (with a walkthrough of the existing
index.html policy), and author filtering becomes section 3 — still
important, but secondary to script-injection prevention.

Also adds a 'no dangerouslySetInnerHTML' rule and a CSP hygiene rule
to the top-level checklist so those blockers surface before any
sanitization detail.
2026-04-26 21:55:25 -05:00
Alex Gleason 03ffbdaa44 Add nostr-security skill and trim AGENTS.md section
The skill consolidates three attack surfaces for Nostr event data:
author filtering on trust-sensitive queries, URL sanitization before
rendering event-sourced links/images, and CSS injection prevention
when interpolating event data into styles. The latter two were
previously undocumented in mkstack — imported and adapted from the
Ditto project's guidance, generalized to reference sanitizeUrl and
sanitizeCssString helpers as patterns to implement (mkstack doesn't
ship them yet) rather than existing imports.

AGENTS.md's Nostr Security Model now fits in a bulleted rule list
plus a single spoof-vs-authors example, with a pointer to the skill
for the full NIP-72 moderation walkthrough and sanitization details.
2026-04-26 21:52:42 -05:00
Alex Gleason 4217e553df Nest Loading and Empty States under Design Standards in AGENTS.md
Moves the section below the design rules list and demotes it from ## to
### so it reads as a subsection rather than a standalone top-level topic.
2026-04-26 21:50:53 -05:00
Alex Gleason a1619c1dab Extract testing guidance into a dedicated skill
Moves the 'don't write tests unless asked' policy and the Vitest +
TestApp setup example out of AGENTS.md into .agents/skills/testing/.
AGENTS.md keeps a short pointer so the 'always run the test script'
rule stays top-level while the test-authoring details load on demand.

Also adds a hook-testing example (renderHook + TestApp wrapper) and
notes for running vitest directly during iteration.
2026-04-26 21:50:26 -05:00
Alex Gleason bb24cb458b Patch lockfile to resolve npm audit advisories
Bumps transitive lodash and unhead versions within existing semver
ranges, clearing 2 moderate and 1 high advisory (GHSA-r5fr-rjxr-66jc,
GHSA-f23m-r3pf-42rh, GHSA-95h2-gj7x-gx9w).
2026-04-26 21:47:45 -05:00
Alex Gleason 66410edb60 Remove unused dependencies
None of these were imported in src/ or referenced in any config file:
- @fontsource-variable/inter, @hookform/resolvers, react-intersection-observer,
  date-fns (only appeared in skill doc stubs)
- @tailwindcss/typography (no tailwind config, no @plugin import)
2026-04-26 21:46:45 -05:00
Alex Gleason ae0a857299 Enable TypeScript strict mode and drop deprecated baseUrl
tsconfig: remove the deprecated `baseUrl` (paths already use relative `./src/*`), flip strict to true, and drop the now-redundant individual linting flags that were only there to partially relax the old non-strict config.

useNostrPublish: tighten the mutation input type to a proper EventTemplate (Pick kind+content, Partial tags+created_at) so its UseMutationResult generics match the call sites under strict mode.
2026-04-26 21:42:33 -05:00
Alex Gleason b868c445d5 Bump react, vite, and tailwind to latest
Update package.json caret ranges so the declared minimums match the currently-latest releases: react & react-dom 19.2.5, vite 8.0.10. tailwindcss and @tailwindcss/vite are already on 4.2.4.
2026-04-26 21:39:28 -05:00
Alex Gleason 1a27af0212 Apply @tailwindcss/upgrade canonical class migrations
Ran `npx @tailwindcss/upgrade`. Bumps tailwindcss and @tailwindcss/vite to 4.2.x and migrates arbitrary-value syntax to the canonical v4 shorthands (e.g. translate-x-[var(--x)] \u2192 translate-x-(--x), whitespace cleanups inside calc()).
2026-04-26 21:38:20 -05:00
Alex Gleason 8a02a177f4 Silence fast-refresh warnings and modernize toast
Extract non-component exports (cva variants, contexts, hooks, constants) into sibling *-variants.ts / *-utils.ts files so every .tsx exports only components. This clears the react-refresh/only-export-components warnings introduced when regenerating the shadcn v4 components.

Affected:
- badge, button, toggle, navigation-menu, tabs: variants extracted
- form: FormFieldContext, FormItemContext, useFormField extracted
- sidebar: SIDEBAR_* constants, SidebarContext, useSidebar, sidebarMenuButtonVariants extracted
- calendar, pagination: updated to import buttonVariants from button-variants

Also upgrade toast.tsx to React 19 idioms: drop forwardRef + ElementRef + ComponentPropsWithoutRef in favor of ref-as-prop + React.ComponentProps, add data-slot attributes, replace z-[100] with z-100, and extract toastVariants to toast-variants.ts.

Includes canonical-class cleanups in chart, checkbox, command, context-menu, and drawer (e.g. min-w-[8rem] \u2192 min-w-32, data-[inset] \u2192 data-inset, [&_[cmdk-*]] \u2192 **:[[cmdk-*]]).
2026-04-26 21:37:26 -05:00
Alex Gleason 7e6ee840fe Regenerate shadcn/ui components for v4
Replace the v3-authored shadcn components with their new-york-v4 equivalents via `npx shadcn add --overwrite`. The new components use the `radix-ui` meta-package, inline `cva` variants, `data-slot` attributes, and the v4 aria-invalid/focus-ring patterns.

Also:
- Remove now-unused @radix-ui/react-* packages (only react-toast is kept for the preserved toast/toaster).
- Delete orphaned *-variants.ts / *-utils.ts files (variants are inline in v4).
- Drop duplicate src/hooks/use-mobile.ts; sidebar now imports the existing useIsMobile hook.
- Rewrite src/index.css in the shadcn v4 idiom: raw hsl() values on --background etc., with @theme inline remapping to --color-*. Switch --sidebar-background to --sidebar to match the new sidebar classes.
- Keep toast.tsx, toaster.tsx, and qrcode.tsx untouched.
2026-04-26 21:27:30 -05:00
Alex Gleason edf1b1df49 Remove unused components.json
The shadcn CLI config file isn't referenced by the build, tests, or runtime — only by `npx shadcn add`, which we don't rely on.
2026-04-26 20:52:03 -05:00
Alex Gleason f0a92e5475 Upgrade to Tailwind CSS v4
Migrate from v3's JS config + PostCSS to v4's CSS-first setup using the @tailwindcss/vite plugin. Theme tokens move into @theme inline in src/index.css, tailwindcss-animate is replaced by tw-animate-css, and the container utility is redeclared via @utility. A compatibility layer preserves v3's default border color so existing shadcn/ui components render unchanged. Also exclude .agents/** (and other non-source dirs) from the Vitest run.
2026-04-26 20:51:29 -05:00
Alex Gleason b5043195d9 Remove skill list from AGENTS.md
The skill tool already provides a list of available skills with
descriptions, so enumerating them in AGENTS.md is redundant. Inline
"load the X skill" pointers next to related sections are kept \u2014
they serve as contextual cross-references, not a directory.
2026-04-26 20:44:31 -05:00
Alex Gleason 9617964e69 Split AGENTS.md into skills; compress design and query prose
Extract five topic areas into loadable skills: file-uploads,
nostr-encryption, theming, nip19-routing, nostr-relay-pools. Trim the
shadcn component enumeration, hook list, NostrMetadata type dump, and
Design Standards prose down to concrete rules. AGENTS.md shrinks from
1147 to 409 lines (~64%) while preserving the security model, core
hook usage, routing, loading/empty state, and git/test policies.
2026-04-26 20:43:22 -05:00
Alex Gleason 90e9045829 Shrink AccountSwitcher trigger to match starpoint
Starpoint achieves a more compact trigger via className descendant
selectors on LoginArea (h-10, p-1 pr-2.5, gap-2, w-8 h-8 avatar, no
name label). Apply those values as the component's default instead of
requiring every call site to override them.

Drops the md+ name label \u2014 the display name still shows inside the
dropdown. Also removes the 'stable file' warning header since this is
now an actively-maintained component.
2026-04-26 20:36:10 -05:00
Alex Gleason fc34ae02d4 Unify login/signup into single AuthDialog with 'Join' button
LoginArea now shows a single 'Join' button instead of separate 'Log in'
and 'Sign Up' buttons. The button opens a unified AuthDialog ported from
espy with steps: welcome \u2192 generate \u2192 secure \u2192 profile \u2192 login \u2192 connect.

The welcome step lets the user choose 'Create new account' or 'I already
have an account', so no functionality is lost \u2014 extension login,
nostrconnect QR flow, bunker URI, and secret-key file upload are all
preserved. Styling uses the template's neutral shadcn look rather than
espy's gradients, and copy is generic (no product branding).

Deletes LoginDialog.tsx and SignupDialog.tsx; updates AGENTS.md to
describe the new single-button behavior.
2026-04-26 20:16:14 -05:00
Alex Gleason 83c0ed42af Simplify nostr-comments skill and add 3-dots actions menu
- Drop the outer Card wrapper, title, and counter from CommentsSection; it
  now renders as a lightweight space-y-6 container matching starpoint.
- Drop the Card wrapper and 'Adding to the discussion' label from
  CommentForm; use a rounded Textarea + right-aligned 'Post' button.
- Add a per-comment 3-dots menu with 'Open in Ditto' (opens nevent on
  ditto.pub) and 'Delete' (NIP-09 kind 5, shown only for own comments,
  confirmed via AlertDialog, optimistically removes from the cached
  useComments result via queryClient.setQueriesData).
- Remove the obsolete title prop from SKILL.md docs and examples.
2026-04-26 20:09:29 -05:00
Alex Gleason 76dc27a513 Add nip85-stats skill for NIP-85 Trusted Assertion stats 2026-04-26 20:03:42 -05:00
Alex Gleason 3866c0a119 Use tailwindcss-safe-area plugin in capacitor skill
Replaces the hand-rolled safe-area CSS utilities with the
tailwindcss-safe-area Tailwind plugin (same approach Shakespeare uses),
which gives us a richer utility set plus offset / or variants:

  pt-safe, pb-safe, px-safe, p-safe, mt-safe, inset-safe,
  top-safe, bottom-safe, h-dvh-safe, min-h-dvh-safe,
  pt-safe-offset-4 (safe area + 1rem),
  pb-safe-or-8 (max of safe area and 2rem),
  scroll-p-safe, border-t-safe, and more.

Critically, the SKILL.md now pins the plugin version per Tailwind
major \u2014 the plugin changed its registration API between 0.x and
1.x to match Tailwind's own v3\u2192v4 transition:

  Plugin 0.8.0  \u2192 Tailwind 3.x  (add to plugins: array in config)
  Plugin >=1.0  \u2192 Tailwind 4.x  (@import in main CSS, not @plugin)

mkstack ships Tailwind 3.4.x, so install targets 0.8.0 specifically.
Using @latest on a Tailwind 3 project silently produces no utilities
at all \u2014 documented in both the setup section and troubleshooting.

Also documents the Android WebView <140 caveat: Chromium bug 40699457
causes env(safe-area-inset-*) to return 0. Capacitor's SystemBars
plugin (insetsHandling: 'css', already preset in our capacitor.config.ts
template) works around it by injecting --safe-area-inset-* CSS variables,
but tailwindcss-safe-area uses env() directly and can't see them.
Two fixes:
  1. preferred: target WebView 140+ (Aug 2025+, auto-updated on any
     active Android >=7 via Play Services)
  2. fallback: new files/safe-area-shim.css that redeclares the common
     utilities with var(--safe-area-inset-*, env(..., 0px)) so the
     SystemBars-injected variables win. Copy to src/ and @import after
     @tailwind utilities; if targeting older Android fleets.

Changes:
- Remove files/safe-area.css (hand-rolled utilities)
- Add files/safe-area-shim.css (optional Android <140 override)
- SKILL.md: new step 3 'Register the Tailwind Safe-Area Plugin'
  inserted between 'Copy Skill Files' and 'Edit capacitor.config.ts';
  subsequent steps renumbered 4\u201310
- SKILL.md: 'Install Dependencies' adds the Tailwind plugin with a
  version matrix table and explicit v3-pinning rationale
- SKILL.md: 'Using the APIs \u2192 Safe-area utilities' rewritten with
  a real-world usage cheatsheet mapping plugin classes to use cases
- SKILL.md: expanded troubleshooting with three new safe-area
  entries (Android env-0 WebView<140, 'pt-safe doesn't exist' =
  plugin not registered or wrong major version, iOS missing
  viewport-fit=cover)

Validated: full stack staged into src/ + package.json (including
[email protected] and tailwind.config.ts plugins
registration). npm run test passes with only the 6 pre-existing
baseline errors; reverted cleanly.
2026-04-26 19:53:28 -05:00
Alex Gleason f927a00dcf Add capacitor skill for native iOS/Android builds
Provides the cross-platform primitives needed to wrap the mkstack web app
as a native iOS and Android binary using Capacitor, modeled on how Ditto
integrates the framework.

Each helper works unconditionally on every platform \u2014 native builds
use the real Capacitor plugin, web falls back to an equivalent browser
API:

- haptics: impactLight/Medium/Heavy, notificationSuccess/Warning/Error,
  selectionChanged \u2014 taptic engine on native, navigator.vibrate() on
  web, silent no-op where neither exists
- downloadTextFile / openUrl \u2014 @capacitor/filesystem and native
  share sheet on native, <a download> and window.open on web
- secureStorage + useSecureLocalStorage \u2014 iOS Keychain / Android
  KeyStore adapter with automatic migration of existing plaintext values
  from localStorage on first native read, plus an async-aware React hook
  that exposes a 'ready' flag
- DeepLinkHandler \u2014 listens for Capacitor appUrlOpen and forwards
  into React Router navigation
- bootstrapNative() \u2014 hides the iOS keyboard accessory bar and keeps
  the system-bar icon style in sync with the active CSS theme via
  MutationObserver on both the <html> class and the theme-vars style
  element; detects dark background from theme class or computed body
  luminance
- safe-area CSS utilities \u2014 .safe-area-top/-bottom/-left/-right
  padding classes plus .safe-area-inset-top/-bottom positional variants,
  preferring --safe-area-inset-* CSS vars (injected by the SystemBars
  plugin on Android) over env(safe-area-inset-*) so Chromium <140 on
  Android Just Works
- capacitor.config.ts template \u2014 preconfigured with androidScheme
  https, ios contentInset never, SystemBars insetsHandling css; placeholder
  appId / appName / scheme ready to be customized
- patch-cap-config.mjs \u2014 post-cap-sync hook that restores
  packageClassList entries for local (non-SPM) native plugin classes so
  they get registered at startup

SKILL.md documents the full setup sequence: install the nine
@capacitor/* + capacitor-secure-storage-plugin packages, copy files
into src/, paste the CSS snippet into index.css, edit capacitor.config.ts
identity fields, add viewport-fit=cover, wire bootstrapNative() into
main.tsx and DeepLinkHandler into AppRouter, npx cap add android / ios,
build, sync, run. Also covers common follow-ups (custom plugins, icons,
splash, push, deep-link verification, credential manager integration)
and troubleshooting (safe-area zero on Android, navigation no-op, keychain
orphaning, keyboard accessory bar timing, custom theme detection).

Validated: all files staged into src/ + deps installed \u2014 npm run
test passes with only the 6 pre-existing baseline errors (template
FIXMEs + missing index.html manifest/meta), then cleanly reverted.
2026-04-26 19:48:23 -05:00
Alex Gleason 0b220f250a Upgrade note-content skill with advancements from Ditto
Replaces the minimal NoteContent component with the full-featured
version from ~/Projects/ditto, and bundles the helper modules and
minimal companion stubs needed to make it work standalone.

New capabilities:
- BOLT11 lightning-invoice detection (renders LightningInvoiceCard)
- Inline image / video / audio / webxdc embeds with MIME detection
- Consecutive images grouped into an ImageGallery with shared Lightbox
- NIP-94 imeta-declared media appended when absent from content
- Embedded nevent / naddr cards, with relay and author hints pulled
  from q tags; supports naddr1 fragments embedded in external URLs
- Bare and @-prefixed NIP-19 identifiers (no nostr: prefix required)
- Line-end-aware link rendering: URLs at the end of a line become
  preview cards, mid-sentence URLs stay inline
- Trailing-punctuation stripping on URLs so 'see https://x.com.'
  links correctly
- wss:// relay URLs routed to /r/<encoded>
- Unicode-aware hashtag regex (matches non-ASCII letters)
- NIP-30 custom emoji via :shortcode: with per-event and viewer-wide
  fallback collections (useCustomEmojis)
- Flag emoji linkified to /i/iso3166:<CC>
- 'Emoji-only' posts auto-rendered at large size
- dir="auto" for RTL content
- Whitespace normalization around block embeds
- disableEmbeds / disableMediaEmbeds / disableNoteEmbeds /
  hideEmbedImages props for recursive embed cards and preview
  contexts

New bundled files:
- lib/: mediaUrls.ts, sanitizeUrl.ts, imeta.ts, customEmoji.ts,
  getDisplayName.ts, avatarShape.ts, countries.ts
- hooks/: useCustomEmojis.ts (stub), useBlossomFallback.ts (stub),
  useProfileUrl.ts (stub)
- components/: LinkEmbed, EmbeddedNote, EmbeddedNaddr,
  LightningInvoiceCard, VideoPlayer, AudioVisualizer, WebxdcEmbed,
  ImageGallery + Lightbox, ProfileHoverCard, CustomEmoji \u2014 all
  minimal but functional stubs; each file documents how to upgrade
  to a richer implementation

SKILL.md rewritten with full file list, upgrade paths for each
stub, routing expectations, and a patterns-to-render table.

Validated: tsc --noEmit clean, vitest run passes all 5 NoteContent
tests, vite build succeeds \u2014 when all skill files are staged
into src/ alongside the component.
2026-04-26 19:38:31 -05:00
Alex Gleason c067e87f2c Add note-content skill for rich text rendering of Nostr notes
Moves src/components/NoteContent.tsx and its test file into a new
note-content skill at .agents/skills/note-content/. The component
linkifies URLs, hashtags, and Nostr URIs (npub/nprofile/note/nevent)
inside plaintext event content, and was previously imported only by
the comments and DM stacks that have already been extracted/removed.

Also removes the 'Rendering Rich Text Content' section from
AGENTS.md since NoteContent is no longer part of the default
template surface. The new SKILL.md documents the expected /:nip19
and /t/:hashtag routes and the existing template hooks it relies on
(useAuthor, genUserName).
2026-04-26 18:04:43 -05:00
Alex Gleason 353551342b Add relay-management skill for NIP-65 relay list UI
Moves src/components/RelayListManager.tsx into a new
relay-management skill at .agents/skills/relay-management/, with a
SKILL.md covering installation, NIP-65 background, and how the
component hooks into the existing AppContext / NostrSync / kind
10002 publishing already present in the core template.

AGENTS.md's 'Relay Management' section keeps the NIP-65 sync
description but drops the RelayListManager usage example, pointing
at the new skill instead.
2026-04-26 18:00:11 -05:00
Alex Gleason bc97f82d3e Add edit-profile skill for Nostr profile editing form
Moves src/components/EditProfileForm.tsx into a new edit-profile
skill at .agents/skills/edit-profile/, with a SKILL.md covering
installation, the kind 0 fields it edits (name, about, picture,
banner, website, nip05, bot), and the existing template hooks it
plugs into (useCurrentUser, useNostrPublish, useUploadFile,
useToast).

Also removes the 'Nostr Edit Profile' section from AGENTS.md since
the component is no longer part of the default template surface.
2026-04-26 17:59:17 -05:00
Alex Gleason 0d5a415bac Extract Shakespeare AI hook into the ai-chat skill
Moves src/hooks/useShakespeare.ts into
.agents/skills/ai-chat/files/hooks/useShakespeare.ts and prepends
setup instructions to the existing SKILL.md.

Also removes the useShakespeare bullet from AGENTS.md since the hook
is no longer part of the default template surface.
2026-04-26 17:58:22 -05:00
Alex Gleason 29913ef530 Extract comment system into the nostr-comments skill
Moves the NIP-22 (kind 1111) commenting stack out of src/ and into
.agents/skills/nostr-comments/files/ \u2014 useComments, usePostComment,
and the Comment / CommentForm / CommentsSection components.

Updates the existing SKILL.md with a setup preamble explaining how
to copy the files back into src/ when a project needs comment
functionality. No dependency changes were required; the skill only
uses packages already present in the template.
2026-04-26 17:57:46 -05:00
Alex Gleason c6be6355a7 Remove direct messaging from the codebase
Deletes the entire DM stack \u2014 DMProvider, DMContext, the dm/ UI
components, useDMContext, useConversationMessages, the dm* library
modules, pages/Messages.tsx, and the nostr-direct-messages skill.
Also drops the idb dependency, which was only used by the DM
IndexedDB message store.

The implementation was complex and tightly coupled; removing it
clears the way for a future, cleaner approach if DM support is
needed again.
2026-04-26 17:57:05 -05:00
Alex Gleason 9e2599502d Extract NWC and Lightning zap code into an nwc skill
Moves NWC wallet connection (useNWC, NWCContext, WalletModal) along with
the WebLN wallet detection (useWallet) and NIP-57 zap stack (useZaps,
ZapButton, ZapDialog) out of src/ and into .agents/skills/nwc/ as an
opt-in skill. Removes NWCProvider from App.tsx and TestApp.tsx, drops
the NWC-only dependencies (@getalby/sdk, @webbtc/webln-types) from
package.json, and updates AGENTS.md to stop referencing the extracted
hooks and components.

The new SKILL.md explains how to reinstall the dependencies, copy the
files back into src/, and wire up NWCProvider when a project actually
needs Lightning wallet and zap functionality.
2026-04-26 17:48:46 -05:00
Alex Gleason 59c32c845c Add mandatory commit instruction to AGENTS.md
Require that every completed task end with a git commit, without waiting
for the user to ask. Committing is part of completing the task.
2026-04-26 00:58:25 -05:00
Alex Gleason 4044d586db Upgrade Radix UI packages to fix infinite render loop with React 19
@radix-ui/react-popper 1.2.4 had a useEffect with no dependency array
that called setState on every render, causing an infinite loop. Fixed
in 1.2.8 by tracking the previous anchor in a ref.
2026-03-28 02:31:41 -05:00
Alex Gleason 01889d1207 Upgrade Vite and Nostrify 2026-03-28 00:43:37 -05:00
Alex Gleason dcfdbf9e47 Upgrade to React 19
- react, react-dom: ^18.3.1 -> ^19.2.4
- @types/react, @types/react-dom: ^18.3.1 -> ^19.x
- react-day-picker: ^8.10.1 -> ^9.14.0 (rewrite calendar.tsx for v9 API)
- vaul: ^0.9.3 -> ^1.1.2
- Fix RefObject<T> type in ZapDialog for React 19 type changes
2026-03-28 00:13:05 -05:00
Alex Gleason cb52a18d09 Add NIP-42 relay authentication support
Sign kind 22242 AUTH events automatically when relays send challenges.
Uses a signer ref pattern so the pool doesn't need to be recreated
when the user logs in/out or switches accounts.
2026-03-25 02:14:41 -05:00
Alex Gleason 699a3acb85 Upgrade Nostrify 2026-03-25 01:47:45 -05:00
Alex Gleason 1caf9dabcb feat: add client-initiated NIP-46 (nostrconnect://) login support
Upgrade to @nostrify/[email protected] and implement the nostrconnect:// login flow:
- QR code display on desktop, deep link on mobile
- Copy URI button, retry on timeout, abort on dialog close
- Bunker URI manual input as fallback under the Remote Signer tab
- Add QRCodeCanvas component using the existing qrcode dependency
2026-03-24 16:21:15 -05:00
Alex Gleason 9af2db39f2 Upgrade to Vite 8
Way faster builds!
2026-03-20 15:51:52 -05:00
Alex Gleason 1cf1ad94b2 .claude/skills/ -> .agents/skills/ 2026-03-12 12:51:56 -05:00
Alex Gleason e67f5158b7 Standardize Nostr filter limit to 15 in AGENTS.md examples 2026-03-11 18:28:22 -05:00
Alex Gleason 32ba132ae5 Add plausible-analytics skill 2026-03-11 14:48:17 -05:00
Alex Gleason ba892fdd54 Fix iOS Safari auto-zoom on input focus by ensuring 16px minimum font size on mobile 2026-03-07 11:38:12 -06:00
Alex Gleason c88350270a Update nostr-comments skill to include full scope of NIP-73 commenting 2026-02-24 13:25:26 -06:00
Alex Gleason b39bd0b7b7 Support NIP-73 hashtag identifiers 2026-02-24 11:55:40 -06:00
Alex Gleason 4a87514a06 Remove github test workflow 2026-02-23 19:13:34 -06:00
Alex Gleason 7e184e9199 npm audit fix 2026-02-21 21:08:55 -06:00
Alex Gleason 3d77bdba93 Upgrade Nostrify 2026-02-21 21:08:26 -06:00
Alex Gleason 157ecac58b Remove AbortSignal.any calls 2026-02-21 13:57:43 -06:00
Alex Gleason 12dcbfdb33 Add 'nostr' prefix to author queryKey 2026-02-21 13:53:09 -06:00
Alex Gleason 8a69f988ce npm audit fix 2026-02-19 03:52:37 -06:00
Alex Gleason 3bbdab76a1 Upgrade Nostrify 2026-02-19 03:51:30 -06:00
Alex Gleason 6ddc230446 Reduce default eoseTimeout to 200ms 2026-02-12 14:39:07 -06:00
Alex Gleason 098be99f9f Upgrade Nostrify, also npm audit fix 2026-02-12 13:40:11 -06:00
Alex Gleason 57d3f8abec npx update-browserslist-db@latest 2026-01-30 22:58:29 -06:00
Alex Gleason 5bea40c1a2 Remove relay.nostr.band (I thought we already did this) 2026-01-30 21:55:45 -06:00
Alex Gleason c1bd55108c Remove stray docs mentions from AGENTS.md 2026-01-24 21:21:09 -06:00
Alex Gleason 266e2c92d8 Replace docs with skills 2026-01-24 21:20:22 -06:00
Alex Gleason 8163f30011 You don't actually have to pass signal now 2026-01-24 00:02:15 -06:00
Alex Gleason b97db2ca77 Upgrade zod to v4 2026-01-23 23:59:13 -06:00
Alex Gleason cda1b903a9 Merge branch 'main' of gitlab.com:soapbox-pub/mkstack 2026-01-21 16:52:45 -06:00
Alex Gleason ead11c31fe Remove stack.json 2026-01-21 16:52:23 -06:00
Alex Gleason a9bbb5ab84 Merge branch 'remove-nostr-band-relay' into 'main'
Replace dead relay.nostr.band with relay.primal.net

See merge request soapbox-pub/mkstack!29
2026-01-21 20:32:10 +00:00
Derek Ross f87510bc3a Replace dead relay.nostr.band with relay.primal.net 2026-01-21 15:29:02 -05:00
Alex Gleason fc010f9b91 Add Nostr Security Model to AGENTS.md 2026-01-21 12:14:24 -06:00
Alex Gleason 20f9ea9069 npm audit fix 2026-01-17 19:19:05 -06:00
Alex Gleason fc4c4deded Upgrade Nostrify 2026-01-17 19:18:43 -06:00
Alex Gleason b3dac352a4 Remove deploy script 2026-01-11 22:21:47 -06:00
Alex Gleason e94f53f0e2 Add -z-10 isolate hint 2026-01-10 11:37:12 -06:00
Alex Gleason 74449cf0d7 Add opencode.json with Nostr MCP server 2026-01-09 16:27:49 -06:00
Alex Gleason e26ab6a433 Fix URL wrapping in NoteContent 2025-12-30 18:19:20 -06:00
Alex Gleason 816051f5ea Greatly simplify the login and signup dialogs 2025-12-30 17:53:32 -06:00
Alex Gleason 413aa93e4f Generate custom images liberally 2025-12-23 05:54:11 -06:00
Alex Gleason 6941aad2f5 Upgrade Nostrify 2025-12-22 13:28:39 -06:00
Alex Gleason 28aba4b3a4 Revert "Fix happy-dom vuln"
This reverts commit e5b3f249f8.
2025-12-21 04:11:11 -06:00
Alex Gleason e5b3f249f8 Fix happy-dom vuln 2025-12-21 02:28:15 -06:00
Alex Gleason 12e6465912 npm audit fix 2025-12-21 02:02:24 -06:00
Alex Gleason 722d138f35 Remove "Vibed with MKStack" 2025-12-02 20:26:37 -06:00
Alex Gleason 84a15aa077 Revert "Try adding cashu deps"
This reverts commit 6534c5fcea.
2025-11-20 11:14:14 -06:00
Alex Gleason 8c7b595d22 Revert "Use nutstack package.json and package-lock.json"
This reverts commit 0bf1e0e85e.
2025-11-20 11:14:07 -06:00
Alex Gleason 0bf1e0e85e Use nutstack package.json and package-lock.json 2025-11-19 18:47:04 -06:00
Alex Gleason 6534c5fcea Try adding cashu deps 2025-11-19 18:42:35 -06:00
Alex Gleason e4ee998500 Fix posting a comment not invalidating comment cache 2025-11-17 19:44:34 -06:00
Alex Gleason 000be63075 Don't redirect /assets/* in Netlify redirects file 2025-11-13 22:11:57 -06:00
Alex Gleason 5f14ac11fc Remove DM stuff from App.tsx, add instructions on how to add it in docs 2025-11-11 17:36:32 -06:00
Alex Gleason 0b7d86a16f Remove DMProvider from App.tsx and update DM documentation
- Removed DMProvider, DMConfig imports and configuration from App.tsx
- Updated docs/NOSTR_DIRECT_MESSAGES.md with setup instructions
- DM functionality now requires manual setup as documented
- Preserved all existing intentional test errors
2025-11-11 17:34:45 -06:00
Alex Gleason 8496cb99e5 Disable DM functionality by default 2025-11-11 17:31:46 -06:00
Alex Gleason 386d664a33 Merge branch 'main' of gitlab.com:soapbox-pub/mkstack 2025-11-10 17:49:28 -06:00
Alex Gleason 0a5e8fc9e0 Bully the robot to utilize git if it's available, and to always read files before writing to them 2025-11-10 17:45:42 -06:00
Alex Gleason 2ba510c54f Merge branch 'removeMessageRoute' into 'main'
Remove "/messages" route

See merge request soapbox-pub/mkstack!27
2025-11-07 12:19:29 +00:00
lemonknowsall eb0fd14e33 remove /messages route 2025-11-06 19:43:20 -08:00
Alex Gleason 0532d23b57 RelayListManager improved mobile support 2025-11-05 00:23:40 -06:00
Alex Gleason 8eddf49e61 Implement NIP-65 relay management
- Replace single relayUrl with NIP-65 compatible relayMetadata structure
- Add RelayListManager component for managing multiple relays with read/write permissions
- Add NostrSync component to automatically sync user's NIP-65 relay list on login
- Update NostrProvider to use relay list instead of single relay
- Remove RelaySelector component and update empty states
- Update AGENTS.md documentation to reflect relay management changes
- Automatically publish relay list changes as NIP-65 events when user is logged in
2025-11-04 23:58:32 -06:00
Alex Gleason d7dee81b1c Split DM context up into multiple files 2025-11-04 23:33:58 -06:00
Alex Gleason fbafc52992 Stronger guidance to call the generate_kind tool 2025-11-03 22:33:18 -06:00
Alex Gleason 6d9e1816ee Fix some lint/test issues 2025-10-23 12:08:27 -05:00
Alex Gleason 44b264e4b4 Merge branch 'feat/messaging' into 'main'
feat/messaging

See merge request soapbox-pub/mkstack!26
2025-10-23 17:08:13 +00:00
sam cc393a266c refactor docs into the appropriate dm doc file 2025-10-23 18:17:51 +02:00
sam 7eca8f850b ++ 2025-10-23 00:07:50 +07:00
sam f37b97630f leave out yarn trace 2025-10-23 00:05:39 +07:00
sam 14db9f59d0 Merge branch 'main' into feat/messaging-example 2025-10-22 23:59:41 +07:00
sam 701067fa8f remove one invalid dep, and calmed other lint warns 2025-10-22 23:11:02 +07:00
sam ea791d405e lint fix 2025-10-22 23:06:29 +07:00
sam 35ad8cfa1b log edge case nip17 processesing errors 2025-10-22 22:48:08 +07:00
sam 0fd52feabb fix some nip17 issues; fuzzed signers and times 2025-10-22 22:05:38 +07:00
sam 440e02ff0e remove debug statemnts 2025-10-22 18:27:56 +07:00
sam 6380b1980c handle kind 14/15s via contained event instead 2025-10-22 16:55:37 +07:00
sam 79980ded70 redo encryption to enc individual messages content, not the whole blob, to circumvent nip44 signer limits 2025-10-22 16:44:27 +07:00
Alex Gleason 0562cb8ee2 Remove some cruft 2025-10-21 20:14:50 -05:00
Alex Gleason 1b4c27d17d Use nostrify from npm 2025-10-21 20:11:41 -05:00
sam 9d7f5e48df fix caching messages insecurely if signer nip44 failed 2025-10-21 22:06:29 +07:00
sam dbacdbc8ac update docs regarding default enabled state, and with info on all messaging components so that there's a better base for custom UIs 2025-10-21 21:46:22 +07:00
sam 1c23b6bafc enable a custom messaging db file per mkstacks app made 2025-10-21 21:45:20 +07:00
sam 1dc91bd978 disable message unless explicitly added 2025-10-21 21:45:04 +07:00
sam 69b314c831 wip - document DMs to the LLM 2025-10-21 21:28:57 +07:00
sam 50ed58730c expose attachments param 2025-10-21 20:42:38 +07:00
sam 69252a7526 port dms hook to provider to unify source of truth 2025-10-21 20:26:04 +07:00
sam d1ef321e38 cahce profile data 2025-10-21 17:37:52 +07:00
sam 8d14062d14 skeleton on avatar and resolved display name to avoid glitchy looking rewrites 2025-10-21 17:35:26 +07:00
sam 61763d04c8 avoid unnecessary render 2025-10-21 17:23:31 +07:00
sam 211d303301 idb package 2025-10-21 08:58:24 +07:00
sam 5ad2d7fabc add relay selector to debug/test messaging page 2025-10-21 08:58:12 +07:00
sam 76cb50f2da comvey message type in ui 2025-10-21 06:58:59 +07:00
sam 7e24b0c347 use same date formatting funcs on messages as chat list 2025-10-20 21:44:17 +07:00
sam 6c48e7c684 better loading feedback in the ui 2025-10-20 21:33:38 +07:00
sam d8b195e624 theres only one format, no need for versioning 2025-10-20 21:03:04 +07:00
sam e6acf05e8d tooltip for any decryption errors for the curious minded 2025-10-20 19:34:44 +07:00
sam e8ef8f02ab query relays for nip4 and nip17s in parallel 2025-10-20 19:07:16 +07:00
sam e218305799 encrypt the whole message cache instaed of individual messages, for faster decryption on load 2025-10-20 18:36:16 +07:00
sam 8bbb247ba8 intercept hard refresh to clear cache 2025-10-20 15:16:51 +07:00
sam ed80d74824 use a config object for DM provider 2025-10-20 14:04:58 +07:00
sam 92eb50f8d2 handle edge case cache reset when user changes relay while logged out then logs in again 2025-10-20 12:53:58 +07:00
sam f379a95548 clear message cache on relay change 2025-10-20 12:47:18 +07:00
sam 9bafd29ec9 fix updating latest message date when new messages from another nip are added 2025-10-20 12:00:05 +07:00
sam d7d6f8d6d5 change formatting for recent convo 2025-10-20 11:52:56 +07:00
sam 381fdaf977 ensure unique ids for dom 2025-10-19 22:34:26 +07:00
sam 15ec6c69e7 fix issue with decrypting stored encrypted messages 2025-10-19 21:42:09 +07:00
sam 7a52562926 wip kind 14/15 within nip17 seal for attachments 2025-10-19 19:57:40 +07:00
sam 5d8a4d4ace since nip17s can be fuzzed +- 2 days, query/subscribe from -2days as an offset 2025-10-19 19:02:33 +07:00
sam cb50cbe137 give 1059s a fuzzed time 2025-10-19 18:58:13 +07:00
sam 79b03dee38 random signers for 1059s 2025-10-19 18:16:09 +07:00
sam 04ae3d89c0 pagination 2025-10-19 14:37:43 +07:00
sam 1ffe78c80c let messaging be optional 2025-10-19 14:28:23 +07:00
sam 04c5a84ca9 memoize a bunch of things 2025-10-19 14:18:55 +07:00
sam 71b9c9d380 rename dm components for concistency 2025-10-19 14:12:29 +07:00
sam cb231c7770 put the split responsive messaging ui in a component of its own 2025-10-19 13:57:15 +07:00
sam d72b28cf77 loading state copy 2025-10-19 13:24:12 +07:00
Alex Gleason 19ecfee4bf Add Buffer polyfill 2025-10-18 12:11:32 -05:00
sam 67658eb446 optionality around what messaging nips can be used 2025-10-18 21:37:09 +07:00
sam d8e2e62736 add warn to all nip4 messages 2025-10-18 21:04:36 +07:00
sam f37d86b8d3 fix sending nip4 2025-10-18 20:53:53 +07:00
sam d3866ae0af fix use latest message in sidebar 2025-10-18 20:49:09 +07:00
sam f6e149893b fix surfacing decrypt error for nip17s once already cached 2025-10-18 20:43:17 +07:00
sam dcffee03af rearrange header 2025-10-18 20:33:17 +07:00
sam 9d3ead4428 fix scroll and use a warn for nip4 messages 2025-10-18 20:18:35 +07:00
sam 9e222850ce fix sixing of conversation list items 2025-10-18 19:39:51 +07:00
sam 114eb13ce6 clear cache properly and without hacky window reload 2025-10-18 18:54:48 +07:00
sam d72fc80cc5 use a lower subscription overlap 2025-10-18 18:51:08 +07:00
sam 68031244a5 fix: always update sync time even if no messages 2025-10-18 18:44:18 +07:00
sam 53ac562d10 ++ 2025-10-18 18:26:15 +07:00
sam 51be437219 change var names, remove unused, change component to pure style 2025-10-18 18:25:46 +07:00
sam b132e4847d wip chat ui 2025-10-18 18:19:47 +07:00
sam 1d42551b36 wip initial dump of DM stuff from universes 2025-10-18 15:34:36 +07:00
Alex Gleason 49abb22471 Fix inefficient queryClient update when relay URL changes 2025-10-16 18:42:35 -05:00
Alex Gleason a974da9f88 Make Ditto relay the default 2025-10-16 18:33:30 -05:00
Alex Gleason 16837284fb Only set app config that's actually changed 2025-10-16 18:33:24 -05:00
Alex Gleason 3f21df473b Try copying in some of bolt.diy's system prompt 2025-10-12 19:17:32 -05:00
Alex Gleason cec3b7f7d2 Merge branch 'main' of gitlab.com:soapbox-pub/mkstack 2025-10-11 18:26:25 -05:00
Alex Gleason df0cc7c6aa Add robots.txt 2025-10-11 17:13:33 -05:00
Alex Gleason 629c350300 Merge branch 'aiChatModelSelector' into 'main'
Remove Hardcoded Shakespeare Models

See merge request soapbox-pub/mkstack!25
2025-10-08 06:29:10 +00:00
lemonknowsall 998bf4fc47 remove hardcoded model names 2025-10-07 22:56:30 -07:00
Alex Gleason c69e440c04 Merge branch 'weblnQuiet' into 'main'
Make webln check less intrusive

See merge request soapbox-pub/mkstack!24
2025-10-05 23:59:37 +00:00
Chad Curtis aac77d05bd Move type import to line. v2 2025-10-05 21:11:47 +00:00
Chad Curtis c3c41ca4b3 Move type import to line. 2025-10-05 21:10:57 +00:00
Chad Curtis bd675e090e Remove unrelated lint fix attempt. 2025-10-05 21:09:12 +00:00
Chad Curtis b77885093c Remove webln from state, simplify webln detection. 2025-10-05 20:59:27 +00:00
Chad Curtis 45cdcecf9e Review fixes 2025-10-05 20:05:33 +00:00
Chad Curtis d462a8d679 Remove unneeded webln npm package
This change removes the webln package as it serves no specific function that isn't
already provided via native browser capability as it relates to WebLN.
2025-10-05 19:33:04 +00:00
Alex Gleason 1fbd0cdcc2 Merge branch 'infiniteDedup' into 'main'
Add deduplication to infinite feed scroll example

See merge request soapbox-pub/mkstack!23
2025-10-05 18:54:44 +00:00
Chad Curtis 23b9ca58c0 Add deduplication to infinite feed scroll example
This change introduces a simple deduplication mechanicsm for the example infinite
scroll feed code we provide for the agent. I have also added a 'isFetchingNextPage'
check to avoid the potential scenario of aggressively overfetching via quick scrolling.

If a post exists in the feed already (it has been 'seen'), the it and all duplicate
post events will be filtered out from the returned content.
2025-10-04 17:46:17 +00:00
Alex Gleason 1f2fa9d03e Add docs section to AGENTS.md 2025-10-01 00:32:03 -05:00
Alex Gleason 5c8e74b484 Move some more info out of AGENTS.md into docs/ 2025-10-01 00:23:52 -05:00
Alex Gleason b00b19a4bd Add docs/ dir, move AI chat lingo to docs/AI_CHAT.md 2025-10-01 00:13:44 -05:00
Alex Gleason aa9a0d8f93 Merge branch 'shakespeare-ai-hook' into 'main'
Shakespeare AI Hook

See merge request soapbox-pub/mkstack!21
2025-10-01 05:09:09 +00:00
lemonknowsall 6ffa656680 agent instructions to assist with AI 1-shot 2025-09-28 11:18:27 -07:00
lemonknowsall c669dd3604 added error handling and more instruction 2025-09-27 21:29:00 -07:00
lemonknowsall 6980497532 Add Shakespeare AI hook and agent instruction 2025-09-27 21:29:00 -07:00
Alex Gleason 57c646f919 Revert tailwindcss changes, @apply is fine actually
Revert "Remove all @apply usage from index.css"

This reverts commit 81fae13219.

Revert "Add TailwindCSS @apply guidelines"

This reverts commit 3aedc574d7.
2025-09-27 22:23:38 -05:00
Alex Gleason 81fae13219 Remove all @apply usage from index.css
- Convert @apply border-border to pure CSS: border-color: hsl(var(--border))
- Convert @apply bg-background text-foreground to pure CSS equivalents
- Update comment to reflect complete @apply removal
- Update AGENTS.md to strengthen prohibition language
- Maintain all theming functionality with pure CSS custom properties
2025-09-26 21:15:31 -05:00
Alex Gleason 3aedc574d7 Add TailwindCSS @apply guidelines
- Document prohibition of @apply at-rule in AGENTS.md
- Add explanatory comment in index.css about @apply policy
- Promote component-driven styling approach over @apply usage
- Note exceptions for shadcn/ui base layer styles
2025-09-26 20:59:43 -05:00
194 changed files with 19447 additions and 12027 deletions

No files matched your search

+359
View File
@@ -0,0 +1,359 @@
---
name: ai-chat
description: Build AI-powered chat interfaces, implement streaming responses, or integrate with Shakespeare AI.
---
# AI Integration with Shakespeare API
This skill provides the `useShakespeare` hook for AI chat completions with Nostr authentication against the Shakespeare AI API. The API dynamically provides available models, so you should query them at runtime rather than hardcoding model names.
**The Shakespeare integration is not included in the project by default.** When the user wants AI chat functionality, follow the setup instructions below to install the hook.
## Files Provided by This Skill
| Skill file | Copy to |
|---|---|
| `files/hooks/useShakespeare.ts` | `src/hooks/useShakespeare.ts` |
## Setup Instructions
### 1. Dependencies
No extra npm packages are required — the hook uses only packages already present in the template (`react`, `@nostrify/react/login` via the existing `useCurrentUser` hook).
### 2. Copy the Skill File Into `src/`
Copy `.agents/skills/ai-chat/files/hooks/useShakespeare.ts` into `src/hooks/useShakespeare.ts`. The hook uses `@/hooks/useCurrentUser` and `@nostrify/react/login` types — both already present in the template — so no further wiring is required.
## Usage
Use the `useShakespeare` hook for AI chat completions with Nostr authentication. The API dynamically provides available models, so you should query them at runtime rather than hardcoding model names.
```tsx
import { useShakespeare, type ChatMessage, type Model } from '@/hooks/useShakespeare';
const {
sendChatMessage,
sendStreamingMessage,
getAvailableModels,
isLoading,
error,
isAuthenticated
} = useShakespeare();
```
#### Model Selector Component
```tsx
function ModelSelector({ onModelSelect }: { onModelSelect: (modelId: string) => void }) {
const { getAvailableModels, isLoading } = useShakespeare();
const [models, setModels] = useState<Model[]>([]);
const [selectedModel, setSelectedModel] = useState<string>('');
useEffect(() => {
const fetchModels = async () => {
try {
const response = await getAvailableModels();
// Sort models by total cost (cheapest first)
const sortedModels = response.data.sort((a, b) => {
const costA = parseFloat(a.pricing.prompt) + parseFloat(a.pricing.completion);
const costB = parseFloat(b.pricing.prompt) + parseFloat(b.pricing.completion);
return costA - costB;
});
setModels(sortedModels);
// Select the cheapest model by default
if (sortedModels.length > 0) {
const cheapestModel = sortedModels[0];
setSelectedModel(cheapestModel.id);
onModelSelect(cheapestModel.id);
}
} catch (err) {
console.error('Failed to fetch models:', err);
}
};
fetchModels();
}, [getAvailableModels, onModelSelect]);
const handleModelChange = (modelId: string) => {
setSelectedModel(modelId);
onModelSelect(modelId);
};
return (
<div>
<label htmlFor="model-select">Choose Model:</label>
<select
id="model-select"
value={selectedModel}
onChange={(e) => handleModelChange(e.target.value)}
disabled={isLoading}
>
<option value="">Select a model...</option>
{models.map((model, index) => {
const totalCost = parseFloat(model.pricing.prompt) + parseFloat(model.pricing.completion);
const isCheapest = index === 0;
return (
<option key={model.id} value={model.id}>
{model.name} - {isCheapest ? "Cheapest" : `$${totalCost.toFixed(6)}/token`}
</option>
);
})}
</select>
</div>
);
}
```
#### Basic Chat Example
```tsx
function AIChat() {
const { sendChatMessage, isLoading, error, isAuthenticated } = useShakespeare();
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [input, setInput] = useState('');
const [selectedModel, setSelectedModel] = useState<string>('');
const handleSend = async () => {
if (!input.trim() || !selectedModel) return;
const newMessages = [...messages, { role: 'user', content: input }];
setMessages(newMessages);
setInput('');
try {
const response = await sendChatMessage(newMessages, selectedModel);
setMessages(prev => [...prev, {
role: 'assistant',
content: response.choices[0].message.content as string
}]);
} catch (err) {
console.error('Chat error:', err);
}
};
if (!isAuthenticated) return <div>Please log in to use AI</div>;
return (
<div className="max-w-2xl mx-auto p-4">
{error && <div className="text-red-500 mb-4">{error}</div>}
{/* Model Selection */}
<div className="mb-4">
<ModelSelector onModelSelect={setSelectedModel} />
</div>
<div className="space-y-2 mb-4">
{messages.map((msg, i) => (
<div key={i} className={`p-2 rounded ${msg.role === 'user' ? 'bg-blue-100' : 'bg-gray-100'}`}>
<strong>{msg.role}:</strong> {msg.content}
</div>
))}
</div>
<div className="flex gap-2">
<input
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyPress={(e) => e.key === 'Enter' && handleSend()}
className="flex-1 p-2 border rounded"
disabled={isLoading || !selectedModel}
placeholder={!selectedModel ? "Select a model first..." : "Type your message..."}
/>
<button
onClick={handleSend}
disabled={isLoading || !selectedModel}
className="px-4 py-2 bg-blue-500 text-white rounded disabled:opacity-50"
>
Send
</button>
</div>
</div>
);
}
```
#### Streaming Chat Example
```tsx
function StreamingChat() {
const { sendStreamingMessage } = useShakespeare();
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [currentResponse, setCurrentResponse] = useState('');
const [selectedModel, setSelectedModel] = useState<string>('');
const handleStreaming = async (content: string) => {
if (!selectedModel) return;
setCurrentResponse('');
const newMessages = [...messages, { role: 'user', content }];
setMessages(newMessages);
try {
await sendStreamingMessage(newMessages, selectedModel, (chunk) => {
setCurrentResponse(prev => prev + chunk);
});
// Add the complete response to messages
if (currentResponse.trim()) {
setMessages(prev => [...prev, {
role: 'assistant',
content: currentResponse
}]);
}
} catch (err) {
console.error('Streaming error:', err);
} finally {
setCurrentResponse('');
}
};
return (
<div>
{/* Model selection UI */}
<div className="mb-4">
<ModelSelector onModelSelect={setSelectedModel} />
</div>
{/* Chat interface */}
{/* ... rest of your chat UI */}
</div>
);
}
```
#### Model Information
Models are dynamically fetched from the Shakespeare API and include:
- **Model ID**: Unique identifier for the model
- **Name**: Human-readable model name
- **Description**: Model capabilities and use cases
- **Context Window**: Maximum token limit for conversations
- **Pricing**: Cost per token for prompt and completion
- **Free Models**: Models with `pricing.prompt === "0"` and `pricing.completion === "0"`
#### Key Points
- **Dynamic Model Discovery**: Always fetch available models using `getAvailableModels()`
- **Authentication Required**: User must be logged in with Nostr account
- **Free vs Premium**: Check pricing to determine if model requires credits
- **Error Handling**: Handle `isLoading` and `error` states appropriately
- **Model Selection**: Provide UI for users to choose between available models
## Implementation Patterns and Best Practices
### Dialog Component Patterns
When using Dialog components, always ensure accessibility compliance by including required elements:
```tsx
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription } from "@/components/ui/dialog";
// ✅ Correct - Always include DialogHeader with DialogTitle
<Dialog open={isOpen} onOpenChange={onClose}>
<DialogContent>
<DialogHeader>
<DialogTitle>Dialog Title</DialogTitle>
<DialogDescription>
Optional description for screen readers
</DialogDescription>
</DialogHeader>
{/* Dialog content */}
</DialogContent>
</Dialog>
```
**Important**: Even if you want to hide the title visually, use the `VisuallyHidden` component to maintain accessibility:
```tsx
import { VisuallyHidden } from "radix-ui";
<DialogHeader>
<VisuallyHidden.Root>
<DialogTitle>Hidden Title for Screen Readers</DialogTitle>
</VisuallyHidden.Root>
</DialogHeader>
```
### Streaming Response Handling
When implementing streaming chat interfaces, always accumulate streamed content in a local variable before clearing the streaming state to prevent content loss:
```tsx
const handleStreamingResponse = async () => {
let streamedContent = ''; // ✅ Use local variable to accumulate content
try {
await sendStreamingMessage(messages, model, (chunk) => {
streamedContent += chunk; // ✅ Accumulate in local variable
setCurrentStreamingMessage(streamedContent); // Update UI
});
// ✅ Save accumulated content to persistent state
if (streamedContent.trim()) {
const assistantMessage: MessageDisplay = {
id: Date.now().toString(),
role: 'assistant',
content: streamedContent, // ✅ Use accumulated content
timestamp: new Date()
};
setMessages(prev => [...prev, assistantMessage]);
}
} finally {
setCurrentStreamingMessage(''); // ✅ Clear streaming state after saving
}
};
```
### Error Boundary Patterns
Always wrap AI components with error boundaries and provide user-friendly error messages for common failure scenarios:
```tsx
import { ErrorBoundary } from '@/components/ErrorBoundary';
import { Alert, AlertDescription } from '@/components/ui/alert';
function AIChatWithErrorBoundary() {
return (
<ErrorBoundary
fallback={
<div className="p-4">
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>
Something went wrong with the AI chat. Please refresh the page and try again.
</AlertDescription>
</Alert>
</div>
}
>
<AIChat />
</ErrorBoundary>
);
}
// In your AI component, handle specific error types gracefully:
function useAIWithErrorHandling() {
const { sendChatMessage, error, clearError } = useShakespeare();
const sendMessage = async (messages: ChatMessage[], modelId: string) => {
try {
await sendChatMessage(messages, modelId);
} catch (err) {
// Handle specific error types with user-friendly messages
if (err.message.includes('401')) {
throw new Error('Authentication failed. Please log in again.');
} else if (err.message.includes('402')) {
throw new Error('Insufficient credits. Please add credits to use premium features.');
} else if (err.message.includes('network')) {
throw new Error('Network error. Please check your internet connection.');
}
throw err; // Re-throw for error boundary
}
};
return { sendMessage, error, clearError };
}
```
@@ -0,0 +1,372 @@
import { useCallback, useState } from 'react';
import { useCurrentUser } from './useCurrentUser';
import type { NUser } from '@nostrify/react/login';
// Types for Shakespeare API (compatible with OpenAI ChatCompletionMessageParam)
export interface ChatMessage {
role: 'user' | 'assistant' | 'system';
content: string | Array<{
type: 'text' | 'image_url';
text?: string;
image_url?: {
url: string;
};
}>;
}
export interface ChatCompletionRequest {
model: string;
messages: ChatMessage[];
stream?: boolean;
temperature?: number;
max_tokens?: number;
}
export interface ChatCompletionResponse {
id: string;
object: string;
created: number;
model: string;
choices: Array<{
index: number;
message: ChatMessage;
finish_reason: string;
}>;
usage: {
prompt_tokens: number;
completion_tokens: number;
total_tokens: number;
};
}
export interface Model {
id: string;
name: string;
description: string;
object: string;
owned_by: string;
created: number;
context_window: number;
pricing: {
prompt: string;
completion: string;
};
}
export interface ModelsResponse {
object: string;
data: Model[];
}
// Configuration
const SHAKESPEARE_API_URL = 'https://ai.shakespeare.diy/v1';
// Helper function to create NIP-98 token
async function createNIP98Token(
method: string,
url: string,
body?: unknown,
user?: NUser
): Promise<string> {
if (!user?.signer) {
throw new Error('User signer is required for NIP-98 authentication');
}
// Create the tags array
const tags: string[][] = [
['u', url],
['method', method]
];
// Add payload hash for requests with body (following NIP-98 spec)
if (body && (method === 'POST' || method === 'PUT' || method === 'PATCH')) {
const bodyString = JSON.stringify(body);
const encoder = new TextEncoder();
const data = encoder.encode(bodyString);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const payloadHash = Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, '0'))
.join('');
tags.push(['payload', payloadHash]);
}
// Create the HTTP request event
const event = await user.signer.signEvent({
kind: 27235, // NIP-98 HTTP Auth
content: '',
tags,
created_at: Math.floor(Date.now() / 1000)
});
// Return the token (base64 encoded event)
return btoa(JSON.stringify(event));
}
// Helper function to handle API errors with user-friendly messages
async function handleAPIError(response: Response) {
if (response.status === 401) {
throw new Error('Authentication failed. Please make sure you are logged in with a Nostr account.');
} else if (response.status === 402) {
throw new Error('Insufficient credits. Please add credits to your account to use premium models, or use the free "tybalt" model.');
} else if (response.status === 400) {
try {
const error = await response.json();
if (error.error?.type === 'invalid_request_error') {
// Handle specific validation errors
if (error.error.code === 'minimum_amount_not_met') {
throw new Error(`Minimum credit amount is $${error.error.minimum_amount}. Please increase your payment amount.`);
} else if (error.error.code === 'unsupported_method') {
throw new Error('Payment method not supported. Please use "stripe" or "lightning".');
} else if (error.error.code === 'invalid_url') {
throw new Error('Invalid redirect URL provided for Stripe payment.');
}
}
throw new Error(`Invalid request: ${error.error?.message || error.details || error.error || 'Please check your request parameters.'}`);
} catch {
throw new Error('Invalid request. Please check your parameters and try again.');
}
} else if (response.status === 404) {
throw new Error('Resource not found. Please check the payment ID or try again.');
} else if (response.status >= 500) {
throw new Error('Server error. Please try again in a few moments.');
} else if (!response.ok) {
try {
const errorData = await response.json();
throw new Error(`API error: ${errorData.error?.message || errorData.details || errorData.error || response.statusText}`);
} catch {
throw new Error(`Network error: ${response.statusText}. Please check your connection and try again.`);
}
}
}
export function useShakespeare() {
const { user } = useCurrentUser();
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
// Clear error helper
const clearError = useCallback(() => {
setError(null);
}, []);
// Chat completion function
const sendChatMessage = useCallback(async (
messages: ChatMessage[],
model: string = 'shakespeare',
options?: Partial<ChatCompletionRequest>
): Promise<ChatCompletionResponse> => {
if (!user) {
throw new Error('User must be logged in to use AI features');
}
setIsLoading(true);
setError(null);
try {
const requestBody: ChatCompletionRequest = {
model,
messages,
...options
};
const token = await createNIP98Token(
'POST',
`${SHAKESPEARE_API_URL}/chat/completions`,
requestBody,
user
);
const response = await fetch(`${SHAKESPEARE_API_URL}/chat/completions`, {
method: 'POST',
headers: {
'Authorization': `Nostr ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody),
});
await handleAPIError(response);
return await response.json();
} catch (err) {
let errorMessage = 'An unexpected error occurred';
if (err instanceof Error) {
errorMessage = err.message;
} else if (typeof err === 'string') {
errorMessage = err;
}
// Add context for common issues
if (errorMessage.includes('Failed to fetch') || errorMessage.includes('Network')) {
errorMessage = 'Network error: Please check your internet connection and try again.';
} else if (errorMessage.includes('signer')) {
errorMessage = 'Authentication error: Please make sure you are logged in with a Nostr account that supports signing.';
}
setError(errorMessage);
throw new Error(errorMessage, { cause: err });
} finally {
setIsLoading(false);
}
}, [user]);
// Streaming chat completion function
const sendStreamingMessage = useCallback(async (
messages: ChatMessage[],
model: string = 'shakespeare',
onChunk: (chunk: string) => void,
options?: Partial<ChatCompletionRequest>
): Promise<void> => {
if (!user) {
throw new Error('User must be logged in to use AI features');
}
setIsLoading(true);
setError(null);
try {
const requestBody: ChatCompletionRequest = {
model,
messages,
stream: true,
...options
};
const token = await createNIP98Token(
'POST',
`${SHAKESPEARE_API_URL}/chat/completions`,
requestBody,
user
);
const response = await fetch(`${SHAKESPEARE_API_URL}/chat/completions`, {
method: 'POST',
headers: {
'Authorization': `Nostr ${token}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(requestBody),
});
await handleAPIError(response);
if (!response.body) {
throw new Error('No response body');
}
const reader = response.body.getReader();
const decoder = new TextDecoder();
try {
while (true) {
const { done, value } = await reader.read();
if (done) break;
const chunk = decoder.decode(value);
const lines = chunk.split('\n');
for (const line of lines) {
if (line.startsWith('data: ')) {
const data = line.slice(6);
if (data === '[DONE]') return;
try {
const parsed = JSON.parse(data);
const content = parsed.choices?.[0]?.delta?.content;
if (content) {
onChunk(content);
}
} catch {
// Ignore parsing errors for incomplete chunks
}
}
}
}
} finally {
reader.releaseLock();
}
} catch (err) {
let errorMessage = 'An unexpected error occurred';
if (err instanceof Error) {
errorMessage = err.message;
} else if (typeof err === 'string') {
errorMessage = err;
}
// Add context for common issues
if (errorMessage.includes('Failed to fetch') || errorMessage.includes('Network')) {
errorMessage = 'Network error: Please check your internet connection and try again.';
} else if (errorMessage.includes('signer')) {
errorMessage = 'Authentication error: Please make sure you are logged in with a Nostr account that supports signing.';
}
setError(errorMessage);
throw new Error(errorMessage, { cause: err });
} finally {
setIsLoading(false);
}
}, [user]);
// Get available models
const getAvailableModels = useCallback(async (): Promise<ModelsResponse> => {
if (!user) {
throw new Error('User must be logged in to use AI features');
}
setIsLoading(true);
setError(null);
try {
const token = await createNIP98Token(
'GET',
`${SHAKESPEARE_API_URL}/models`,
undefined,
user
);
const response = await fetch(`${SHAKESPEARE_API_URL}/models`, {
method: 'GET',
headers: {
'Authorization': `Nostr ${token}`,
},
});
await handleAPIError(response);
return await response.json();
} catch (err) {
let errorMessage = 'An unexpected error occurred';
if (err instanceof Error) {
errorMessage = err.message;
} else if (typeof err === 'string') {
errorMessage = err;
}
// Add context for common issues
if (errorMessage.includes('Failed to fetch') || errorMessage.includes('Network')) {
errorMessage = 'Network error: Please check your internet connection and try again.';
} else if (errorMessage.includes('signer')) {
errorMessage = 'Authentication error: Please make sure you are logged in with a Nostr account that supports signing.';
}
setError(errorMessage);
throw new Error(errorMessage, { cause: err });
} finally {
setIsLoading(false);
}
}, [user]);
return {
// State
isLoading,
error,
isAuthenticated: !!user,
// Actions
sendChatMessage,
sendStreamingMessage,
getAvailableModels,
clearError,
};
}
+198
View File
@@ -0,0 +1,198 @@
---
name: capacitor
description: Wrap the mkstack web app as a native iOS and Android application using Capacitor. Provides haptics, native file downloads / share sheet, OS-level secure storage (Keychain / KeyStore), deep-link routing, status-bar theme sync, and safe-area CSS utilities.
---
# Capacitor Native Wrapper
This skill turns the web app into a native iOS and Android binary using [Capacitor](https://capacitorjs.com/) — no Swift or Kotlin required for the basics. The React UI runs unchanged inside a native WebView; the helpers below provide the cross-platform primitives that make it feel native.
**Not included in the project by default.** Run the setup below when the user wants to ship to an app store or produce an `.apk` / `.ipa`.
## What this skill provides
| Capability | Web behavior | Native behavior |
|---|---|---|
| **Haptics** (`impactLight`, `notificationSuccess`, …) | `navigator.vibrate()` on Android browsers | Taptic engine / Android haptics |
| **`downloadTextFile(filename, content)`** | `<a download>` click | Writes to app Documents directory |
| **`openUrl(url)`** | `window.open(url, '_blank')` | Native share sheet |
| **`secureStorage` / `useSecureLocalStorage`** | `localStorage` | iOS Keychain / Android KeyStore, auto-migrates plaintext values |
| **`<DeepLinkHandler />`** | no-op | Forwards OS `appUrlOpen` into React Router |
| **`bootstrapNative()`** | no-op | Hides iOS keyboard accessory bar; syncs system-bar icon style with theme |
| **Safe-area utilities** (Tailwind) | `env(safe-area-inset-*)` | `env(safe-area-inset-*)` + `SystemBars` back-fill on Android |
Every helper is SSR-safe and web-safe — import and call unconditionally from shared components. Each source file ships with a JSDoc header covering the exact API, gotchas, and usage examples; read them after copying.
## Files to copy
Copy from `.agents/skills/capacitor/files/` into the matching project location:
| Skill file | Copy to |
|---|---|
| `files/lib/haptics.ts` | `src/lib/haptics.ts` |
| `files/lib/downloadFile.ts` | `src/lib/downloadFile.ts` |
| `files/lib/secureStorage.ts` | `src/lib/secureStorage.ts` |
| `files/lib/nativeBootstrap.ts` | `src/lib/nativeBootstrap.ts` |
| `files/hooks/useSecureLocalStorage.ts` | `src/hooks/useSecureLocalStorage.ts` |
| `files/components/DeepLinkHandler.tsx` | `src/components/DeepLinkHandler.tsx` |
| `files/capacitor.config.ts` | `capacitor.config.ts` (project root — edit `appId`, `appName`, `scheme`, background colors) |
| `files/scripts/patch-cap-config.mjs` | `scripts/patch-cap-config.mjs` — only needed if you add **local** (non-SPM) native plugin classes; otherwise skip |
| `files/safe-area-shim.css` | `src/safe-area-shim.css` — **only if** you need Android WebView <140 support (see shim file header and troubleshooting below) |
## Setup
### 1. Install
```bash
# Runtime + plugins
npm install @capacitor/core @capacitor/app @capacitor/filesystem \
@capacitor/haptics @capacitor/keyboard @capacitor/share \
capacitor-secure-storage-plugin
# Toolchain
npm install -D @capacitor/cli @capacitor/android @capacitor/ios
# Safe-area utilities (Tailwind v4 — this project)
npm install -D tailwindcss-safe-area
```
mkstack ships **Tailwind v4** with CSS-first config (`@import "tailwindcss"` in `src/index.css`, no `tailwind.config.ts`). If you're adapting these instructions to a Tailwind v3 project, install `[email protected]` instead and register it in `tailwind.config.ts`'s `plugins` array — `1.x` emits no utilities on v3.
### 2. Copy the skill files
Copy every file from the table above.
### 3. Register the safe-area plugin
Add a second `@import` to `src/index.css`, right after the existing `@import "tailwindcss";`:
```css
@import "tailwindcss";
@import "tailwindcss-safe-area";
@import "tw-animate-css";
```
**Use `@import`, not `@plugin`.** The package ships a plain CSS file for Tailwind v4, not a JS plugin entry point.
### 4. Fill in `capacitor.config.ts`
Edit `appId` (reverse-DNS; **cannot be changed after publishing**), `appName`, `ios.scheme`, and the iOS/Android `backgroundColor` values. All other defaults in the skill's config are production-safe.
### 5. Update `index.html`
iOS won't expose `env(safe-area-inset-*)` without `viewport-fit=cover`:
```html
<meta name="viewport"
content="width=device-width, initial-scale=1, viewport-fit=cover, interactive-widget=resizes-content" />
```
### 6. Wire up bootstrap and deep links
Call `bootstrapNative()` **before** React mounts, so system bars are themed at first paint:
```tsx
// src/main.tsx
import { bootstrapNative } from '@/lib/nativeBootstrap';
bootstrapNative();
createRoot(document.getElementById('root')!).render(<App />);
```
Render `<DeepLinkHandler />` **inside** `<BrowserRouter>` so `useNavigate()` works:
```tsx
// src/AppRouter.tsx
<BrowserRouter>
<DeepLinkHandler />
<ScrollToTop />
{/* <Routes>…</Routes> */}
</BrowserRouter>
```
**A deep link is an untrusted navigation.** Any web page the user visits can
open `myapp://whatever` — no prompt, no gesture beyond the tap that got them to
the page. `DeepLinkHandler` turns that into a `navigate()` call, so a custom
scheme lets an attacker put the user on any route in your app. Universal links
(`https://`) are safer, since the OS only routes them to you after verifying
`apple-app-site-association` / `assetlinks.json`, but the app has no way to tell
the two apart once the event arrives.
So: **no route may perform a side effect on mount.** A route that publishes an
event, follows a user, sends a payment, or deletes something as soon as it
renders is an action any website can trigger silently. Render a confirmation
the user has to click instead. If your app has no custom scheme, restricting
the handler to `url.protocol === 'https:'` is worth doing as well.
### 7. Add platforms and build
```bash
npx cap add android
npx cap add ios # macOS only
npm run build # produces dist/
npx cap sync # copies dist/ into android/ and ios/
npx cap open android # Android Studio; hit Run
npx cap open ios # Xcode (macOS only); hit Run
```
Commit the generated `android/` and `ios/` directories (signing keys stay excluded via the generated `.gitignore`s). If you later add a **local** (non-SPM) Capacitor plugin class, append `node scripts/patch-cap-config.mjs` to your sync command so `packageClassList` survives each `npx cap sync`.
## Using the APIs
Each file's JSDoc header has full usage details. Quick tour:
```tsx
import { impactLight, notificationSuccess } from '@/lib/haptics';
import { downloadTextFile, openUrl } from '@/lib/downloadFile';
import { secureStorage } from '@/lib/secureStorage';
import { useSecureLocalStorage } from '@/hooks/useSecureLocalStorage';
impactLight(); // fire-and-forget
notificationSuccess(); // silent no-op on unsupported platforms
await downloadTextFile('export.json', JSON.stringify(data));
await openUrl('https://example.com');
await secureStorage.setItem('nwc:active', conn);
await secureStorage.getItem('nwc:active');
const [conn, setConn, ready] = useSecureLocalStorage<string | null>('nwc:active', null);
if (!ready) return <Spinner />; // native reads are async
```
## Safe-area utilities
Once step 3 is done, `*-safe` utilities are available for padding, margin, position, height, border, and scroll properties. The most useful ones:
- `pt-safe`, `pb-safe`, `px-safe`, `py-safe`, `p-safe` (also logical `ps-`/`pe-` and `start-`/`end-` positions)
- `top-safe`, `bottom-safe`, `inset-safe`, `inset-x-safe`
- `h-dvh-safe`, `min-h-dvh-safe`, `h-svh-safe`, `h-lvh-safe`, `h-screen-safe`
- `{prop}-safe-offset-{n}` — safe area **plus** `{n}` (`pb-safe-offset-4` = inset + 1rem)
- `{prop}-safe-or-{n}` — `max(safe-area, {n})` (`pb-safe-or-8` = at least 2rem)
```tsx
<header className="sticky top-0 pt-safe">…</header>
<nav className="fixed inset-x-0 bottom-0 pb-safe">…</nav>
<Dialog className="h-dvh-safe">…</Dialog>
<footer className="pb-safe-or-8">…</footer>
```
Full list: [plugin README](https://github.com/mvllow/tailwindcss-safe-area).
## Common follow-ups
- **App icons / splash screen** — standard icon generator → `android/app/src/main/res/mipmap-*/` and `ios/App/App/Assets.xcassets/AppIcon.appiconset/`. For splash, add `@capacitor/splash-screen` and configure under `plugins.SplashScreen`.
- **Push notifications** — add `@capacitor/push-notifications` (FCM / APNs); the web side keeps using Web Push.
- **Deep-link verification** — host `apple-app-site-association` and `assetlinks.json` on your domain so the OS opens verified `https://` links directly. Full checklist in the `DeepLinkHandler.tsx` header.
- **Nsec autofill via iCloud Keychain / Credential Manager** — add `@capgo/capacitor-autofill-save-password` and wrap it analogously to `secureStorage`.
## Troubleshooting
- **Safe-area utilities render as `0` on Android** — Chromium WebView <140 reports `env(safe-area-inset-*)` as `0` ([bug 40699457](https://issues.chromium.org/issues/40699457)). `SystemBars` (`insetsHandling: 'css'`, already set) injects `--safe-area-inset-*` CSS variables, but `tailwindcss-safe-area` uses `env(…)` directly. **Preferred fix:** target WebView 140+ (Aug 2025; auto-updated on Android ≥7). **Fallback:** copy `files/safe-area-shim.css` to `src/` and `@import` it **after** `@import "tailwindcss-safe-area";` so the variables take over when `env()` is 0.
- **`pt-safe` doesn't exist** — either `@import "tailwindcss-safe-area";` is missing / in the wrong position (must come **after** `@import "tailwindcss";`), or you installed `0.8.0` (v3-only) on a v4 project. `npm ls tailwindcss-safe-area` should show `>=1.0.0`.
- **Safe-area is 0 on iOS Safari / simulator** — missing `viewport-fit=cover` in the `<meta name="viewport">` tag.
- **Deep links don't navigate** — `<DeepLinkHandler />` must be **inside** `<BrowserRouter>`; `useNavigate()` throws silently otherwise.
- **iOS keyboard still shows the accessory bar** — `bootstrapNative()` must run **before** any `<input>` is focused. Invoke at the top of `main.tsx`.
Remaining edge cases (`secureStorage` returning `null` after debug reinstall, status-bar theming with custom CSS-variable setups) are covered in the corresponding file headers.
@@ -0,0 +1,40 @@
import type { CapacitorConfig } from '@capacitor/cli';
// ── Fill in your app identity before running `npx cap add android` / `ios`. ──
// The appId must be a reverse-DNS-style identifier (e.g. `com.example.myapp`)
// and cannot be changed later without re-registering the app with the stores.
const config: CapacitorConfig = {
appId: 'com.example.myapp',
appName: 'MyApp',
webDir: 'dist',
server: {
androidScheme: 'https',
iosScheme: 'https',
},
android: {
// Disallow loading mixed-content (http:// inside https://).
allowMixedContent: false,
// Background color shown behind the web view before first paint.
// Usually your app's dark-theme background so the splash feels seamless.
backgroundColor: '#14161f',
},
ios: {
backgroundColor: '#14161f',
// `never` prevents WKWebView from inset-adjusting scroll content — the
// app handles safe-area insets itself in CSS via env(safe-area-inset-*).
contentInset: 'never',
// Custom URL scheme for deep-links (e.g. `myapp://…`) — match this
// in your Info.plist CFBundleURLSchemes.
scheme: 'MyApp',
},
plugins: {
SystemBars: {
// Inject --safe-area-inset-* CSS variables on Android to work around
// a Chromium bug (<140) where env(safe-area-inset-*) reports 0.
insetsHandling: 'css',
},
},
};
export default config;
@@ -0,0 +1,94 @@
import { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Capacitor } from '@capacitor/core';
/**
* Forwards OS-level deep-link opens into the React Router navigation stack.
*
* When the OS launches your app via a URL (a `https://your-domain.com/post/123`
* universal link or a `myapp://post/123` custom-scheme link), Capacitor fires
* an `appUrlOpen` event. This component listens for it and calls
* `navigate(pathname + search + hash)` so the app lands on the intended
* in-app route instead of staying on whatever page it was on.
*
* Must be rendered **inside** a `<BrowserRouter>` (so `useNavigate` works).
* Safe to render unconditionally — on web it is a no-op.
*
* ## Deep links are untrusted input
*
* Any web page the user visits can open `myapp://anything`, which arrives here
* and becomes a `navigate()` call. Universal links are verified by the OS;
* custom schemes are not, and the `appUrlOpen` event does not distinguish
* them. Treat the destination as attacker-chosen: **no route may perform a
* side effect on mount** (publishing an event, following, paying, deleting).
* Such a route is an action any website can trigger without the user knowing.
* Require a click on the page instead. Apps with no custom scheme should also
* reject anything but `url.protocol === 'https:'` below.
*
* To enable deep links:
*
* **iOS (Universal Links):**
* 1. Add your domain under *Signing & Capabilities → Associated Domains*
* as `applinks:your-domain.com`
* 2. Host an `apple-app-site-association` file at
* `https://your-domain.com/.well-known/apple-app-site-association`
*
* **iOS (custom scheme):**
* 1. Set `ios.scheme` in `capacitor.config.ts`
* 2. Capacitor already registers the scheme in Info.plist's
* `CFBundleURLSchemes` during `npx cap sync`
*
* **Android (App Links):**
* 1. Declare an `<intent-filter android:autoVerify="true">` with your
* domain in `android/app/src/main/AndroidManifest.xml`
* 2. Host a `assetlinks.json` file at
* `https://your-domain.com/.well-known/assetlinks.json`
*
* **Android (custom scheme):**
* 1. Add an `<intent-filter>` with `<data android:scheme="myapp" />` in
* the manifest
*
* @example
* // In AppRouter.tsx, inside BrowserRouter:
* <BrowserRouter>
* <DeepLinkHandler />
* <ScrollToTop />
* <Routes>...</Routes>
* </BrowserRouter>
*/
export function DeepLinkHandler() {
const navigate = useNavigate();
useEffect(() => {
if (!Capacitor.isNativePlatform()) return;
let cleanup: (() => void) | undefined;
async function setup() {
const { App } = await import('@capacitor/app');
// Handle URLs opened while the app is already running
const listener = await App.addListener('appUrlOpen', (event) => {
try {
const url = new URL(event.url);
const path = url.pathname + url.search + url.hash;
if (path) {
navigate(path);
}
} catch {
// Invalid URL, ignore
}
});
cleanup = () => listener.remove();
}
setup();
return () => {
cleanup?.();
};
}, [navigate]);
return null;
}
@@ -0,0 +1,158 @@
import { useState, useEffect, useRef } from 'react';
import { Capacitor } from '@capacitor/core';
import { secureStorage } from '@/lib/secureStorage';
/**
* Hook for storing sensitive state that should not live in plaintext
* localStorage on native platforms.
*
* - On web: uses `localStorage` (identical to `useLocalStorage`).
* - On native (Capacitor iOS/Android): uses the native Keychain / KeyStore via
* `secureStorage`. Any existing plaintext value in localStorage for the same
* key is migrated on first read and the plaintext copy is removed.
*
* This is async under the hood, so the hook additionally exposes a `ready`
* flag indicating whether the initial load has completed. While `!ready`, the
* state is `defaultValue` and callers should avoid making decisions based on
* an "empty" state (e.g. do not persist a default back if the user has real
* data stored that hasn't been loaded yet).
*
* The return tuple is `[state, setValue, ready]`.
*
* @example
* const [connection, setConnection, ready] = useSecureLocalStorage<string | null>(
* 'nwc:active',
* null,
* );
* if (!ready) return <Spinner />;
* // ...
*/
export function useSecureLocalStorage<T>(
key: string,
defaultValue: T,
serializer?: {
serialize: (value: T) => string;
deserialize: (value: string) => T;
},
) {
const serialize = serializer?.serialize || JSON.stringify;
const deserialize = serializer?.deserialize || JSON.parse;
const isNative = Capacitor.isNativePlatform();
// On web we can read synchronously during initialization (same behavior as
// useLocalStorage). On native we must wait for the async read, so we start
// with defaultValue and flip `ready` once loaded.
const [state, setState] = useState<T>(() => {
if (isNative) return defaultValue;
try {
const item = localStorage.getItem(key);
return item ? deserialize(item) : defaultValue;
} catch (error) {
console.warn(`Failed to load ${key} from localStorage:`, error);
return defaultValue;
}
});
const [ready, setReady] = useState<boolean>(!isNative);
// Track the most-recently-requested key so stale async reads don't clobber
// state after the caller swapped to a different key.
const currentKeyRef = useRef(key);
useEffect(() => {
currentKeyRef.current = key;
}, [key]);
useEffect(() => {
let cancelled = false;
async function load() {
try {
if (isNative) {
// Check secureStorage first (handles migration from plaintext
// localStorage internally per secureStorage.getItem).
const item = await secureStorage.getItem(key);
if (cancelled || currentKeyRef.current !== key) return;
setState(item ? deserialize(item) : defaultValue);
} else {
const item = localStorage.getItem(key);
if (cancelled || currentKeyRef.current !== key) return;
setState(item ? deserialize(item) : defaultValue);
}
} catch (error) {
if (!cancelled) {
console.warn(`Failed to load ${key} from secure storage:`, error);
setState(defaultValue);
}
} finally {
if (!cancelled) setReady(true);
}
}
// Reset `ready` before kicking off the new async load — this is a
// deliberate external-system sync pattern.
// eslint-disable-next-line react-hooks/set-state-in-effect
setReady(false);
load();
return () => {
cancelled = true;
};
// defaultValue and deserialize are intentionally excluded — we only want to
// re-read when the key identity changes.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [key, isNative]);
const setValue = (value: T | ((prev: T) => T)) => {
const persist = (next: T) => {
try {
const serialized = serialize(next);
if (isNative) {
// Fire-and-forget; errors are logged but shouldn't block the caller.
void secureStorage.setItem(key, serialized).catch((error) => {
console.warn(`Failed to save ${key} to secure storage:`, error);
});
} else {
localStorage.setItem(key, serialized);
}
} catch (error) {
console.warn(`Failed to serialize ${key}:`, error);
}
};
if (value instanceof Function) {
setState((prev) => {
const next = (value as (p: T) => T)(prev);
if (next === prev) return prev;
persist(next);
return next;
});
} else {
setState((prev) => {
if (value === prev) return prev;
persist(value);
return value;
});
}
};
// Sync with cross-tab changes on web. Native secure storage has no
// cross-tab concept.
useEffect(() => {
if (isNative) return;
const handleStorageChange = (e: StorageEvent) => {
if (e.key === key && e.newValue !== null) {
try {
setState(deserialize(e.newValue));
} catch (error) {
console.warn(`Failed to sync ${key} from localStorage:`, error);
}
}
};
window.addEventListener('storage', handleStorageChange);
return () => window.removeEventListener('storage', handleStorageChange);
}, [key, isNative, deserialize]);
return [state, setValue, ready] as const;
}
@@ -0,0 +1,60 @@
import { Capacitor } from '@capacitor/core';
/**
* Download a text file to the user's device.
*
* On the web this uses the classic `<a download>` trick.
* On native (Android & iOS) the file is saved to the app's Documents
* directory, which is visible in the iOS Files app and Android's
* app-scoped documents. No permissions are required.
*
* @example
* await downloadTextFile('backup.json', JSON.stringify(data));
*/
export async function downloadTextFile(filename: string, content: string): Promise<void> {
if (Capacitor.isNativePlatform()) {
const { Filesystem, Directory, Encoding } = await import('@capacitor/filesystem');
// Write straight to Documents — visible in the iOS Files app and
// Android's app-scoped documents. No storage permissions needed.
// NOTE: encoding is required — without it Capacitor expects base64 data
// and will throw for plain-text strings.
await Filesystem.writeFile({
path: filename,
data: content,
directory: Directory.Documents,
encoding: Encoding.UTF8,
});
} else {
// Web: use the anchor-click download pattern
const blob = new Blob([content], { type: 'text/plain; charset=utf-8' });
const url = globalThis.URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = filename;
a.style.display = 'none';
document.body.appendChild(a);
a.click();
globalThis.URL.revokeObjectURL(url);
document.body.removeChild(a);
}
}
/**
* Open a URL in a new browser tab, or present the native share sheet on Capacitor.
*
* The programmatic `<a target="_blank">` click pattern doesn't work inside
* WKWebView on iOS. On native platforms this presents the share sheet instead,
* letting the user open, save, or share the resource.
*
* @example
* <Button onClick={() => openUrl('https://example.com')}>Visit site</Button>
*/
export async function openUrl(url: string): Promise<void> {
if (Capacitor.isNativePlatform()) {
const { Share } = await import('@capacitor/share');
await Share.share({ url });
} else {
window.open(url, '_blank', 'noopener,noreferrer');
}
}
@@ -0,0 +1,125 @@
import { Capacitor } from '@capacitor/core';
/**
* Centralized haptic feedback utility.
*
* On native (iOS/Android) it uses @capacitor/haptics for true taptic engine
* feedback. On web it falls back to navigator.vibrate() which works on
* Android browsers but is a silent no-op elsewhere.
*
* Each helper is fire-and-forget: errors are swallowed (logged as warnings)
* so calling haptics from UI handlers never disrupts user actions.
*
* @example
* import { impactLight, notificationSuccess } from '@/lib/haptics';
*
* <Button onClick={() => { impactLight(); doThing(); }}>Tap me</Button>
*/
type ImpactStyle = 'Heavy' | 'Medium' | 'Light';
type NotificationType = 'Success' | 'Warning' | 'Error';
// Lazy-loaded Haptics plugin — only imported on native to avoid bundling
// the plugin in web builds where it isn't useful.
let hapticsPromise: Promise<typeof import('@capacitor/haptics')> | null = null;
function getHaptics() {
if (!hapticsPromise) {
hapticsPromise = import('@capacitor/haptics');
}
return hapticsPromise;
}
// ── Helpers ──────────────────────────────────────────────────────────────────
async function nativeImpact(style: ImpactStyle) {
const { Haptics, ImpactStyle } = await getHaptics();
await Haptics.impact({ style: ImpactStyle[style] });
}
async function nativeNotification(type: NotificationType) {
const { Haptics, NotificationType } = await getHaptics();
await Haptics.notification({ type: NotificationType[type] });
}
async function nativeSelectionChanged() {
const { Haptics } = await getHaptics();
await Haptics.selectionChanged();
}
function vibrate(ms: number) {
try {
navigator.vibrate?.(ms);
} catch {
/* Vibration API not available */
}
}
// ── Public API ───────────────────────────────────────────────────────────────
function warnHapticError(label: string, err: unknown) {
console.warn(`[haptics] ${label} failed:`, err);
}
/** Light tap — reactions, reposts, bookmarks, share. */
export function impactLight(): void {
if (Capacitor.isNativePlatform()) {
nativeImpact('Light').catch((e) => warnHapticError('impactLight', e));
} else {
vibrate(10);
}
}
/** Medium tap — zap button press, pull-to-refresh threshold, follow. */
export function impactMedium(): void {
if (Capacitor.isNativePlatform()) {
nativeImpact('Medium').catch((e) => warnHapticError('impactMedium', e));
} else {
vibrate(20);
}
}
/** Heavy tap — game button press, destructive confirmation. */
export function impactHeavy(): void {
if (Capacitor.isNativePlatform()) {
nativeImpact('Heavy').catch((e) => warnHapticError('impactHeavy', e));
} else {
vibrate(30);
}
}
/** Success notification — zap payment success, post published. */
export function notificationSuccess(): void {
if (Capacitor.isNativePlatform()) {
nativeNotification('Success').catch((e) => warnHapticError('notificationSuccess', e));
} else {
vibrate(15);
}
}
/** Warning notification. */
export function notificationWarning(): void {
if (Capacitor.isNativePlatform()) {
nativeNotification('Warning').catch((e) => warnHapticError('notificationWarning', e));
} else {
vibrate(20);
}
}
/** Error notification. */
export function notificationError(): void {
if (Capacitor.isNativePlatform()) {
nativeNotification('Error').catch((e) => warnHapticError('notificationError', e));
} else {
vibrate(30);
}
}
/** Selection changed — toggle switches, tab taps, picker changes. */
export function selectionChanged(): void {
if (Capacitor.isNativePlatform()) {
nativeSelectionChanged().catch((e) => warnHapticError('selectionChanged', e));
} else {
vibrate(5);
}
}
@@ -0,0 +1,121 @@
import { Capacitor, SystemBars, SystemBarsStyle } from '@capacitor/core';
/**
* One-time Capacitor-native bootstrap: configures system chrome to match
* the active CSS theme and hides the iOS keyboard accessory bar.
*
* Call this from `src/main.tsx` **before** `createRoot(...).render(...)`.
* On web this is a no-op.
*
* What it does on native:
*
* 1. Hides the iOS keyboard accessory bar (the prev/next/done toolbar above
* the keyboard) — most apps don't need it and it steals screen space.
*
* 2. Keeps the native system bar icon style (clock, battery, etc.) in sync
* with the active CSS theme. When the app is on a dark background, icons
* are rendered light; on a light background, dark. This is re-applied
* whenever:
* - the `class` on `<html>` changes (light / dark / any custom theme
* that toggles a class, e.g. your AppProvider)
* - the contents of `<style id="theme-vars">` change (custom themes
* that set CSS variables without toggling a class)
*
* Uses `SystemBars` (exposed by the Capacitor-core plugin registry). On
* Android 16+ (API 36) setBackgroundColor on the bars no longer works — the
* bars are transparent and the web content renders behind them. Your app
* should draw its own safe-area backgrounds in CSS. Only icon style matters
* here.
*
* @example
* // src/main.tsx
* import { bootstrapNative } from '@/lib/nativeBootstrap';
* bootstrapNative();
* createRoot(document.getElementById('root')!).render(<App />);
*/
export function bootstrapNative(): void {
if (!Capacitor.isNativePlatform()) return;
// iOS-only: hide the keyboard accessory bar.
if (Capacitor.getPlatform() === 'ios') {
import('@capacitor/keyboard').then(({ Keyboard }) => {
Keyboard.setAccessoryBarVisible({ isVisible: false }).catch(() => {});
}).catch(() => {});
}
/**
* SystemBarsStyle.Dark = light/white icons (use on dark backgrounds)
* SystemBarsStyle.Light = dark/black icons (use on light backgrounds)
*/
function updateStatusBar() {
const isDark = isBackgroundDark();
SystemBars.setStyle({
style: isDark ? SystemBarsStyle.Dark : SystemBarsStyle.Light,
}).catch(() => {});
}
// Apply immediately. The theme class is usually set synchronously by the
// AppProvider useLayoutEffect before the first React paint, but we still
// try early in case it's already set.
updateStatusBar();
// Re-apply whenever the theme class changes on <html>.
const classObserver = new MutationObserver(() => updateStatusBar());
classObserver.observe(document.documentElement, {
attributes: true,
attributeFilter: ['class'],
});
// Re-apply whenever the injected <style id="theme-vars"> content changes
// (covers custom themes that change CSS variables without changing the
// class).
const styleObserver = new MutationObserver(() => updateStatusBar());
const observeThemeVars = () => {
const el = document.getElementById('theme-vars');
if (el) {
styleObserver.observe(el, {
characterData: true,
childList: true,
subtree: true,
});
}
};
observeThemeVars();
// The style element may not exist yet — watch <head> for it to appear.
const headObserver = new MutationObserver(() => observeThemeVars());
headObserver.observe(document.head, { childList: true });
}
/**
* Detect whether the current app background is "dark" for the purposes of
* choosing status-bar icon color.
*
* Strategy (first match wins):
* 1. If `<html>` has class `dark`, return true.
* 2. If `<html>` has class `light`, return false.
* 3. Parse the computed `background-color` of `<body>` and compare its
* perceived luminance against 0.5.
*
* Steps 1 and 2 cover the default mkstack theme system. Step 3 covers
* custom themes that don't toggle the `light`/`dark` class on `<html>`.
*/
function isBackgroundDark(): boolean {
const cl = document.documentElement.classList;
if (cl.contains('dark')) return true;
if (cl.contains('light')) return false;
const bg = getComputedStyle(document.body).backgroundColor;
const rgb = parseRgb(bg);
if (!rgb) return false;
// Perceived luminance (ITU-R BT.709).
const [r, g, b] = rgb.map((c) => c / 255);
const lum = 0.2126 * r + 0.7152 * g + 0.0722 * b;
return lum < 0.5;
}
function parseRgb(color: string): [number, number, number] | null {
const m = color.match(/rgba?\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)/);
if (!m) return null;
return [Number(m[1]), Number(m[2]), Number(m[3])];
}
@@ -0,0 +1,71 @@
import { Capacitor } from '@capacitor/core';
import { SecureStoragePlugin } from 'capacitor-secure-storage-plugin';
/**
* Storage adapter that uses native secure storage (iOS Keychain / Android
* KeyStore) on Capacitor builds and falls back to localStorage on web.
*
* API is async-compatible with the Web Storage interface (`getItem`,
* `setItem`, `removeItem`) — each method returns a Promise.
*
* On the first native read, if a key is not found in secure storage but
* exists in localStorage, it is automatically migrated to secure storage
* and the plaintext localStorage copy is removed. This means shipping a
* Capacitor build of an app that previously wrote to localStorage will
* transparently upgrade existing users' secrets to the Keychain/KeyStore
* the first time the app reads them.
*
* Use this for any sensitive state you don't want in plaintext on device:
* - NWC (Nostr Wallet Connect) connection strings
* - Device-specific push notification keys
* - Encryption passphrases / derived keys
* - Any cached credential you'd otherwise have to re-prompt for
*
* @example
* await secureStorage.setItem('nwc:active', 'nostr+walletconnect://…');
* const conn = await secureStorage.getItem('nwc:active');
*/
export const secureStorage = {
async getItem(key: string): Promise<string | null> {
if (!Capacitor.isNativePlatform()) {
return localStorage.getItem(key);
}
try {
const { value } = await SecureStoragePlugin.get({ key });
return value;
} catch {
// Key not found in secure storage — check localStorage for migration.
const legacy = localStorage.getItem(key);
if (legacy !== null) {
// Migrate to secure storage and remove the plaintext copy.
await SecureStoragePlugin.set({ key, value: legacy });
localStorage.removeItem(key);
return legacy;
}
return null;
}
},
async setItem(key: string, value: string): Promise<void> {
if (!Capacitor.isNativePlatform()) {
localStorage.setItem(key, value);
return;
}
await SecureStoragePlugin.set({ key, value });
},
async removeItem(key: string): Promise<void> {
if (!Capacitor.isNativePlatform()) {
localStorage.removeItem(key);
return;
}
try {
await SecureStoragePlugin.remove({ key });
} catch {
// Key didn't exist — ignore.
}
},
};
@@ -0,0 +1,71 @@
/* ─────────────────────────────────────────────────────────────────────────
* Optional Android WebView <140 shim for tailwindcss-safe-area
*
* The `tailwindcss-safe-area` plugin emits CSS that uses raw
* `env(safe-area-inset-*)`. On Android WebView versions before 140
* (roughly anything shipped before Aug 2025 that hasn't auto-updated),
* Chromium has a bug where those values report 0 even when the device
* has a notch or gesture area.
*
* Capacitor's SystemBars plugin (with `insetsHandling: 'css'`, which is
* the default and is already set in the skill's `capacitor.config.ts`)
* works around this by injecting `--safe-area-inset-*` CSS variables on
* the `html` element with the correct values. But the Tailwind plugin
* uses `env()` directly, so those variables alone don't reach it.
*
* This shim redeclares the most common safe-area utilities with the
* `var(--safe-area-inset-*, env(safe-area-inset-*, 0px))` pattern so they
* prefer the SystemBars-injected variables when present and fall back to
* `env()` otherwise.
*
* ONLY include this file if you are targeting older Android devices that
* may still be running WebView <140. On iOS and on Android 140+ the
* plugin's output works correctly and this shim is redundant.
*
* How to include (Tailwind v4, CSS-first config):
* 1. Copy this file to `src/safe-area-shim.css`
* 2. Import it in `src/index.css` AFTER `@import "tailwindcss-safe-area";`
* so source order lets these rules win within the utilities layer:
*
* @import "tailwindcss";
* @import "tailwindcss-safe-area";
* @import "./safe-area-shim.css";
*
* Uses `@layer utilities` so these rules sit in the same cascade layer as
* the Tailwind utilities they're overriding; later-declared rules within
* the same layer win on specificity ties.
* ───────────────────────────────────────────────────────────────────────── */
@layer utilities {
/* Padding */
.pt-safe { padding-top: var(--safe-area-inset-top, env(safe-area-inset-top, 0px)); }
.pr-safe { padding-right: var(--safe-area-inset-right, env(safe-area-inset-right, 0px)); }
.pb-safe { padding-bottom: var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px)); }
.pl-safe { padding-left: var(--safe-area-inset-left, env(safe-area-inset-left, 0px)); }
.px-safe {
padding-right: var(--safe-area-inset-right, env(safe-area-inset-right, 0px));
padding-left: var(--safe-area-inset-left, env(safe-area-inset-left, 0px));
}
.py-safe {
padding-top: var(--safe-area-inset-top, env(safe-area-inset-top, 0px));
padding-bottom: var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px));
}
.p-safe {
padding-top: var(--safe-area-inset-top, env(safe-area-inset-top, 0px));
padding-right: var(--safe-area-inset-right, env(safe-area-inset-right, 0px));
padding-bottom: var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px));
padding-left: var(--safe-area-inset-left, env(safe-area-inset-left, 0px));
}
/* Margin */
.mt-safe { margin-top: var(--safe-area-inset-top, env(safe-area-inset-top, 0px)); }
.mr-safe { margin-right: var(--safe-area-inset-right, env(safe-area-inset-right, 0px)); }
.mb-safe { margin-bottom: var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px)); }
.ml-safe { margin-left: var(--safe-area-inset-left, env(safe-area-inset-left, 0px)); }
/* Position */
.top-safe { top: var(--safe-area-inset-top, env(safe-area-inset-top, 0px)); }
.right-safe { right: var(--safe-area-inset-right, env(safe-area-inset-right, 0px)); }
.bottom-safe { bottom: var(--safe-area-inset-bottom, env(safe-area-inset-bottom, 0px)); }
.left-safe { left: var(--safe-area-inset-left, env(safe-area-inset-left, 0px)); }
}
@@ -0,0 +1,56 @@
#!/usr/bin/env node
/**
* Patch capacitor.config.json to include local (non-SPM) plugin classes.
*
* `npx cap sync` regenerates the `packageClassList` array from SPM packages
* only, so local plugins compiled directly into the app binary (like a
* custom SandboxPlugin) are not included. This script appends them after
* sync so the Capacitor bridge eagerly registers them at startup.
*
* Usage: node scripts/patch-cap-config.mjs
* Typically run after `npx cap sync` (wire it into an npm script, e.g.:
* "cap:sync": "npx cap sync && node scripts/patch-cap-config.mjs"
* ).
*
* Edit the LOCAL_PLUGINS array below to match the class names of any
* custom native plugins you've added to your android/ios projects.
*/
import { readFileSync, writeFileSync } from 'fs';
import { resolve } from 'path';
/** Local plugin class names to ensure are registered. */
const LOCAL_PLUGINS = [
// 'MyCustomPlugin',
];
const platforms = ['ios/App/App', 'android/app/src/main/assets'];
for (const platform of platforms) {
const configPath = resolve(platform, 'capacitor.config.json');
let config;
try {
config = JSON.parse(readFileSync(configPath, 'utf-8'));
} catch {
// Platform may not exist or config not yet generated — skip.
continue;
}
const classList = new Set(config.packageClassList ?? []);
let changed = false;
for (const plugin of LOCAL_PLUGINS) {
if (!classList.has(plugin)) {
classList.add(plugin);
changed = true;
}
}
if (changed) {
config.packageClassList = [...classList];
writeFileSync(configPath, JSON.stringify(config, null, '\t') + '\n');
console.log(`Patched ${configPath}: added ${LOCAL_PLUGINS.join(', ')}`);
}
}
+93
View File
@@ -0,0 +1,93 @@
---
name: edit-profile
description: Add a form that lets users edit their Nostr profile metadata (NIP-01 kind 0). Provides EditProfileForm with fields for name, about, picture, banner, website, nip05, and a bot flag, plus Blossom image uploads wired up through useUploadFile.
---
# Edit Profile Form
This skill provides `EditProfileForm`, a drop-in React component that lets a logged-in user update their Nostr profile metadata (NIP-01 kind 0). The form covers the common metadata fields, handles image uploads through the project's existing `useUploadFile` hook, publishes a new kind 0 event on save, and invalidates the relevant TanStack Query caches so the rest of the app reflects the change.
**This component is not included in the project by default.** When the user wants profile editing, follow the setup instructions below to install the component.
## Files Provided by This Skill
| Skill file | Copy to |
|---|---|
| `files/components/EditProfileForm.tsx` | `src/components/EditProfileForm.tsx` |
## Setup Instructions
### 1. Dependencies
No extra npm packages are required. The component uses packages already present in the template:
- `react-hook-form` + `@hookform/resolvers` — form state and validation
- `zod` (via `NSchema` in `@nostrify/nostrify`) — metadata schema validation
- `@tanstack/react-query` — cache invalidation after publish
- `@nostrify/nostrify` — `NSchema.metadata()` Zod schema + `NostrMetadata` type
- `lucide-react` — icons
- shadcn/ui — `Button`, `Form`, `Input`, `Textarea`, `Switch`
### 2. Copy the Skill File Into `src/`
Copy `.agents/skills/edit-profile/files/components/EditProfileForm.tsx` into `src/components/EditProfileForm.tsx`. The component imports:
- `@/hooks/useCurrentUser` — current logged-in user and their existing metadata
- `@/hooks/useNostrPublish` — publishes the kind 0 event
- `@/hooks/useToast` — success/error feedback
- `@/hooks/useUploadFile` — Blossom uploads for picture/banner
All of these are standard in the template; no extra work is needed beyond copying the file.
## Usage
Place the component anywhere a logged-in user should be able to edit their profile. It renders the form itself, with no surrounding layout:
```tsx
import { EditProfileForm } from '@/components/EditProfileForm';
export default function EditProfilePage() {
return (
<div className="container mx-auto max-w-2xl py-8">
<h1 className="text-2xl font-semibold mb-6">Edit Profile</h1>
<EditProfileForm />
</div>
);
}
```
The component takes no props. It reads the current user's existing metadata via `useCurrentUser` and pre-populates every field, so the user can tweak values without losing anything else on their profile.
## Fields
| Field | NIP-01 key | Input | Notes |
|---|---|---|---|
| Name | `name` | text | Short handle |
| About | `about` | textarea | Bio / description |
| Picture | `picture` | URL + upload button | Profile avatar. Upload button calls `useUploadFile` and sets the resulting URL. |
| Banner | `banner` | URL + upload button | Profile banner. Same upload flow as picture. |
| Website | `website` | URL | Any related web URL |
| NIP-05 | `nip05` | text | Email-like Nostr identifier (e.g. `[email protected]`) |
| Bot | `bot` | switch | Marks the account as automated (NIP-24) |
On submit, the component publishes a kind 0 event whose `content` is the JSON-stringified metadata, and invalidates any `useAuthor`/profile queries so the UI reflects the new values immediately.
## Routing
The form is just a component. If you want a dedicated route for it, wire it up in `AppRouter.tsx`:
```tsx
// AppRouter.tsx
import EditProfilePage from './pages/EditProfilePage';
<Route path="/settings/profile" element={<EditProfilePage />} />
```
## Related Hooks
If you're building a profile page that *displays* the user's metadata (as opposed to editing it), use:
- `useCurrentUser` — the logged-in user and their metadata
- `useAuthor(pubkey)` — any user's metadata by pubkey
Both are part of the core template.
@@ -22,7 +22,7 @@ import { NSchema as n, type NostrMetadata } from '@nostrify/nostrify';
import { useQueryClient } from '@tanstack/react-query';
import { useUploadFile } from '@/hooks/useUploadFile';
export const EditProfileForm: React.FC = () => {
export const EditProfileForm = () => {
const queryClient = useQueryClient();
const { user, metadata } = useCurrentUser();
@@ -108,7 +108,7 @@ export const EditProfileForm: React.FC = () => {
// Invalidate queries to refresh the data
queryClient.invalidateQueries({ queryKey: ['logins'] });
queryClient.invalidateQueries({ queryKey: ['author', user.pubkey] });
queryClient.invalidateQueries({ queryKey: ['nostr', 'author', user.pubkey] });
toast({
title: 'Success',
@@ -284,14 +284,14 @@ interface ImageUploadFieldProps {
onUpload: (file: File) => void;
}
const ImageUploadField: React.FC<ImageUploadFieldProps> = ({
const ImageUploadField = ({
field,
label,
placeholder,
description,
previewType,
onUpload,
}) => {
}: ImageUploadFieldProps) => {
const fileInputRef = useRef<HTMLInputElement>(null);
return (
+83
View File
@@ -0,0 +1,83 @@
---
name: file-uploads
description: Upload files (images, media, attachments) from the browser to a Blossom server via the useUploadFile hook, and attach them to Nostr events with NIP-94 imeta tags.
---
# File Uploads on Nostr
This project includes a `useUploadFile` hook that uploads files to Blossom servers and returns NIP-94-compatible tags. Use it whenever a feature needs to accept a user-provided file (avatars, banners, post attachments, etc.).
## The `useUploadFile` Hook
```tsx
import { useUploadFile } from "@/hooks/useUploadFile";
function MyComponent() {
const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile();
const handleUpload = async (file: File) => {
try {
// Returns an array of NIP-94-compatible tags.
// The first tag is the `url` tag; its second element is the file URL.
const tags = await uploadFile(file);
const url = tags[0][1];
// ...use the url
} catch (error) {
// ...handle errors (show a toast, etc.)
}
};
// ...rest of component
}
```
The hook is a TanStack Query mutation, so `isPending` can drive loading UI and `mutateAsync` integrates cleanly with `async`/`await` flows.
## Attaching Files to Events
### Kind 0 (profile metadata)
Use the plain URL in the relevant JSON field:
```ts
const tags = await uploadFile(file);
const url = tags[0][1];
createEvent({
kind: 0,
content: JSON.stringify({ ...existingMetadata, picture: url }),
});
```
### Kind 1 (text notes) and other content events
Append the URL to `content`, and add one `imeta` tag per file. `imeta` carries the NIP-94 metadata (mime type, dimensions, blurhash, etc.) that the uploader returned:
```ts
const tags = await uploadFile(file); // e.g. [["url", "https://..."], ["m", "image/png"], ["dim", "1024x768"], ...]
const url = tags[0][1];
// Flatten the NIP-94 tags into a single imeta tag value.
const imeta = tags.map(([name, value]) => `${name} ${value}`);
createEvent({
kind: 1,
content: `Check this out ${url}`,
tags: [["imeta", ...imeta]],
});
```
Repeat the pattern (one `imeta` tag per file) for multiple attachments.
## Common Patterns
- **Avatar / banner pickers:** wrap an `<input type="file" accept="image/*">` and call `uploadFile` on change; on success, update the relevant profile field and publish a kind 0 event.
- **Post composers:** call `uploadFile` for each selected file before publishing the note, then build `imeta` tags alongside `content`.
- **Progress UI:** use `isPending` from the mutation to disable the submit button and show a spinner or skeleton.
- **Error handling:** wrap `uploadFile` in `try/catch` and surface failures via `useToast` — network and Blossom-server errors are common and should never break the UI.
## Constraints
- The hook requires a logged-in user (Blossom auth is signed by the user's signer). Guard uploads behind `useCurrentUser`.
- Don't store or display raw `File` objects after upload — always use the returned URL.
- Large files may take time; prefer `mutateAsync` over `mutate` so the caller can `await` completion before publishing an event that references the URL.
+112
View File
@@ -0,0 +1,112 @@
---
name: lockdown-mode
description: Apple Lockdown Mode restrictions and their impact on web APIs inside WKWebView/Safari/WebView. Reference when debugging or building features for lockdown-enabled devices.
---
# Apple Lockdown Mode
Apple's Lockdown Mode is an opt-in security hardening profile that disables or restricts many web platform APIs inside Safari and WKWebView. Since this app ships inside a Capacitor WKWebView shell, **every restriction that applies to Safari also applies to our app**.
## Platform Availability
Lockdown Mode is available on:
- **iOS 16** or later (iPhone)
- **iPadOS 16** or later (iPad)
- **watchOS 10** or later (Apple Watch)
- **macOS Ventura** or later (Mac)
Additional protections are available starting in iOS 17, iPadOS 17, watchOS 10, and macOS Sonoma.
For full details, see [About Lockdown Mode](https://support.apple.com/en-us/105120) on Apple Support.
## Testing Baseline
This document is based on testing against **iOS 18.7 / Safari 26.4** on an iPhone with Lockdown Mode enabled (April 2026). The web API restrictions documented below apply to Safari and WKWebView across all supported platforms (iOS, iPadOS, and macOS).
## Blocked APIs
These APIs are **completely unavailable** (return `undefined`, `null`, or throw) when Lockdown Mode is active.
| API | Impact | Notes |
|-----|--------|-------|
| **IndexedDB** | Critical | `indexedDB` global is missing entirely. Any library that relies on IndexedDB for storage will fail (Dexie, idb, localForage with IndexedDB driver, etc.). |
| **Service Workers** | High | `navigator.serviceWorker` is absent. No offline caching, no background sync, no push notifications via SW. |
| **Cache API** | High | `caches` global is absent. Often used alongside Service Workers for offline strategies. |
| **WebAssembly** | High | `WebAssembly` global is `undefined`. Libraries compiled to WASM (e.g. libsodium-wrappers, secp256k1-wasm, SQLite WASM) will not load. |
| **Web Locks** | High | `navigator.locks` is absent. Cross-tab coordination patterns that depend on this will break silently. |
| **WebRTC** | High | `RTCPeerConnection` is absent. No peer-to-peer audio/video/data channels. |
| **WebGL / WebGL2** | Medium | All canvas `getContext('webgl'*)` calls return `null`. GPU-accelerated rendering, maps (Mapbox GL, deck.gl), and 3D are broken. |
| **FileReader** | Medium | `FileReader` constructor is absent. Cannot read `Blob`/`File` objects client-side (e.g. image preview before upload). Use the `File` constructor + `URL.createObjectURL()` as a workaround for previews. |
| **SharedArrayBuffer** | Medium | `SharedArrayBuffer` is `undefined`. May also require COOP/COEP headers on non-lockdown browsers, so this is often already unavailable. |
| **Speech Synthesis** | Low | `window.speechSynthesis` is absent. Text-to-speech features won't work. |
| **Notifications API** | Low | `Notification` is absent. Web push permission prompts won't appear. (Capacitor local notifications via the native plugin are unaffected.) |
| **WebCodecs** | Low | `VideoDecoder` / `VideoEncoder` are absent (`AudioDecoder` remains). Low-level media processing is unavailable. |
| **Gamepad API** | Low | `navigator.getGamepads` is absent. |
| **OPFS** | Medium | `navigator.storage.getDirectory` method does not exist. The `navigator.storage` object is present but the Origin Private File System API is stripped. SQLite-over-OPFS and any other OPFS-based storage will fail. |
| **Web Share API** | Low | `navigator.share` is absent. Use Capacitor's `@capacitor/share` plugin instead -- the native share sheet still works. |
## Available APIs
These APIs **still work** under Lockdown Mode and can be relied on.
| API | Notes |
|-----|-------|
| **File constructor** | `new File(...)` works. You can create File/Blob objects. |
| **FontFace API** | Dynamic font loading via `new FontFace()` succeeds. Remote font fetches may fail with a network error (data URIs rejected). |
| **JIT compilation** | JavaScript JIT appears active (~110ms for 1M iterations). Performance is not interpreter-level degraded. |
| **PDF viewer** | `navigator.pdfViewerEnabled` is `true`. Inline `<embed type="application/pdf">` works. |
| **Cookies** | `navigator.cookieEnabled` is `true`. |
| **Credential Management** | `navigator.credentials` is available. |
| **localStorage / sessionStorage** | Standard Web Storage APIs remain functional. |
## Implications for This App
### Storage
- **localStorage works** -- our primary client-side storage (app config, relay lists, etc.) is unaffected.
- **IndexedDB is gone** -- if any dependency silently uses IndexedDB (e.g. some Nostr caching layers, TanStack Query persisters), it will fail. Ensure all storage paths fall back to localStorage or in-memory.
- **OPFS is gone** -- `navigator.storage.getDirectory` is stripped (the method doesn't exist, though the `navigator.storage` object itself remains). SQLite-over-OPFS (e.g. wa-sqlite, sql.js with OPFS backend) and any other OPFS-based persistence will not work.
### Cryptography
- **WebAssembly is blocked** -- any WASM-based crypto libraries (secp256k1 compiled to WASM, libsodium WASM builds) will not load. Use pure-JS implementations (e.g. `@noble/secp256k1`, `@noble/hashes`) which are already what nostr-tools uses.
- **WebCrypto (`crypto.subtle`)** -- not listed as blocked in testing. The SubtleCrypto API should still be available for NIP-44 encryption via the standard Web Crypto path.
### Media & Rendering
- **WebGL is gone** -- map libraries that require WebGL (Mapbox GL JS, Google Maps WebGL renderer) will show blank canvases. Use raster tile alternatives or static map images.
- **FileReader is gone** -- image/file preview workflows that use `FileReader.readAsDataURL()` need a workaround. Use `URL.createObjectURL(file)` directly for `<img src>` previews instead.
### Communication
- **WebRTC is gone** -- any peer-to-peer features (voice/video calls, WebRTC data channels) are completely unavailable.
- **Fetch / XMLHttpRequest** -- standard network requests appear unaffected. Relay WebSocket connections should work normally.
### Native Plugin Workarounds
Several blocked web APIs have Capacitor plugin equivalents that bypass WKWebView restrictions entirely:
| Blocked Web API | Capacitor Alternative |
|---|---|
| Web Share | `@capacitor/share` (already installed) |
| Notifications | `@capacitor/local-notifications` (already installed) |
| File downloads | `@capacitor/filesystem` + share (already implemented in `downloadFile.ts`) |
### Detection
The report used a scoring heuristic (8/12 key APIs blocked = 70%) to detect Lockdown Mode. There is no official API to query Lockdown Mode status. Detection relies on probing for the absence of multiple APIs that are specifically disabled by Lockdown Mode but normally present in Safari.
## Raw Diagnostic Report
For exact error messages, navigator properties, weight scores, and per-API diagnostic output, see [ios-report.txt](ios-report.txt).
## Guidance for Feature Decisions
When building new features, consider:
1. **Always provide pure-JS fallbacks** for any crypto or data-processing library that might ship a WASM build.
2. **Never depend on IndexedDB or OPFS** as the sole storage mechanism. Both are completely stripped. Always fall back to localStorage or in-memory stores.
3. **Avoid WebGL-dependent UI** for core functionality. Use it as a progressive enhancement with a CSS/Canvas 2D fallback.
4. **Use Capacitor plugins** for sharing, notifications, and file operations rather than web APIs -- they work on all native platforms regardless of Lockdown Mode.
5. **Test on a Lockdown Mode device** when shipping features that touch storage, crypto, or media APIs.
+229
View File
@@ -0,0 +1,229 @@
============================================================
LOCKDOWN MODE DETECTOR REPORT
2026-04-06T23:40:58.170Z
============================================================
VERDICT: Lockdown Mode Likely Active
8 of 12 key APIs are blocked, consistent with iOS/macOS Lockdown Mode.
Score: 70% (8/12 key APIs blocked)
============================================================
API TEST RESULTS (detailed)
============================================================
------------------------------------------------------------
[BLOCKED] IndexedDB (weight: 3)
Client-side structured storage
Result: Can't find variable: indexedDB
Diagnostics:
uncaught: Can't find variable: indexedDB
------------------------------------------------------------
[BLOCKED] WebAssembly (weight: 2)
Binary instruction execution
Result: WebAssembly is undefined
Diagnostics:
typeof WebAssembly: undefined
WebAssembly global does not exist
------------------------------------------------------------
[BLOCKED] Web Locks API (weight: 3)
Cross-tab resource coordination
Result: navigator.locks is undefined
Diagnostics:
typeof navigator.locks: undefined
'locks' in navigator: false
navigator.locks is falsy
------------------------------------------------------------
[BLOCKED] Speech Synthesis (weight: 3)
Web Speech API (text-to-speech)
Result: window.speechSynthesis is undefined
Diagnostics:
typeof window.speechSynthesis: undefined
'speechSynthesis' in window: false
typeof SpeechSynthesisUtterance: undefined
speechSynthesis is falsy
------------------------------------------------------------
[BLOCKED] FileReader API (weight: 2)
Local file reading interface
Result: FileReader is undefined
Diagnostics:
typeof FileReader: undefined
FileReader constructor does not exist
------------------------------------------------------------
[AVAILABLE] File Constructor (weight: 2)
File object creation
Result: File created: name=test.txt size=4
Diagnostics:
typeof File: function
calling new File(['test'], 'test.txt', {type:'text/plain'})...
succeeded
f.name: test.txt
f.size: 4
f.type: text/plain
f instanceof Blob: true
------------------------------------------------------------
[BLOCKED] WebGL (weight: 2)
GPU-accelerated graphics
Result: all WebGL contexts returned null
Diagnostics:
getContext('webgl2'): null
getContext('webgl'): null
getContext('experimental-webgl'): null
------------------------------------------------------------
[BLOCKED] WebGL2 (weight: 1)
Advanced GPU graphics context
Result: getContext('webgl2') returned null
Diagnostics:
getContext('webgl2'): null
------------------------------------------------------------
[BLOCKED] Service Worker (weight: 1)
Background script registration
Result: navigator.serviceWorker not present
Diagnostics:
'serviceWorker' in navigator: false
typeof navigator.serviceWorker: undefined
------------------------------------------------------------
[BLOCKED] Web Share API (weight: 0)
Native sharing interface
Result: navigator.share is undefined
Diagnostics:
typeof navigator.share: undefined
typeof navigator.canShare: undefined
------------------------------------------------------------
[BLOCKED] Gamepad API (weight: 1)
Game controller input
Result: navigator.getGamepads not present
Diagnostics:
'getGamepads' in navigator: false
------------------------------------------------------------
[BLOCKED] WebRTC (weight: 2)
Real-time peer communication
Result: RTCPeerConnection is undefined
Diagnostics:
typeof RTCPeerConnection: undefined
typeof webkitRTCPeerConnection: undefined
------------------------------------------------------------
[AVAILABLE] FontFace API (weight: 1)
Dynamic font loading
Result: status: loaded
Diagnostics:
typeof FontFace: function
new FontFace() succeeded
ff.status: unloaded
ff.family: test
ff.status after load: loaded
------------------------------------------------------------
[AVAILABLE] Remote Fonts (weight: 2)
Loading fonts from network via data URI
Result: API works, load rejected: A network error occurred.
Diagnostics:
FontFace created with data URI
ff.status before load: unloaded
caught: DOMException: A network error occurred.
------------------------------------------------------------
[AVAILABLE] JIT Compilation (weight: 2)
JavaScript JIT optimization heuristic
Result: 99.0ms for 1M iterations (JIT likely)
Diagnostics:
running 1,000,000 iterations of Math.sqrt*Math.sin...
elapsed: 99.00ms
sum (to prevent dead-code elimination): -681.7597
threshold: <150ms suggests JIT active
verdict: likely JIT
------------------------------------------------------------
[BLOCKED] Notifications API (weight: 1)
Push notification permission
Result: Notification not in window
Diagnostics:
'Notification' in window: false
typeof Notification: undefined
------------------------------------------------------------
[BLOCKED] WebCodecs (weight: 1)
Low-level VideoDecoder API
Result: VideoDecoder is undefined
Diagnostics:
typeof VideoDecoder: undefined
typeof VideoEncoder: undefined
typeof AudioDecoder: function
------------------------------------------------------------
[AVAILABLE] PDF Embed (weight: 2)
Inline PDF rendering via embed/pdfViewerEnabled
Result: pdfViewerEnabled is true
Diagnostics:
navigator.pdfViewerEnabled: true
typeof navigator.pdfViewerEnabled: boolean
created and appended <embed type=application/pdf>
navigator.mimeTypes['application/pdf']: [object MimeType]
------------------------------------------------------------
[BLOCKED] SharedArrayBuffer (weight: 1)
Shared memory between workers
Result: SharedArrayBuffer is undefined
Diagnostics:
typeof SharedArrayBuffer: undefined
requires COOP/COEP headers to be present; may not indicate Lockdown Mode specifically
------------------------------------------------------------
[BLOCKED] Cache API (weight: 1)
Programmatic HTTP cache (CacheStorage)
Result: caches not in window
Diagnostics:
'caches' in window: false
typeof caches: undefined
------------------------------------------------------------
[BLOCKED] OPFS (weight: 2)
Origin Private File System (navigator.storage.getDirectory)
Result: navigator.storage.getDirectory is not a function
Diagnostics:
typeof navigator.storage: object
typeof navigator.storage.getDirectory: undefined
getDirectory method does not exist
============================================================
NAVIGATOR INFO
============================================================
userAgent: Mozilla/5.0 (iPhone; CPU iPhone OS 18_7 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/26.4 Mobile/15E148 Safari/604.1
platform: iPhone
vendor: Apple Computer, Inc.
language: en-US
languages: en-US
cookieEnabled: true
doNotTrack: null
maxTouchPoints: 5
hardwareConcurrency: 4
deviceMemory: N/A
pdfViewerEnabled: true
webdriver: false
connection: unavailable
mediaDevices: unavailable
storage: available
serviceWorker: unavailable
credentials: available
bluetooth: unavailable
gpu (WebGPU): unavailable
screenWidth: 393
screenHeight: 852
devicePixelRatio: 3
colorDepth: 24
============================================================
END OF REPORT
============================================================
+146
View File
@@ -0,0 +1,146 @@
---
name: nip19-routing
description: Implement or populate the root-level NIP-19 router (/:nip19) that handles npub, nprofile, note, nevent, and naddr identifiers. Covers decoding, secure filter construction, and type-specific rendering for profiles, notes, events, and addressable events.
---
# NIP-19 Identifier Routing
NIP-19 defines the bech32-encoded identifiers used throughout Nostr (`npub1...`, `note1...`, `naddr1...`, etc.). This project routes all of them through a single root-level page at `/:nip19`, implemented by `src/pages/NIP19Page.tsx`.
Use this skill when the user wants to populate the `NIP19Page` sections with real views, add a new identifier type, or build links that point into the Nostr routing system.
## Identifier Reference
| Prefix | Payload | Use when… |
|--------------|------------------------------------------------------------------|--------------------------------------------------------------|
| `npub1` | 32-byte public key | Simple user reference |
| `nprofile1` | Public key + optional relay hints + petname | User reference with relay context |
| `note1` | 32-byte event ID (kind:1 text notes only, per NIP-10) | Referencing a short text note/thread |
| `nevent1` | Event ID + optional relay hints + author pubkey + kind | Any event kind, or notes where you need relay/author context |
| `naddr1` | `kind` + `pubkey` + `identifier` (`d` tag) + optional relay hints | Addressable events (kind 30000-39999): articles, products |
| `nsec1` | Private key | **Never display or route** — treat as a 404 |
| `nrelay1` | Relay URL | Deprecated |
### `note1` vs `nevent1`
- `note1` carries only an event ID, and is canonically tied to kind:1 text notes.
- `nevent1` can reference **any** kind and can carry relay hints + author pubkey. Prefer `nevent1` for non-kind-1 events or when you want to ship relay hints with a link.
### `npub1` vs `nprofile1`
- `npub1` is just a pubkey.
- `nprofile1` adds relay hints and a petname. Prefer it for shareable profile links where discoverability matters.
## Routing Rules
1. **All NIP-19 identifiers are handled at the URL root**: `/:nip19` in `AppRouter.tsx`. Never nest them under paths like `/note/:id` or `/profile/:npub`.
2. **Invalid, vacant, or unsupported identifiers** (including `nsec1` and `nrelay1`) render the 404 page. The `NIP19Page` boilerplate already handles this.
3. **Addressable event URLs must include the author**. `naddr1` already encodes `pubkey` + `kind` + `identifier`, which is exactly what a secure query filter needs. If you ever design an alternative URL, use the shape `/:npub/:dtag`, never `/:dtag` alone — otherwise anyone can publish a conflicting event with the same `d` tag.
## Decoding and Filtering
Nostr relay filters only accept hex strings. Always decode the NIP-19 identifier before building a filter.
```ts
import { nip19 } from 'nostr-tools';
const decoded = nip19.decode(value); // throws on invalid input
switch (decoded.type) {
case 'npub': {
const pubkey = decoded.data; // hex string
return nostr.query([{ kinds: [0], authors: [pubkey], limit: 1 }]);
}
case 'nprofile': {
const { pubkey /*, relays */ } = decoded.data;
return nostr.query([{ kinds: [0], authors: [pubkey], limit: 1 }]);
}
case 'note': {
const id = decoded.data;
return nostr.query([{ ids: [id], kinds: [1], limit: 1 }]);
}
case 'nevent': {
const { id /*, relays, author, kind */ } = decoded.data;
return nostr.query([{ ids: [id], limit: 1 }]);
}
case 'naddr': {
const { kind, pubkey, identifier } = decoded.data;
return nostr.query([{
kinds: [kind],
authors: [pubkey], // critical: prevents d-tag spoofing
'#d': [identifier],
limit: 1,
}]);
}
default:
// nsec, nrelay, unknown → 404
throw new Error('Unsupported Nostr identifier');
}
```
### Common mistakes
```ts
// ❌ Passing bech32 into a filter
nostr.query([{ ids: [naddr] }]);
// ❌ Addressable lookup without the author — anyone can spoof the d-tag
nostr.query([{ kinds: [30023], '#d': [slug] }]);
// ✅ Decode first, then include author
const { kind, pubkey, identifier } = nip19.decode(naddr).data;
nostr.query([{ kinds: [kind], authors: [pubkey], '#d': [identifier] }]);
```
## Populating `NIP19Page`
`src/pages/NIP19Page.tsx` already:
- Decodes `params.nip19` with `nip19.decode`.
- Branches on `decoded.type` with a section for each supported identifier.
- Redirects invalid / unsupported identifiers to the 404 page.
- Provides a responsive container wrapper.
To turn it into a real router, replace each placeholder section with a concrete component:
| `decoded.type` | Typical view |
|-----------------------|---------------------------------------------------------------|
| `npub` / `nprofile` | Profile page: header from kind 0, feed of the user's events |
| `note` | Single kind:1 text note with thread + replies |
| `nevent` | Generic event renderer; branch on `kind` for specialized UIs |
| `naddr` | Addressable-event view (article, product, community, etc.) |
Inside each branch, pass the decoded payload (not the raw bech32 string) to a child component. That keeps filter construction colocated with the fetching hook and removes any chance of a re-decode mismatch.
## Linking to NIP-19 Routes
When building links elsewhere in the app:
```tsx
import { nip19 } from 'nostr-tools';
import { Link } from 'react-router-dom';
// To a profile
<Link to={`/${nip19.npubEncode(pubkey)}`}>Profile</Link>
// To an addressable event (article, product, …)
<Link to={`/${nip19.naddrEncode({ kind, pubkey, identifier, relays })}`}>
Open
</Link>
// To a specific event of any kind, with relay hints
<Link to={`/${nip19.neventEncode({ id, relays, author, kind })}`}>Open</Link>
```
Always encode with the **most specific** identifier you have context for (`nprofile` > `npub`, `nevent` > `note`, `naddr` for addressable). The extra metadata makes links more robust across relays.
## Security Recap
- Decode **before** querying.
- For addressable events, always include `authors: [pubkey]` in the filter — the `d` tag alone is not a trust boundary.
- Treat `nsec1` and any unknown/invalid identifier as 404. Never render, log, or echo a decoded `nsec`.
+190
View File
@@ -0,0 +1,190 @@
---
name: nip85-stats
description: Fetch pre-computed engagement stats (follower count, post count, reply count, reaction count, zap amounts, etc.) for users, events, and addressable events via a NIP-85 Trusted Assertion provider. Provides useNip85UserStats, useNip85EventStats, and useNip85AddrStats hooks backed by a configurable provider pubkey in AppConfig.
---
# NIP-85 Trusted Assertion Stats
[NIP-85](https://github.com/nostr-protocol/nips/blob/master/85.md) defines "Trusted Assertions" — events published by a service provider that carry pre-computed stats (follower counts, reaction counts, zap totals, etc.) for users and events. Clients that would otherwise need to load thousands of events to compute these numbers can instead query a single addressable event from a trusted provider.
This skill adds three hooks — `useNip85UserStats`, `useNip85EventStats`, `useNip85AddrStats` — and a configurable `nip85StatsPubkey` field on `AppConfig` so you can swap providers.
## Kinds Used
| Kind | Subject | `d` tag value |
| ----- | ---------------------------- | -------------------------- |
| 30382 | User | user pubkey (hex) |
| 30383 | Event (regular, kind 1 etc.) | event id (hex) |
| 30384 | Addressable event | `<kind>:<pubkey>:<d-tag>` |
The hooks query one replaceable event at a time (`limit: 1`), filtered by `authors: [statsPubkey]` and `#d`. **Filtering by `authors` is required** — without it, anyone could publish a fake assertion with the same `d` tag and the client would accept it.
## Files Provided by This Skill
| Skill file | Copy to |
|---|---|
| `files/hooks/useNip85Stats.ts` | `src/hooks/useNip85Stats.ts` |
## Setup Instructions
### 1. Copy the Hooks File
Copy `.agents/skills/nip85-stats/files/hooks/useNip85Stats.ts` into `src/hooks/useNip85Stats.ts`. It imports `@nostrify/react`, `@tanstack/react-query`, and `@/hooks/useAppContext`, all already present in the template.
### 2. Add `nip85StatsPubkey` to `AppConfig`
In `src/contexts/AppContext.ts`, add the field to the `AppConfig` interface:
```typescript
export interface AppConfig {
// ...existing fields...
/** Hex pubkey of the NIP-85 Trusted Assertion provider. Empty = disabled. */
nip85StatsPubkey: string;
}
```
### 3. Update the Zod Schema in `AppProvider.tsx`
In `src/components/AppProvider.tsx`, add the field to `AppConfigSchema`:
```typescript
const AppConfigSchema = z.object({
// ...existing fields...
nip85StatsPubkey: z.string().refine(
(val) => val.length === 0 || /^[0-9a-f]{64}$/i.test(val),
{ message: 'Must be empty or a 64-character hex pubkey' },
),
}) satisfies z.ZodType<AppConfig>;
```
### 4. Set the Default in `App.tsx`
Pick a provider pubkey and add it to `defaultConfig`. The ditto.pub provider is a reasonable default:
```typescript
const defaultConfig: AppConfig = {
// ...existing fields...
nip85StatsPubkey: '5f68e85ee174102ca8978eef302129f081f03456c884185d5ec1c1224ab633ea',
};
```
Set to `''` to ship with stats disabled.
### 5. Update `TestApp.tsx`
In `src/test/TestApp.tsx`, add the field to the test default config. Use an empty string so tests don't hit a live provider:
```typescript
const defaultConfig: AppConfig = {
// ...existing fields...
nip85StatsPubkey: '',
};
```
## Usage
### User stats (kind 30382)
```tsx
import { useNip85UserStats } from '@/hooks/useNip85Stats';
function FollowerCount({ pubkey }: { pubkey: string }) {
const { data: stats } = useNip85UserStats(pubkey);
if (!stats) return null; // no provider configured or no assertion yet
return <span>{stats.followers.toLocaleString()} followers</span>;
}
```
### Event stats (kind 30383)
```tsx
import { useNip85EventStats } from '@/hooks/useNip85Stats';
function NoteStats({ eventId }: { eventId: string }) {
const { data: stats } = useNip85EventStats(eventId);
if (!stats) return null;
return (
<div className="flex gap-3 text-sm text-muted-foreground">
<span>{stats.reactionCount} reactions</span>
<span>{stats.repostCount} reposts</span>
<span>{stats.commentCount} comments</span>
<span>{stats.zapAmount} sats</span>
</div>
);
}
```
### Addressable event stats (kind 30384)
The `addr` argument is the full NIP-01 event address `<kind>:<pubkey>:<d-tag>`:
```tsx
import { useNip85AddrStats } from '@/hooks/useNip85Stats';
function ArticleStats({ kind, pubkey, identifier }: { kind: number; pubkey: string; identifier: string }) {
const { data: stats } = useNip85AddrStats(`${kind}:${pubkey}:${identifier}`);
if (!stats) return null;
return <span>{stats.reactionCount} reactions</span>;
}
```
## Behavior Notes
- **Graceful degradation:** The hooks return `null` (not an error) when `nip85StatsPubkey` is empty or the provider has no assertion for the subject. Always render defensively — NIP-85 is an optimization, not a source of truth.
- **Short timeouts:** Each query is wrapped in a 2-second `AbortSignal.timeout` so a slow stats relay never blocks the UI.
- **Cached by TanStack Query:** `staleTime` is 30s for event/addr stats and 60s for user stats. Results are keyed on `[kind, subject, statsPubkey]`, so swapping providers invalidates the cache automatically.
- **Missing tags = 0:** A tag absent from the assertion is reported as `0` rather than `undefined`, matching NIP-85's "no data" semantics.
- **Not the source of truth:** For interactive features (did *this* user like *this* post?) you still need to query the underlying reaction/zap/repost events. NIP-85 only provides aggregate counts.
## Extending the Stats
The hooks expose a small subset of the tags defined in NIP-85. To surface more (e.g. `zap_amt_sent`, `rank`, `first_created_at`), extend the return types and pull additional tags via `getIntTag`:
```typescript
export interface Nip85UserStats {
followers: number;
postCount: number;
rank: number; // new
zapAmtReceived: number; // new
}
// inside useNip85UserStats queryFn
return {
followers: getIntTag(tags, 'followers'),
postCount: getIntTag(tags, 'post_cnt'),
rank: getIntTag(tags, 'rank'),
zapAmtReceived: getIntTag(tags, 'zap_amt_recd'),
};
```
See the full tag table in [NIP-85](https://github.com/nostr-protocol/nips/blob/master/85.md).
## Exposing a Provider Picker (Optional)
If you want the user to change providers at runtime, add an input bound to `config.nip85StatsPubkey` and call `updateConfig` with a validated 64-char hex value:
```tsx
import { useAppContext } from '@/hooks/useAppContext';
function StatsProviderInput() {
const { config, updateConfig } = useAppContext();
return (
<input
value={config.nip85StatsPubkey}
onChange={(e) => {
const v = e.target.value.trim().toLowerCase();
if (v === '' || /^[0-9a-f]{64}$/.test(v)) {
updateConfig(() => ({ nip85StatsPubkey: v }));
}
}}
placeholder="64-char hex pubkey (blank to disable)"
/>
);
}
```
## Related NIPs
- [NIP-85](https://github.com/nostr-protocol/nips/blob/master/85.md) — Trusted Assertions (this skill)
- [NIP-01](https://github.com/nostr-protocol/nips/blob/master/01.md) — Addressable event addressing (`<kind>:<pubkey>:<d-tag>`)
- [NIP-57](https://github.com/nostr-protocol/nips/blob/master/57.md) — Zaps (the underlying events `zap_amount` / `zap_cnt` aggregate)
@@ -0,0 +1,156 @@
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
import { useAppContext } from '@/hooks/useAppContext';
/** Engagement counts exposed by NIP-85 kind 30383 (events) and 30384 (addressable events). */
export interface Nip85EventStats {
commentCount: number;
repostCount: number;
reactionCount: number;
zapCount: number;
/** Zap amount in sats. */
zapAmount: number;
}
/** A subset of NIP-85 kind 30382 (user) stats — extend as needed. */
export interface Nip85UserStats {
followers: number;
postCount: number;
}
/**
* Read an integer tag value from a NIP-85 assertion event. Returns 0 when missing
* or unparseable, which mirrors the semantics of "no data" in NIP-85.
*/
function getIntTag(tags: string[][], tagName: string): number {
const tag = tags.find(([name]) => name === tagName);
if (!tag?.[1]) return 0;
const n = parseInt(tag[1], 10);
return Number.isFinite(n) ? n : 0;
}
/**
* Fetches NIP-85 event stats (kind 30383) from the configured stats pubkey.
* Returns `null` when no stats pubkey is configured or the provider has no
* assertion for this event.
*/
export function useNip85EventStats(eventId: string | undefined) {
const { nostr } = useNostr();
const { config } = useAppContext();
const statsPubkey = config.nip85StatsPubkey;
return useQuery<Nip85EventStats | null>({
queryKey: ['nip85-event-stats', eventId, statsPubkey],
queryFn: async ({ signal }) => {
if (!eventId || !statsPubkey) return null;
const combined = AbortSignal.any([signal, AbortSignal.timeout(2000)]);
try {
const events = await nostr.query(
[{ kinds: [30383], authors: [statsPubkey], '#d': [eventId], limit: 1 }],
{ signal: combined },
);
if (events.length === 0) return null;
const { tags } = events[0];
return {
commentCount: getIntTag(tags, 'comment_cnt'),
repostCount: getIntTag(tags, 'repost_cnt'),
reactionCount: getIntTag(tags, 'reaction_cnt'),
zapCount: getIntTag(tags, 'zap_cnt'),
zapAmount: getIntTag(tags, 'zap_amount'),
};
} catch {
return null;
}
},
enabled: !!eventId && !!statsPubkey,
staleTime: 30 * 1000,
retry: false,
});
}
/**
* Fetches NIP-85 user stats (kind 30382) from the configured stats pubkey.
* Returns `null` when no stats pubkey is configured or the provider has no
* assertion for this pubkey.
*/
export function useNip85UserStats(pubkey: string | undefined) {
const { nostr } = useNostr();
const { config } = useAppContext();
const statsPubkey = config.nip85StatsPubkey;
return useQuery<Nip85UserStats | null>({
queryKey: ['nip85-user-stats', pubkey, statsPubkey],
queryFn: async ({ signal }) => {
if (!pubkey || !statsPubkey) return null;
const combined = AbortSignal.any([signal, AbortSignal.timeout(2000)]);
try {
const events = await nostr.query(
[{ kinds: [30382], authors: [statsPubkey], '#d': [pubkey], limit: 1 }],
{ signal: combined },
);
if (events.length === 0) return null;
const { tags } = events[0];
return {
followers: getIntTag(tags, 'followers'),
postCount: getIntTag(tags, 'post_cnt'),
};
} catch {
return null;
}
},
enabled: !!pubkey && !!statsPubkey,
staleTime: 60 * 1000,
retry: false,
});
}
/**
* Fetches NIP-85 addressable event stats (kind 30384) from the configured
* stats pubkey. The `addr` argument is the full NIP-01 event address string,
* e.g. `30023:<pubkey>:<d-tag>`.
*/
export function useNip85AddrStats(addr: string | undefined) {
const { nostr } = useNostr();
const { config } = useAppContext();
const statsPubkey = config.nip85StatsPubkey;
return useQuery<Nip85EventStats | null>({
queryKey: ['nip85-addr-stats', addr, statsPubkey],
queryFn: async ({ signal }) => {
if (!addr || !statsPubkey) return null;
const combined = AbortSignal.any([signal, AbortSignal.timeout(2000)]);
try {
const events = await nostr.query(
[{ kinds: [30384], authors: [statsPubkey], '#d': [addr], limit: 1 }],
{ signal: combined },
);
if (events.length === 0) return null;
const { tags } = events[0];
return {
commentCount: getIntTag(tags, 'comment_cnt'),
repostCount: getIntTag(tags, 'repost_cnt'),
reactionCount: getIntTag(tags, 'reaction_cnt'),
zapCount: getIntTag(tags, 'zap_cnt'),
zapAmount: getIntTag(tags, 'zap_amount'),
};
} catch {
return null;
}
},
enabled: !!addr && !!statsPubkey,
staleTime: 30 * 1000,
retry: false,
});
}
+207
View File
@@ -0,0 +1,207 @@
---
name: nostr-comments
description: Implement Nostr comment systems, add discussion features to posts/articles, build community interaction features, or attach comments to any external content identifier including URLs, hashtags, and NIP-73 identifiers (ISBN, podcast GUIDs, geohashes, movie ISANs, blockchain transactions, and more).
---
# Adding Nostr Comments Sections
This skill provides a complete commenting system using NIP-22 (kind 1111) comments that can be added to any Nostr event, URL, hashtag, or NIP-73 external content identifier. The `CommentsSection` component renders a lightweight, inline commenting interface with threaded replies, user authentication, and a per-comment actions menu (Open in Ditto, Delete own comment).
**The comment system is not included in the project by default.** When the user wants comment functionality, follow the setup instructions below to install the files.
## Files Provided by This Skill
All files live under `.agents/skills/nostr-comments/files/` and must be copied into `src/` preserving the directory structure:
| Skill file | Copy to |
|---|---|
| `files/hooks/useComments.ts` | `src/hooks/useComments.ts` |
| `files/hooks/usePostComment.ts` | `src/hooks/usePostComment.ts` |
| `files/components/comments/Comment.tsx` | `src/components/comments/Comment.tsx` |
| `files/components/comments/CommentForm.tsx` | `src/components/comments/CommentForm.tsx` |
| `files/components/comments/CommentsSection.tsx` | `src/components/comments/CommentsSection.tsx` |
## Setup Instructions
### 1. Dependencies
No extra npm packages are required — the skill uses only packages already present in the template (`@nostrify/nostrify`, `@nostrify/react`, `@tanstack/react-query`, `nostr-tools`, `date-fns`, `lucide-react`, `react-router-dom`, and shadcn/ui components).
### 2. Copy the Skill Files Into `src/`
Copy every file listed in the table above from `.agents/skills/nostr-comments/files/` into its corresponding location under `src/`. Preserve the exact paths — the files use `@/hooks/...` and `@/components/...` imports that depend on these locations.
### 3. Required Project Components
The comment components depend on pieces that already ship with the template:
- `@/components/NoteContent` — renders comment text (used by `Comment.tsx`)
- `@/components/auth/LoginArea` — shown to logged-out users (used by `CommentForm.tsx`)
- `@/components/ui/alert-dialog` — confirms deletion (used by `Comment.tsx`)
- `@/hooks/useAuthor` — fetches comment author profile (used by `Comment.tsx`)
- `@/hooks/useCurrentUser` — determines whether to show the composer and the Delete action (used by `CommentForm.tsx`, `Comment.tsx`)
- `@/hooks/useNostrPublish` — publishes kind 1111 comments and kind 5 deletion requests (used by `usePostComment.ts`, `Comment.tsx`)
- `@/hooks/useToast` — user feedback on delete success/failure (used by `Comment.tsx`)
All of these are standard in the template; no extra work is needed beyond copying the skill files.
## Basic Usage
`CommentsSection` renders without an outer card, title, or header — it's just the composer followed by the threaded comment list. Wrap it in whatever page layout you want:
```tsx
import { CommentsSection } from "@/components/comments/CommentsSection";
function ArticlePage({ article }: { article: NostrEvent }) {
return (
<div className="space-y-6">
{/* Your article content */}
<div>{/* article content */}</div>
{/* Comments section — add your own heading if needed */}
<section className="space-y-4">
<h2 className="text-lg font-semibold">Comments</h2>
<CommentsSection root={article} />
</section>
</div>
);
}
```
## Per-Comment Actions Menu
Each comment has a 3-dots menu with:
- **Open in Ditto** — opens the comment at `https://ditto.pub/<nevent>` in a new tab so users can view replies, react, or zap via Ditto.
- **Delete** — only shown when the logged-in user is the comment's author. Publishes a NIP-09 (kind 5) deletion request tagging the comment's `id` and `kind`, then optimistically removes the comment from the cached query result via `queryClient.setQueriesData`. Deletion is not guaranteed across the network — the `AlertDialog` confirmation makes this clear to the user.
## Props and Customization
The `CommentsSection` component accepts the following props:
- **`root`** (required): The root to comment on. Accepts three types:
- `NostrEvent` — comment on a Nostr event (kind 1 note, long-form article, etc.)
- `URL` — comment on an external identifier: web URLs (`new URL("https://...")`) or any NIP-73 identifier except hashtags (e.g. `new URL("isbn:9780765382030")`, `new URL("iso3166:US")`)
- `#${string}` — NIP-73 hashtag only (e.g. `"#bitcoin"`); this template string type is exclusively for hashtags and must not be used for other NIP-73 identifiers
- **`emptyStateMessage`**: Message shown when no comments exist (default: "No comments yet")
- **`emptyStateSubtitle`**: Subtitle for empty state (default: "Be the first to share your thoughts!")
- **`className`**: Additional CSS classes applied to the outer `<div>` (it's a plain `space-y-6` container, no card/border)
- **`limit`**: Maximum number of comments to load (default: 500)
```tsx
<CommentsSection
root={event}
emptyStateMessage="Start the conversation"
emptyStateSubtitle="Share your thoughts about this post"
className="mt-8"
limit={100}
/>
```
## Commenting on URLs
The comments system supports commenting on external URLs, making it useful for web pages, articles, or any online content:
```tsx
<CommentsSection
root={new URL("https://example.com/article")}
/>
```
## Commenting on Hashtags
Pass a hashtag string (`#${string}` format) to attach comments to a topic. The hashtag must be lowercase:
```tsx
// Comments for the #bitcoin hashtag
<CommentsSection
root="#bitcoin"
/>
// Comments for a community-specific tag
<CommentsSection
root="#nostr"
/>
```
## Commenting on NIP-73 External Content Identifiers
NIP-73 defines a standard set of external content IDs. All NIP-73 identifiers (except hashtags) are passed as `URL` objects — the identifier string is used directly as the URL:
### Books (ISBN)
```tsx
// ISBN must be without hyphens
<CommentsSection
root={new URL("isbn:9780765382030")}
/>
```
### Podcasts
```tsx
// Podcast feed
<CommentsSection
root={new URL("podcast:guid:c90e609a-df1e-596a-bd5e-57bcc8aad6cc")}
/>
// Podcast episode
<CommentsSection
root={new URL("podcast:item:guid:d98d189b-dc7b-45b1-8720-d4b98690f31f")}
/>
```
### Movies (ISAN)
```tsx
// ISAN without version part
<CommentsSection
root={new URL("isan:0000-0000-401A-0000-7")}
/>
```
### Geohashes
```tsx
// Geohash must be lowercase
<CommentsSection
root={new URL("geo:ezs42e44yx96")}
/>
```
### Countries (ISO 3166)
```tsx
// ISO 3166 codes must be uppercase
<CommentsSection
root={new URL("iso3166:US")}
/>
// Subdivision (state/province)
<CommentsSection
root={new URL("iso3166:US-CA")}
/>
```
### Academic Papers (DOI)
```tsx
// DOI must be lowercase
<CommentsSection
root={new URL("doi:10.1000/xyz123")}
/>
```
### Blockchain Transactions and Addresses
```tsx
// Bitcoin transaction
<CommentsSection
root={new URL("bitcoin:tx:a1075db55d416d3ca199f55b6084e2115b9345e16c5cf302fc80e9d5fbf5d48d")}
/>
// Ethereum address
<CommentsSection
root={new URL("ethereum:1:address:0xd8da6bf26964af9d7eed9e03e53415d37aa96045")}
/>
```
@@ -4,19 +4,45 @@ import { NostrEvent } from '@nostrify/nostrify';
import { nip19 } from 'nostr-tools';
import { useAuthor } from '@/hooks/useAuthor';
import { useComments } from '@/hooks/useComments';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useToast } from '@/hooks/useToast';
import { useQueryClient } from '@tanstack/react-query';
import { CommentForm } from './CommentForm';
import { NoteContent } from '@/components/NoteContent';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible';
import { DropdownMenu, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { MessageSquare, ChevronDown, ChevronRight, MoreHorizontal } from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuSeparator,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
AlertDialog,
AlertDialogAction,
AlertDialogCancel,
AlertDialogContent,
AlertDialogDescription,
AlertDialogFooter,
AlertDialogHeader,
AlertDialogTitle,
} from '@/components/ui/alert-dialog';
import {
MessageSquare,
ChevronDown,
ChevronRight,
MoreHorizontal,
ExternalLink,
Trash2,
} from 'lucide-react';
import { formatDistanceToNow } from 'date-fns';
import { genUserName } from '@/lib/genUserName';
interface CommentProps {
root: NostrEvent | URL;
root: NostrEvent | URL | `#${string}`;
comment: NostrEvent;
depth?: number;
maxDepth?: number;
@@ -26,18 +52,73 @@ interface CommentProps {
export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }: CommentProps) {
const [showReplyForm, setShowReplyForm] = useState(false);
const [showReplies, setShowReplies] = useState(depth < 2); // Auto-expand first 2 levels
const [showDeleteDialog, setShowDeleteDialog] = useState(false);
const author = useAuthor(comment.pubkey);
const { data: commentsData } = useComments(root, limit);
const { user } = useCurrentUser();
const { mutate: publishEvent, isPending: isDeleting } = useNostrPublish();
const { toast } = useToast();
const queryClient = useQueryClient();
const metadata = author.data?.metadata;
const displayName = metadata?.name ?? genUserName(comment.pubkey)
const displayName = metadata?.name ?? 'Anonymous';
const timeAgo = formatDistanceToNow(new Date(comment.created_at * 1000), { addSuffix: true });
const nevent = nip19.neventEncode({ id: comment.id, author: comment.pubkey, kind: comment.kind });
const isOwnComment = user?.pubkey === comment.pubkey;
// Get direct replies to this comment
const replies = commentsData?.getDirectReplies(comment.id) || [];
const hasReplies = replies.length > 0;
const handleDelete = () => {
publishEvent(
{
kind: 5,
content: '',
tags: [
['e', comment.id],
['k', comment.kind.toString()],
],
},
{
onSuccess: () => {
toast({ title: 'Comment deleted' });
setShowDeleteDialog(false);
// Optimistically remove the deleted comment from every cached useComments
// result. Relays may honor the kind 5 deletion request on refetch, but
// that's not guaranteed — this keeps the UI consistent immediately.
queryClient.setQueriesData<ReturnType<typeof useComments>['data']>(
{ queryKey: ['nostr', 'comments'] },
(oldData) => {
if (!oldData) return oldData;
const allComments = oldData.allComments.filter((c) => c.id !== comment.id);
const topLevelComments = oldData.topLevelComments.filter(
(c) => c.id !== comment.id,
);
return {
...oldData,
allComments,
topLevelComments,
getDescendants: (id: string) =>
oldData.getDescendants(id).filter((c) => c.id !== comment.id),
getDirectReplies: (id: string) =>
oldData.getDirectReplies(id).filter((c) => c.id !== comment.id),
};
},
);
},
onError: (error) => {
toast({
title: 'Failed to delete comment',
description: error.message,
variant: 'destructive',
});
},
},
);
};
return (
<div className={`space-y-3 ${depth > 0 ? 'ml-6 border-l-2 border-muted pl-4' : ''}`}>
<Card className="bg-card/50">
@@ -55,7 +136,7 @@ export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }: Comme
</Avatar>
</Link>
<div>
<Link
<Link
to={`/${nip19.npubEncode(comment.pubkey)}`}
className="font-medium text-sm hover:text-primary transition-colors"
>
@@ -83,7 +164,7 @@ export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }: Comme
<MessageSquare className="h-3 w-3 mr-1" />
Reply
</Button>
{hasReplies && (
<Collapsible open={showReplies} onOpenChange={setShowReplies}>
<CollapsibleTrigger asChild>
@@ -112,6 +193,33 @@ export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }: Comme
<MoreHorizontal className="h-3 w-3" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem asChild>
<a
href={`https://ditto.pub/${nevent}`}
target="_blank"
rel="noopener noreferrer"
>
<ExternalLink className="h-3.5 w-3.5 mr-2" />
Open in Ditto
</a>
</DropdownMenuItem>
{isOwnComment && (
<>
<DropdownMenuSeparator />
<DropdownMenuItem
onSelect={(e) => {
e.preventDefault();
setShowDeleteDialog(true);
}}
className="text-destructive focus:text-destructive"
>
<Trash2 className="h-3.5 w-3.5 mr-2" />
Delete
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
@@ -148,6 +256,33 @@ export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }: Comme
</CollapsibleContent>
</Collapsible>
)}
{/* Delete confirmation */}
<AlertDialog open={showDeleteDialog} onOpenChange={setShowDeleteDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle>Delete comment?</AlertDialogTitle>
<AlertDialogDescription>
This publishes a NIP-09 deletion request (kind 5). Relays and clients that
honor deletion requests will hide this comment, but deletion is not
guaranteed across the network.
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel disabled={isDeleting}>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={(e) => {
e.preventDefault();
handleDelete();
}}
disabled={isDeleting}
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
>
{isDeleting ? 'Deleting…' : 'Delete'}
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</div>
);
}
}
@@ -0,0 +1,81 @@
import { useState } from 'react';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { usePostComment } from '@/hooks/usePostComment';
import { LoginArea } from '@/components/auth/LoginArea';
import { NostrEvent } from '@nostrify/nostrify';
import { MessageSquare } from 'lucide-react';
import { cn } from '@/lib/utils';
interface CommentFormProps {
root: NostrEvent | URL | `#${string}`;
reply?: NostrEvent | URL | `#${string}`;
onSuccess?: () => void;
placeholder?: string;
compact?: boolean;
}
export function CommentForm({
root,
reply,
onSuccess,
placeholder = "Write a comment...",
compact = false,
}: CommentFormProps) {
const [content, setContent] = useState('');
const { user } = useCurrentUser();
const { mutate: postComment, isPending } = usePostComment();
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!content.trim() || !user) return;
postComment(
{ content: content.trim(), root, reply },
{
onSuccess: () => {
setContent('');
onSuccess?.();
},
}
);
};
if (!user) {
return (
<div className={cn("rounded-2xl border border-dashed bg-muted/30", compact ? "p-4" : "p-6")}>
<div className="text-center space-y-4">
<div className="flex items-center justify-center space-x-2 text-muted-foreground">
<MessageSquare className="h-5 w-5" />
<span>Sign in to {reply ? 'reply' : 'comment'}</span>
</div>
<LoginArea />
</div>
</div>
);
}
return (
<form onSubmit={handleSubmit} className="space-y-3">
<Textarea
value={content}
onChange={(e) => setContent(e.target.value)}
placeholder={placeholder}
className={cn("rounded-2xl resize-none", compact ? "min-h-[80px]" : "min-h-[100px]")}
disabled={isPending}
/>
<div className="flex justify-end">
<Button
type="submit"
disabled={!content.trim() || isPending}
size={compact ? "sm" : "default"}
className="rounded-full px-6"
>
{isPending ? 'Posting…' : 'Post'}
</Button>
</div>
</form>
);
}
@@ -0,0 +1,74 @@
import { useComments } from '@/hooks/useComments';
import { Skeleton } from '@/components/ui/skeleton';
import { MessageSquare } from 'lucide-react';
import { cn } from '@/lib/utils';
import type { NostrEvent } from '@nostrify/nostrify';
import { CommentForm } from './CommentForm';
import { Comment } from './Comment';
interface CommentsSectionProps {
root: NostrEvent | URL | `#${string}`;
emptyStateMessage?: string;
emptyStateSubtitle?: string;
className?: string;
limit?: number;
}
export function CommentsSection({
root,
emptyStateMessage = "No comments yet",
emptyStateSubtitle = "Be the first to share your thoughts!",
className,
limit = 500,
}: CommentsSectionProps) {
const { data: commentsData, isLoading, error } = useComments(root, limit);
const comments = commentsData?.topLevelComments || [];
if (error) {
return (
<div className={cn("text-center text-muted-foreground py-6", className)}>
<MessageSquare className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p>Failed to load comments</p>
</div>
);
}
return (
<div className={cn("space-y-6", className)}>
<CommentForm root={root} />
{isLoading ? (
<div className="space-y-4">
{[...Array(3)].map((_, i) => (
<div key={i} className="space-y-3">
<div className="flex items-center space-x-3">
<Skeleton className="h-8 w-8 rounded-full" />
<div className="space-y-1">
<Skeleton className="h-4 w-24" />
<Skeleton className="h-3 w-16" />
</div>
</div>
<Skeleton className="h-16 w-full" />
</div>
))}
</div>
) : comments.length === 0 ? (
<div className="text-center py-8 text-muted-foreground">
<MessageSquare className="h-12 w-12 mx-auto mb-4 opacity-30" />
<p className="text-lg font-medium mb-2">{emptyStateMessage}</p>
<p className="text-sm">{emptyStateSubtitle}</p>
</div>
) : (
<div className="space-y-4">
{comments.map((comment) => (
<Comment
key={comment.id}
root={root}
comment={comment}
/>
))}
</div>
)}
</div>
);
}
@@ -2,15 +2,17 @@ import { NKinds, NostrEvent, NostrFilter } from '@nostrify/nostrify';
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
export function useComments(root: NostrEvent | URL, limit?: number) {
export function useComments(root: NostrEvent | URL | `#${string}`, limit?: number) {
const { nostr } = useNostr();
return useQuery({
queryKey: ['comments', root instanceof URL ? root.toString() : root.id, limit],
queryFn: async (c) => {
queryKey: ['nostr', 'comments', root instanceof URL ? root.toString() : typeof root === 'string' ? root : root.id, limit],
queryFn: async () => {
const filter: NostrFilter = { kinds: [1111] };
if (root instanceof URL) {
if (typeof root === 'string') {
filter['#I'] = [root];
} else if (root instanceof URL) {
filter['#I'] = [root.toString()];
} else if (NKinds.addressable(root.kind)) {
const d = root.tags.find(([name]) => name === 'd')?.[1] ?? '';
@@ -26,7 +28,7 @@ export function useComments(root: NostrEvent | URL, limit?: number) {
}
// Query for all kind 1111 comments that reference this addressable event regardless of depth
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
const signal = AbortSignal.timeout(5000);
const events = await nostr.query([filter], { signal });
// Helper function to get tag value
@@ -37,7 +39,9 @@ export function useComments(root: NostrEvent | URL, limit?: number) {
// Filter top-level comments (those with lowercase tag matching the root)
const topLevelComments = events.filter(comment => {
if (root instanceof URL) {
if (typeof root === 'string') {
return getTagValue(comment, 'i') === root;
} else if (root instanceof URL) {
return getTagValue(comment, 'i') === root.toString();
} else if (NKinds.addressable(root.kind)) {
const d = getTagValue(root, 'd') ?? '';
@@ -0,0 +1,93 @@
import { useMutation, useQueryClient } from '@tanstack/react-query';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { NKinds, type NostrEvent } from '@nostrify/nostrify';
interface PostCommentParams {
root: NostrEvent | URL | `#${string}`; // The root event to comment on
reply?: NostrEvent | URL | `#${string}`; // Optional reply to another comment
content: string;
}
/** Post a NIP-22 (kind 1111) comment on an event. */
export function usePostComment() {
const { mutateAsync: publishEvent } = useNostrPublish();
const queryClient = useQueryClient();
return useMutation({
mutationFn: async ({ root, reply, content }: PostCommentParams) => {
const tags: string[][] = [];
// Root event tags
tags.push(...makeCommentTags('root', root));
// Reply event tags
if (reply) {
tags.push(...makeCommentTags('reply', reply));
} else {
// If this is a top-level comment, use the root event's tags
tags.push(...makeCommentTags('reply', root));
}
const event = await publishEvent({
kind: 1111,
content,
tags,
});
return event;
},
onSuccess: (_, { root }) => {
const rootKey = root instanceof URL ? root.toString() : typeof root === 'string' ? root : root.id;
// Invalidate and refetch comments
queryClient.invalidateQueries({
queryKey: ['nostr', 'comments', rootKey]
});
},
});
}
/** Build NIP-22 comment tags for a given scope and target */
function makeCommentTags(scope: 'root' | 'reply', target: NostrEvent | URL | `#${string}`): string[][] {
const tags: string[][] = [];
const d = (typeof target === 'string' || target instanceof URL)
? ''
: target.tags.find(([name]) => name === 'd')?.[1] ?? '';
if (typeof target === 'string') {
tags.push(['I', target]);
} else if (target instanceof URL) {
tags.push(['I', target.toString()]);
} else if (NKinds.addressable(target.kind)) {
tags.push(['A', `${target.kind}:${target.pubkey}:${d}`]);
} else if (NKinds.replaceable(target.kind)) {
tags.push(['A', `${target.kind}:${target.pubkey}:`]);
} else {
tags.push(['E', target.id]);
}
if (typeof target === 'string') {
tags.push(['K', '#']);
} else if (target instanceof URL) {
switch (target.protocol) {
case 'http:':
case 'https:':
tags.push(['K', 'web']);
break;
default:
tags.push(['K', target.protocol.replace(/:$/, '')]);
break;
}
} else {
tags.push(['K', target.kind.toString()]);
tags.push(['P', target.pubkey]);
}
// Lowercase all tag names for reply scope
if (scope === 'reply') {
return tags.map(([name, ...values]) => [name.toLowerCase(), ...values]);
}
// Root scope: uppercase tags
return tags;
}
+81
View File
@@ -0,0 +1,81 @@
---
name: nostr-encryption
description: Encrypt and decrypt content for Nostr direct messages, gift wraps, or any feature that needs NIP-44 (or legacy NIP-04) ciphertext, using the logged-in user's signer.
---
# Nostr Encryption and Decryption
The logged-in user exposes a `signer` object that matches the NIP-07 signer interface. The signer handles all cryptographic operations internally — including ECDH, conversation-key derivation, and AEAD — so your code never touches a private key.
**Always use the signer interface for encryption. Never ask the user for their private key, and never derive a shared secret yourself.**
## NIP-44 (preferred)
NIP-44 is the modern, authenticated encryption scheme used for DMs (NIP-17), gift wraps (NIP-59), and most new encrypted payloads.
```ts
import { useCurrentUser } from "@/hooks/useCurrentUser";
function useEncryptedNote() {
const { user } = useCurrentUser();
if (!user) throw new Error("Must be logged in");
// Guard: older signers may not support NIP-44 yet.
if (!user.signer.nip44) {
throw new Error(
"Please upgrade your signer extension to a version that supports NIP-44 encryption",
);
}
// Encrypt a message to a recipient (use your own pubkey to encrypt to self).
const ciphertext = await user.signer.nip44.encrypt(
recipientPubkey,
"hello world",
);
// Decrypt a message from a sender (use the *other party's* pubkey).
const plaintext = await user.signer.nip44.decrypt(senderPubkey, ciphertext);
return plaintext;
}
```
### Key points
- `encrypt(peerPubkey, plaintext)` — `peerPubkey` is the **other party's** hex public key. For self-encryption (notes, backups), pass `user.pubkey`.
- `decrypt(peerPubkey, ciphertext)` — `peerPubkey` is the author of the ciphertext you're decrypting (for an incoming DM, this is the sender's pubkey).
- Both methods are async and may throw if the signer rejects the request or the ciphertext is malformed. Wrap calls in `try/catch`.
- The signer handles conversation-key caching; repeated calls for the same peer are cheap.
## NIP-04 (legacy)
NIP-04 is only needed when interacting with older clients that haven't adopted NIP-44. The API mirrors NIP-44:
```ts
if (!user.signer.nip04) {
throw new Error("Signer does not support NIP-04");
}
const ciphertext = await user.signer.nip04.encrypt(peerPubkey, plaintext);
const plaintext = await user.signer.nip04.decrypt(peerPubkey, ciphertext);
```
Prefer NIP-44 for anything new. Only fall back to NIP-04 when a spec or peer explicitly requires it.
## Patterns
### Encrypt-to-self (drafts, private notes)
```ts
const ciphertext = await user.signer.nip44.encrypt(user.pubkey, draft);
createEvent({ kind: 30078, content: ciphertext, tags: [["d", "my-draft"]] });
```
### Decrypt an incoming DM (NIP-17 / NIP-59)
For gift-wrapped DMs, you'll typically decrypt the outer wrap, then the inner seal, then read the rumor's content. Each decryption uses the *sender* of that specific layer as the peer pubkey.
### Guarding the UI
Always check `user.signer.nip44` (or `nip04`) before calling encryption methods. Remote signers and older browser extensions may not implement every interface, and catching the missing-capability case lets you show a useful message ("Please upgrade your signer") instead of an unhandled promise rejection.
@@ -0,0 +1,77 @@
---
name: nostr-infinite-scroll
description: Build feed interfaces, implement pagination for Nostr events, or create social media-style infinite scroll experiences.
---
# Infinite Scroll for Nostr Feeds
For feed-like interfaces, implement infinite scroll using TanStack Query's `useInfiniteQuery` with Nostr's timestamp-based pagination:
```typescript
import { useNostr } from '@nostrify/react';
import { useInfiniteQuery } from '@tanstack/react-query';
export function useGlobalFeed() {
const { nostr } = useNostr();
return useInfiniteQuery({
queryKey: ['global-feed'],
queryFn: async ({ pageParam }) => {
const filter = { kinds: [1], limit: 20 };
if (pageParam) filter.until = pageParam;
const events = await nostr.query([filter], {
signal: AbortSignal.timeout(1500),
});
return events;
},
getNextPageParam: (lastPage) => {
if (lastPage.length === 0) return undefined;
return lastPage[lastPage.length - 1].created_at - 1; // Subtract 1 since 'until' is inclusive
},
initialPageParam: undefined,
});
}
```
Example usage with intersection observer for automatic loading:
```tsx
import { useInView } from 'react-intersection-observer';
import { useMemo } from 'react';
function GlobalFeed() {
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useGlobalFeed();
const { ref, inView } = useInView();
useEffect(() => {
if (inView && hasNextPage && !isFetchingNextPage) {
fetchNextPage();
}
}, [inView, hasNextPage, isFetchingNextPage, fetchNextPage]);
// Remove duplicate events by ID
const posts = useMemo(() => {
const seen = new Set();
return data?.pages.flat().filter(event => {
if (!event.id || seen.has(event.id)) return false;
seen.add(event.id);
return true;
}) || [];
}, [data?.pages]);
return (
<div className="space-y-4">
{posts.map((post) => (
<PostCard key={post.id} post={post} />
))}
{hasNextPage && (
<div ref={ref} className="py-4">
{isFetchingNextPage && <Skeleton className="h-20 w-full" />}
</div>
)}
</div>
);
}
```
+92
View File
@@ -0,0 +1,92 @@
---
name: nostr-relay-pools
description: Query or publish to specific Nostr relays or curated relay groups using nostr.relay() and nostr.group(), instead of the default connection pool. Useful for debugging, testing, specialized relays, or geographically-targeted publishing.
---
# Targeted Nostr Relay Connections
By default, the `nostr` object returned from `useNostr` uses the app's connection pool: it reads from one of the configured relays and publishes to all of them. For most features this is exactly what you want.
Use this skill when you need **more granular control** — talking to a single relay, a curated group of relays, or debugging a specific relay's behavior.
## Single Relay: `nostr.relay(url)`
```ts
import { useNostr } from '@nostrify/react';
function useSpecificRelay() {
const { nostr } = useNostr();
// Connect to a specific relay
const relay = nostr.relay('wss://relay.ditto.pub');
// Query from this relay only
const events = await relay.query([{ kinds: [1], limit: 15 }]);
// Publish to this relay only
await relay.event({ kind: 1, content: 'Hello from a specific relay!' });
}
```
**Good fits:**
- Testing a relay's behavior in isolation
- Debugging connectivity or rate-limiting issues
- Querying content that only lives on a specialized relay (paid relays, private relays, niche communities)
- Health checks / admin tooling
## Relay Group: `nostr.group(urls)`
```ts
import { useNostr } from '@nostrify/react';
function useRelayGroup() {
const { nostr } = useNostr();
// Create a group of specific relays
const relayGroup = nostr.group([
'wss://relay.ditto.pub',
'wss://relay.primal.net',
'wss://nos.lol',
]);
// Query from all relays in the group (deduplicated)
const events = await relayGroup.query([{ kinds: [1], limit: 15 }]);
// Publish to all relays in the group
await relayGroup.event({ kind: 1, content: 'Hello from a relay group!' });
}
```
**Good fits:**
- Publishing to a curated set of trusted relays for a specific feature
- Community-scoped queries (e.g. a set of relays known to host a particular topic)
- Geographic/region-targeted delivery
- Load-balancing reads across a known-good subset
## API Consistency
Both the `relay` object and the `group` object expose the **same interface** as the top-level `nostr` object:
- `.query(filters, opts?)` — request events matching filters
- `.req(filters, opts?)` — open a streaming subscription
- `.event(event)` — publish a signed event
- All other Nostrify methods
This means you can drop them into any existing hook or helper that expects a `nostr`-shaped object.
## Choosing Between Pool, Group, and Single Relay
| Scenario | Use |
|----------------------------------------------------|---------------------|
| Default app queries, best reach for publishing | `nostr` (pool) |
| Trusted subset, community-specific publishing | `nostr.group([…])` |
| Single-relay debugging or specialized relay access | `nostr.relay(url)` |
## Tips
- **Don't hard-code user-facing relay lists.** If a feature should publish to "the user's write relays", read from `AppContext.config.relayMetadata` (NIP-65) instead of hard-coding URLs.
- **Compose with TanStack Query.** Wrap `relay.query(...)` / `group.query(...)` inside a `useQuery` hook exactly as you would with the default `nostr` object; the caching layer is identical.
- **Handle unreachable relays.** Specific relays can be offline, rate-limited, or slow. Always wrap calls in `try/catch` and respect the abort signal from the query function (`c.signal`).
- **Avoid leaking subscriptions.** When using `.req(...)` for streaming, always close the subscription on unmount (`controller.abort()` or the returned disposer).
+152
View File
@@ -0,0 +1,152 @@
---
name: nostr-security
description: Threat model and defenses for a web Nostr client — why XSS is catastrophic when nsec keys live in localStorage, CSP as defense-in-depth, URL and CSS sanitization for untrusted event data, and author filtering for trust-sensitive queries (admin actions, moderators, addressable events, NIP-72 communities). Load when building trust-boundary features, rendering user-controlled URLs or markup, interpolating event data into CSS, or reviewing the app's security posture.
---
# Nostr Security
## Threat model
**Nostr private keys (`nsec`) are stored in plaintext in `localStorage`.** Any JavaScript running on the origin can read them with `localStorage.getItem('nostr-login')`. A successful XSS = instant, silent, irreversible key theft — no rotation, no revocation, permanent impersonation across every Nostr client the user ever touches. External signers (NIP-07 extension, NIP-46 bunker) don't change this: an XSS can still ask the active signer to sign arbitrary events, drain funds via zaps, or scrape DMs as they decrypt.
**Treat every piece of untrusted data as a script-injection vector** — event tags, `content`, metadata, URL params, relay responses.
## Defense-in-depth
**Content Security Policy.** `index.html` ships a restrictive CSP: `default-src 'none'`, `script-src 'self'` (no inline scripts, no `eval`), `base-uri 'self'`, `connect-src 'self' https: wss:`. The one intentional gap is `style-src 'unsafe-inline'` — required by Tailwind/shadcn — which means **CSS injection is not blocked by CSP; sanitization is on you**. When modifying CSP, only narrow it. Never add `'unsafe-eval'`, `'unsafe-inline'` on `script-src`, `http:`, or wildcard sources.
**Never use `dangerouslySetInnerHTML`, `innerHTML`, `insertAdjacentHTML`, or `document.write`** with event data, URL params, or any other untrusted string. React's JSX auto-escapes interpolated strings — the moment you bypass that, CSP alone won't save you. If you must render HTML from event data, pipe it through a strict allowlist sanitizer (e.g. DOMPurify) at the parse layer.
**Sanitize URLs and CSS values** — see §1 and §2.
## 1. URL sanitization
Any URL from event tags, `content`, metadata fields (`picture`, `banner`, `website`, `nip05`, etc.), or relay hints is untrusted. Threats beyond `javascript:` XSS: `data:` resource exhaustion / phishing, `http://` IP leaks, relative paths triggering same-origin requests, malformed strings crashing downstream parsers.
**Sanitize unconditionally at the parse layer.** mkstack doesn't ship a helper — add `src/lib/sanitizeUrl.ts` the first time you need one:
```ts
/** Returns canonical href for valid https:// URLs, undefined otherwise. */
export function sanitizeUrl(value: string | undefined | null): string | undefined {
if (!value) return undefined;
try {
const url = new URL(value);
return url.protocol === 'https:' ? url.href : undefined;
} catch {
return undefined;
}
}
```
Apply it when extracting data from events, not at each render site:
```ts
function parseProfile(event: NostrEvent): Profile {
const meta = JSON.parse(event.content);
return {
name: meta.name,
picture: sanitizeUrl(meta.picture),
banner: sanitizeUrl(meta.banner),
website: sanitizeUrl(meta.website),
};
}
```
**When sanitization is NOT required:** URLs matched by a regex that constrains the protocol (e.g. a content tokenizer matching `https?://...` — the regex *is* the sanitizer), hardcoded/app-generated URLs, and strings rendered as plain text that never land in an attribute, CSS value, or network request.
## 2. CSS injection
Event data interpolated into CSS (a `<style>` element, `style=""`, or an injected stylesheet) is a CSS injection vector. A `"`, `)`, `}`, or `;` in the value can break out of the string context and inject rules — overlay phishing, hide UI, exfiltrate via `background-image: url()` requests.
Common surfaces: `background-image: url("${url}")`, `font-family: "${family}"`, `@font-face { src: url("${url}") }`.
**Mitigation:**
- **URLs in `url()`** — use `sanitizeUrl()`. The `URL` constructor percent-encodes `"`, `)`, `\` and rejects non-`https:`.
- **Non-URL strings** (font-family, animation names) — allowlist safe characters:
```ts
/** Keeps Unicode letters/numbers, spaces, hyphens, underscores, apostrophes, periods. */
export function sanitizeCssString(value: string): string {
return value.replace(/[^\p{L}\p{N} _\-'.]/gu, '');
}
```
```ts
// ❌ UNSAFE
style.textContent = `body { background-image: url("${rawUrl}"); font-family: "${rawFamily}"; }`;
// ✅ SAFE — validate URLs, allowlist identifiers
const bgUrl = sanitizeUrl(rawUrl);
const family = sanitizeCssString(rawFamily ?? '');
if (bgUrl && family) {
style.textContent = `body { background-image: url("${bgUrl}"); font-family: "${family}"; }`;
}
```
If you can't justify the exact characters you're allowing, the policy is wrong.
## 3. Author filtering for trust-sensitive queries
Even with perfect XSS defenses, an attacker can publish forged events your UI will trust unless queries constrain `authors`. Relays are dumb pipes — any matching event comes back.
**Filter by `authors` when:**
- Querying admin/moderator/owner events — use a hardcoded trusted-pubkey list.
- Querying addressable events (kinds 30000–39999) — the `d` tag alone is not a trust boundary; the `(kind, pubkey, d)` triple is.
- Querying user-owned replaceable events (profile metadata, relay lists, mute lists) — `authors: [userPubkey]`.
**Do NOT filter by `authors`** for public UGC (kind 1 notes, reactions, zaps, discovery feeds) — anyone can post there by design.
```ts
// ❌ Anyone can publish kind 30078 with this d-tag and self-appoint
nostr.query([{ kinds: [30078], '#d': ['pathos-organizers'], limit: 1 }]);
// ✅ Only trust the admin list
nostr.query([{ kinds: [30078], authors: ADMIN_PUBKEYS, '#d': ['pathos-organizers'], limit: 1 }]);
```
**Routes for addressable/replaceable events must include the author** — otherwise the route handler can't construct a secure filter:
```tsx
// ❌ Any pubkey can squat the slug
<Route path="/article/:slug" element={<Article />} />
// ✅ Filter can include authors
<Route path="/article/:npub/:slug" element={<Article />} />
```
### NIP-72 community moderation
Kind 4550 approvals are only trustworthy if signed by a moderator from the community definition (kind 34550). Two-step query:
```ts
// 1. Fetch community definition — author-filter by the owner.
const [community] = await nostr.query([{
kinds: [34550], authors: [communityOwnerPubkey], '#d': [communityId], limit: 1,
}]);
if (!community) return [];
// 2. Extract moderator pubkeys from `p` tags with role "moderator".
const moderators = community.tags
.filter(([n, , , role]) => n === 'p' && role === 'moderator')
.map(([, pubkey]) => pubkey);
// 3. Query approvals — only from moderators.
const approvals = await nostr.query([{
kinds: [4550],
authors: moderators,
'#a': [`34550:${communityOwnerPubkey}:${communityId}`],
limit: 100,
}]);
```
Without step 3's `authors` filter, anyone can publish a kind 4550 "approval".
## Pre-merge checklist
- [ ] No `dangerouslySetInnerHTML` / `innerHTML` / `document.write` with untrusted data.
- [ ] CSP unchanged or narrowed; no new `'unsafe-eval'`, `'unsafe-inline'` on `script-src`, `http:`, or wildcards.
- [ ] Every event-sourced URL passes `sanitizeUrl()` before reaching `href`, `src`, `srcSet`, `poster`, iframe `src`, or CSS.
- [ ] Every event-sourced string in CSS passes `sanitizeUrl()` (URLs) or `sanitizeCssString()` (identifiers).
- [ ] Every trust-sensitive query includes `authors`.
- [ ] Routes for addressable/replaceable events carry the author in the URL.
+185
View File
@@ -0,0 +1,185 @@
---
name: note-content
description: Render plaintext Nostr note content (kind 1, 11, 1111) with linkified URLs, hashtags, Nostr mentions, custom emoji (NIP-30), flag-to-country links, inline images/video/audio, BOLT11 lightning invoices, embedded nevent/naddr cards, and link previews.
---
# Rich Text Rendering for Nostr Notes
This skill provides a full-featured `NoteContent` component that turns a Nostr event's plaintext `content` field into rich React output. It is adapted from the production implementation in the Ditto client and handles:
- URLs — linkified, with trailing-punctuation stripping and line-end-aware rich preview cards (`LinkEmbed`) vs. inline links
- `wss://` / `ws://` relay URLs — internal links to `/r/<encoded-url>`
- Image URLs — rendered inline as thumbnails, with consecutive images auto-grouped into a gallery and a shared lightbox
- Video/audio URLs — inline players; webxdc `.xdc` URLs — WebXDC app embeds (stub)
- NIP-94 `imeta`-declared media — appended at end when the content string doesn't reference them
- BOLT11 lightning invoices — rendered as `LightningInvoiceCard`
- Hashtags — internal links to `/t/<tag>`, with full Unicode letter support (`\p{L}\p{N}_`)
- Nostr mentions (`nostr:npub…`, `nostr:nprofile…`, bare `npub…`, `@npub…`) — resolved via `useAuthor`, rendered as `@DisplayName` links with optional `ProfileHoverCard`
- Embedded notes (`nostr:note1…`, `nostr:nevent1…`) — rendered as `EmbeddedNote` cards, enriched with relay/author hints from `q` tags
- Embedded addressable events (`nostr:naddr1…` or URLs containing an `naddr1` fragment) — rendered as `EmbeddedNaddr` cards
- Custom emoji (NIP-30 `:shortcode:`) — inline images from the event's own `emoji` tags, with the viewer's `useCustomEmojis` collection as fallback
- Flag emoji (🇺🇸, 🇵🇱, …) — linkified to `/i/iso3166:<CC>` pages
- "Emoji-only" posts — auto-detected and rendered at large size (`text-5xl`)
- Whitespace normalization — leading/trailing whitespace trimmed, redundant blank lines around block embeds collapsed
- Opt-out props — `disableEmbeds`, `disableMediaEmbeds`, `disableNoteEmbeds`, `hideEmbedImages` for preview contexts and recursive embed cards
**This component is not included in the project by default.** When the user's app displays text notes or other plaintext event content, follow the setup instructions below to install it.
## Files Provided by This Skill
Install all files from `.agents/skills/note-content/files/` into their matching `src/` locations:
### Core component & test
| Skill file | Copy to |
|---|---|
| `files/components/NoteContent.tsx` | `src/components/NoteContent.tsx` |
| `files/components/NoteContent.test.tsx` | `src/components/NoteContent.test.tsx` |
### Library helpers
| Skill file | Copy to |
|---|---|
| `files/lib/mediaUrls.ts` | `src/lib/mediaUrls.ts` |
| `files/lib/sanitizeUrl.ts` | `src/lib/sanitizeUrl.ts` |
| `files/lib/imeta.ts` | `src/lib/imeta.ts` |
| `files/lib/customEmoji.ts` | `src/lib/customEmoji.ts` |
| `files/lib/getDisplayName.ts` | `src/lib/getDisplayName.ts` |
| `files/lib/avatarShape.ts` | `src/lib/avatarShape.ts` |
| `files/lib/countries.ts` | `src/lib/countries.ts` |
### Hooks
| Skill file | Copy to |
|---|---|
| `files/hooks/useCustomEmojis.ts` | `src/hooks/useCustomEmojis.ts` |
| `files/hooks/useBlossomFallback.ts` | `src/hooks/useBlossomFallback.ts` |
| `files/hooks/useProfileUrl.ts` | `src/hooks/useProfileUrl.ts` |
### Companion components (minimal stubs — replace with richer versions later)
| Skill file | Copy to | Responsibility |
|---|---|---|
| `files/components/LinkEmbed.tsx` | `src/components/LinkEmbed.tsx` | Rich link preview card |
| `files/components/EmbeddedNote.tsx` | `src/components/EmbeddedNote.tsx` | `note1` / `nevent1` quote card |
| `files/components/EmbeddedNaddr.tsx` | `src/components/EmbeddedNaddr.tsx` | `naddr1` addressable-event card |
| `files/components/LightningInvoiceCard.tsx` | `src/components/LightningInvoiceCard.tsx` | BOLT11 invoice display / pay button |
| `files/components/VideoPlayer.tsx` | `src/components/VideoPlayer.tsx` | Inline video |
| `files/components/AudioVisualizer.tsx` | `src/components/AudioVisualizer.tsx` | Inline audio |
| `files/components/WebxdcEmbed.tsx` | `src/components/WebxdcEmbed.tsx` | WebXDC app launcher |
| `files/components/ImageGallery.tsx` | `src/components/ImageGallery.tsx` | Image grid + shared `Lightbox` |
| `files/components/ProfileHoverCard.tsx` | `src/components/ProfileHoverCard.tsx` | Hover profile preview |
| `files/components/CustomEmoji.tsx` | `src/components/CustomEmoji.tsx` | `CustomEmojiImg` + `EmojifiedText` |
The companion component stubs are **functional** — they render something sensible for every embed type — but deliberately minimal. Read the comment at the top of each file for notes on how to replace them with production-grade versions (OpenGraph scrapers, blurhash placeholders, WebLN-backed invoice payment, etc.).
## Setup Instructions
### 1. Dependencies
No extra npm packages are required. The skill uses only packages already present in the template:
- `react`, `react-router-dom` (internal `Link`)
- `nostr-tools` (`nip19` decoding/encoding)
- `@nostrify/nostrify` (`NostrEvent`, `NostrMetadata`)
### 2. Copy the Skill Files Into `src/`
Copy every file listed in the tables above from `.agents/skills/note-content/files/` into its corresponding location under `src/`. Preserve the exact paths — everything uses `@/` imports that depend on these locations.
### 3. Routing Expectations
`NoteContent` generates links that assume these routes exist in `AppRouter.tsx`:
| Generated link | Route expected |
|---|---|
| `/<nip19-identifier>` (e.g. `/npub1…`, `/note1…`, `/nevent1…`, `/naddr1…`) | Handled by the template's `NIP19Page` at `/:nip19` |
| `/t/<hashtag>` | **Not in the default template.** Add `<Route path="/t/:hashtag" element={<HashtagPage />} />` if you want hashtag pages. |
| `/r/<encoded-wss-url>` | **Not in the default template.** Add `<Route path="/r/:relayUrl" element={<RelayPage />} />` if you want relay pages. |
| `/i/iso3166:<CC>` | **Not in the default template.** Add `<Route path="/i/iso3166::code" element={<CountryPage />} />` if you want flag-emoji country pages. |
Any unrouted link falls through to the 404 page — nothing breaks, but the affordance is inert.
## Usage
```tsx
import { NoteContent } from '@/components/NoteContent';
import type { NostrEvent } from '@nostrify/nostrify';
function Post({ event }: { event: NostrEvent }) {
return (
<article>
{/* ...header, avatar, etc */}
<NoteContent event={event} className="text-sm" />
</article>
);
}
```
### Props
```ts
interface NoteContentProps {
event: NostrEvent;
className?: string;
/** Render URLs as inline links only — suppress LinkEmbed / image / video / audio / invoice previews. */
disableEmbeds?: boolean;
/** Hide the thumbnail in LinkEmbed previews (useful when a cover image is already shown). */
hideEmbedImages?: boolean;
/** Render nostr:nevent/note/naddr embeds as inline links, not cards. Use inside recursive quote cards. */
disableNoteEmbeds?: boolean;
/** Suppress images, galleries, and video/audio players entirely. Used inside lightweight quote cards. */
disableMediaEmbeds?: boolean;
}
```
### Preview contexts
Inside a **recursive quote card** (e.g. when `EmbeddedNote` itself renders `NoteContent` for the quoted note), pass `disableNoteEmbeds disableMediaEmbeds` to prevent unbounded nesting and keep the card compact.
Inside a **compose preview** or a **triple-dot menu preview**, pass `disableEmbeds` to show only linkified URLs without any heavy previews.
## Upgrading the Companion Components
The stubs shipped here are deliberately minimal so the skill works immediately and can be committed without dragging in hundreds of extra files. When your app needs richer behaviour, progressively upgrade individual components — the JSX surface in `NoteContent` stays the same. Common upgrade paths:
- **`LinkEmbed`** → fetch OpenGraph metadata (title, description, thumbnail), detect YouTube/Twitter/Bluesky for embeddable players
- **`EmbeddedNote` / `EmbeddedNaddr`** → introduce a `useEvent(id, relays, author)` / `useAddrEvent({kind, pubkey, identifier}, relays)` hook and render the fetched event using a nested `<NoteContent disableNoteEmbeds disableMediaEmbeds>`
- **`LightningInvoiceCard`** → pair with the `nwc` skill's `useWallet` / `useZaps` to pay directly, decode the BOLT11 for amount/description/expiry, render a QR code
- **`VideoPlayer` / `AudioVisualizer`** → show blurhash placeholders from `imeta`, add full-screen / background-playback controls, respect `dim` for correct aspect ratio on first paint
- **`ImageGallery` / `Lightbox`** → add pinch-zoom, swipe gestures, blurhash placeholders, alt-text overlays
- **`WebxdcEmbed`** → host the WebXDC app in a sandboxed iframe with a Nostr-backed `sendUpdate` / `setUpdateListener` bridge
- **`ProfileHoverCard`** → open a shadcn `HoverCard` with the author's avatar, display name, bio, follow count, follow/zap/DM actions
- **`useCustomEmojis`** → fetch the viewer's kind 10030 "Emoji List" event and any kind 30030 "Emoji Set" events it references, expose all shortcode→URL pairs
- **`useBlossomFallback`** → parse the URL's blossom hash, rotate through the viewer's BUD-03 "User Server List" (kind 10063) on `onError`
- **`useProfileUrl`** → route by the user's verified `nip05` handle when present (requires a `/:handle` route), fall back to `/<npub>`
## Supported Content Patterns
| Pattern in `event.content` | Rendered as |
|---|---|
| `https://example.com/...` | Inline link if mid-line, or `LinkEmbed` card if URL ends a line |
| `https://…/image.jpg` (any `IMAGE_EXTS`) | Inline image; 2+ consecutive → `ImageGallery` |
| `https://…/video.mp4` (any `VIDEO_EXTS`) | `VideoPlayer` |
| `https://…/song.mp3` (any `AUDIO_EXTS`) | `AudioVisualizer` |
| `https://…/app.xdc` | `WebxdcEmbed` |
| `wss://relay…` | Internal `/r/<encoded>` link |
| URL containing `naddr1…` | Paired URL + `EmbeddedNaddr` card |
| `lightning:lnbc…` / `lnbc…` / `lntb…` / `lnbcrt…` / `lntbs…` | `LightningInvoiceCard` |
| `nostr:npub1…` or `nostr:nprofile1…` or bare `npub1…` | `@DisplayName` mention link (through `ProfileHoverCard`) |
| `nostr:note1…` / `nostr:nevent1…` or bare | `EmbeddedNote` card (relay/author hints pulled from event's `q` tags) |
| `nostr:naddr1…` or bare | `EmbeddedNaddr` card |
| `#hashtag` (Unicode letters OK) | Internal `/t/hashtag` link |
| 🇺🇸 🇵🇱 🇧🇷 … | Internal `/i/iso3166:US` link |
| `:custom_emoji:` (with matching `["emoji", …]` tag or viewer collection) | `CustomEmojiImg` |
| Plain text | Rendered as-is with `whitespace-pre-wrap`, `dir="auto"` for RTL |
## Tests
`NoteContent.test.tsx` covers URL linkification (kinds 1 and 1111), plain text, hashtag linkification, and mention rendering with fallback vs real display names. It uses the template's `TestApp` wrapper. Run via `npm run test` once the files are in `src/`.
## Related
- **`useAuthor`** — used internally for mention resolution and for audio-embed author avatar. Core template.
- **`NIP19Page`** — the template's `/:nip19` route that handles every kind of NIP-19 link this component generates.
- **`nwc` skill** — pair with `LightningInvoiceCard` for one-tap invoice payment via WebLN/NWC.
@@ -0,0 +1,46 @@
import { cn } from '@/lib/utils';
interface AudioVisualizerProps {
src: string;
mime?: string;
avatarUrl?: string;
avatarFallback?: string;
avatarShape?: string;
className?: string;
}
/**
* Minimal inline audio player — renders a native `<audio controls>`
* alongside the author's avatar.
*
* Ditto's richer `AudioVisualizer` renders a waveform visualization,
* applies `avatarShape` as a CSS mask, and supports background playback
* state. Replace this stub with a richer player (e.g. using WebAudio +
* Canvas visualization) when desired.
*/
export function AudioVisualizer({
src,
avatarUrl,
avatarFallback,
avatarShape: _avatarShape,
className,
}: AudioVisualizerProps) {
return (
<div
className={cn(
'flex items-center gap-3 border rounded-lg px-3 py-2 my-2.5',
className,
)}
onClick={(e) => e.stopPropagation()}
>
<div className="shrink-0 w-10 h-10 rounded-full bg-muted flex items-center justify-center overflow-hidden">
{avatarUrl ? (
<img src={avatarUrl} alt="" className="w-full h-full object-cover" />
) : (
<span className="text-sm font-medium">{avatarFallback ?? '?'}</span>
)}
</div>
<audio src={src} controls preload="metadata" className="flex-1 min-w-0" />
</div>
);
}
@@ -0,0 +1,87 @@
import { type ReactNode } from 'react';
import { cn } from '@/lib/utils';
interface CustomEmojiImgProps {
/** Shortcode without surrounding colons. */
name: string;
/** The emoji image URL from a NIP-30 `emoji` tag. */
url: string;
className?: string;
}
/**
* Inline NIP-30 custom emoji image.
*/
export function CustomEmojiImg({ name, url, className }: CustomEmojiImgProps) {
return (
<img
src={url}
alt={`:${name}:`}
title={`:${name}:`}
draggable={false}
loading="lazy"
className={cn(
'inline h-[1.2em] w-[1.2em] object-contain align-text-bottom',
className,
)}
/>
);
}
interface EmojifiedTextProps {
/** Event tags containing NIP-30 `emoji` entries used to resolve shortcodes. */
tags: string[][];
children: string;
className?: string;
}
/**
* Render a string, replacing `:shortcode:` patterns with inline
* custom emoji images sourced from the provided `emoji` tags.
* Used inside usernames, reaction displays, etc.
*/
export function EmojifiedText({ tags, children, className }: EmojifiedTextProps) {
const emojiMap = new Map<string, string>();
for (const tag of tags) {
if (tag[0] === 'emoji' && tag[1] && tag[2]) {
emojiMap.set(tag[1], tag[2]);
}
}
if (emojiMap.size === 0) {
return <span className={className}>{children}</span>;
}
const parts: ReactNode[] = [];
const regex = /:([a-zA-Z0-9_-]+):/g;
let lastIndex = 0;
let match: RegExpExecArray | null;
while ((match = regex.exec(children)) !== null) {
const [full, shortcode] = match;
const url = emojiMap.get(shortcode);
if (!url) continue;
if (match.index > lastIndex) {
parts.push(children.substring(lastIndex, match.index));
}
parts.push(
<CustomEmojiImg
key={`emoji-${match.index}`}
name={shortcode}
url={url}
/>,
);
lastIndex = match.index + full.length;
}
if (lastIndex < children.length) {
parts.push(children.substring(lastIndex));
}
return (
<span className={className}>
{parts.length > 0 ? parts : children}
</span>
);
}
@@ -0,0 +1,43 @@
import { Link } from 'react-router-dom';
import { nip19 } from 'nostr-tools';
import { cn } from '@/lib/utils';
import type { AddrCoords } from '@/components/NoteContent';
interface EmbeddedNaddrProps {
addr: AddrCoords;
className?: string;
}
/**
* Minimal embedded-naddr card — renders a link to the referenced
* addressable event (kind:pubkey:identifier).
*
* Ditto's richer `EmbeddedNaddr` fetches the addressable event (long-form
* article, marketplace listing, etc.) and renders a preview card with
* title, author, cover image, and summary. Replace this stub with a
* version that uses `useAddrEvent({kind, pubkey, identifier})` to fetch
* and render the target event.
*/
export function EmbeddedNaddr({ addr, className }: EmbeddedNaddrProps) {
const naddrId = nip19.naddrEncode({
kind: addr.kind,
pubkey: addr.pubkey,
identifier: addr.identifier,
});
return (
<Link
to={`/${naddrId}`}
onClick={(e) => e.stopPropagation()}
className={cn(
'block border rounded-lg px-3 py-2 hover:bg-muted/50 transition-colors text-sm',
className,
)}
>
<div className="font-medium">Addressable event</div>
<div className="text-xs text-muted-foreground font-mono truncate">
kind:{addr.kind} · {addr.identifier || '(no identifier)'}
</div>
</Link>
);
}
@@ -0,0 +1,42 @@
import { Link } from 'react-router-dom';
import { nip19 } from 'nostr-tools';
import { cn } from '@/lib/utils';
interface EmbeddedNoteProps {
eventId: string;
relays?: string[];
authorHint?: string;
className?: string;
}
/**
* Minimal embedded-note card — renders a link to the referenced event.
*
* Ditto's richer `EmbeddedNote` fetches the quoted event, renders its
* author, timestamp, and (recursively) its content inside a card.
* Replace this stub with a version that uses a `useEvent(id, relays, author)`
* hook to fetch and render the quoted note.
*/
export function EmbeddedNote({ eventId, relays, authorHint, className }: EmbeddedNoteProps) {
const neventId = nip19.neventEncode({
id: eventId,
...(authorHint ? { author: authorHint } : {}),
...(relays?.length ? { relays } : {}),
});
return (
<Link
to={`/${neventId}`}
onClick={(e) => e.stopPropagation()}
className={cn(
'block border rounded-lg px-3 py-2 hover:bg-muted/50 transition-colors text-sm',
className,
)}
>
<div className="font-medium">Quoted note</div>
<div className="text-xs text-muted-foreground font-mono truncate">
{neventId.slice(0, 24)}…
</div>
</Link>
);
}
@@ -0,0 +1,168 @@
import { useEffect, useCallback } from 'react';
import { cn } from '@/lib/utils';
import type { ImetaEntry } from '@/lib/imeta';
interface ImageGalleryProps {
images: string[];
/** Max images to show in the grid before "+ more" overflow. */
maxVisible?: number;
maxGridHeight?: string;
/** imeta metadata keyed by URL (dim, blurhash, etc.). Unused in this stub. */
imetaMap?: Map<string, ImetaEntry>;
lightboxIndex?: number | null;
onLightboxOpen?: (index: number) => void;
onLightboxClose?: () => void;
className?: string;
}
/**
* Minimal image gallery grid.
*
* Ditto's richer `ImageGallery` uses `imetaMap` for precise aspect ratios,
* blurhash placeholders, CSS-grid masonry, pinch-to-zoom on mobile, and
* keyboard navigation. Replace this stub with a richer gallery as needed.
*/
export function ImageGallery({
images,
maxVisible = 4,
maxGridHeight,
lightboxIndex,
onLightboxOpen,
onLightboxClose,
className,
}: ImageGalleryProps) {
const shown = images.slice(0, maxVisible);
const extra = Math.max(0, images.length - maxVisible);
// Two-column grid for 2+ images
const gridCols = shown.length === 1 ? 'grid-cols-1' : 'grid-cols-2';
return (
<>
<div
className={cn(
'grid gap-2 my-2.5 rounded-lg overflow-hidden',
gridCols,
className,
)}
style={maxGridHeight ? { maxHeight: maxGridHeight } : undefined}
>
{shown.map((url, idx) => (
<button
key={idx}
type="button"
onClick={(e) => {
e.stopPropagation();
onLightboxOpen?.(idx);
}}
className="block relative overflow-hidden rounded-md bg-muted focus:outline-none focus-visible:ring-2 focus-visible:ring-primary"
>
<img
src={url}
alt=""
loading="lazy"
className="block w-full h-full object-cover hover:opacity-90 transition-opacity"
/>
{idx === maxVisible - 1 && extra > 0 && (
<div className="absolute inset-0 bg-black/50 text-white flex items-center justify-center text-xl font-semibold">
+{extra}
</div>
)}
</button>
))}
</div>
{lightboxIndex !== null && lightboxIndex !== undefined && (
<Lightbox
images={images}
currentIndex={lightboxIndex}
onClose={onLightboxClose ?? (() => { /* noop */ })}
/>
)}
</>
);
}
interface LightboxProps {
images: string[];
currentIndex: number;
onClose: () => void;
onNext?: () => void;
onPrev?: () => void;
}
/**
* Minimal fullscreen lightbox — click-outside-to-close, arrow-key navigation.
*
* Ditto's richer `Lightbox` supports pinch-zoom, swipe gestures, download,
* and alt-text overlays. Replace this stub with a richer viewer as needed.
*/
export function Lightbox({ images, currentIndex, onClose, onNext, onPrev }: LightboxProps) {
const handleKey = useCallback(
(e: KeyboardEvent) => {
if (e.key === 'Escape') onClose();
else if (e.key === 'ArrowRight') onNext?.();
else if (e.key === 'ArrowLeft') onPrev?.();
},
[onClose, onNext, onPrev],
);
useEffect(() => {
window.addEventListener('keydown', handleKey);
return () => window.removeEventListener('keydown', handleKey);
}, [handleKey]);
const url = images[currentIndex];
if (!url) return null;
return (
<div
className="fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4"
onClick={onClose}
>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
onClose();
}}
className="absolute top-4 right-4 text-white text-3xl leading-none hover:opacity-70"
aria-label="Close"
>
×
</button>
{onPrev && images.length > 1 && (
<button
type="button"
onClick={(e) => {
e.stopPropagation();
onPrev();
}}
className="absolute left-4 top-1/2 -translate-y-1/2 text-white text-4xl leading-none hover:opacity-70"
aria-label="Previous"
>
‹
</button>
)}
{onNext && images.length > 1 && (
<button
type="button"
onClick={(e) => {
e.stopPropagation();
onNext();
}}
className="absolute right-4 top-1/2 -translate-y-1/2 text-white text-4xl leading-none hover:opacity-70"
aria-label="Next"
>
›
</button>
)}
<img
src={url}
alt=""
className="max-w-full max-h-full object-contain"
onClick={(e) => e.stopPropagation()}
/>
</div>
);
}
@@ -0,0 +1,34 @@
import { cn } from '@/lib/utils';
interface LightningInvoiceCardProps {
invoice: string;
className?: string;
}
/**
* Minimal Lightning invoice card — renders a `lightning:` link that
* opens in any installed wallet.
*
* Ditto's richer `LightningInvoiceCard` decodes the BOLT11 invoice,
* shows the amount, description, expiry, pays via WebLN/NWC, renders
* a QR code, and tracks payment state. To replicate, pair with the
* `nwc` skill's `useWallet` / `useZaps` hooks and a bolt11 decoder
* such as `light-bolt11-decoder`.
*/
export function LightningInvoiceCard({ invoice, className }: LightningInvoiceCardProps) {
return (
<a
href={`lightning:${invoice}`}
onClick={(e) => e.stopPropagation()}
className={cn(
'block border rounded-lg px-3 py-2 hover:bg-muted/50 transition-colors text-sm my-2.5',
className,
)}
>
<div className="font-medium">⚡ Lightning invoice</div>
<div className="text-xs text-muted-foreground font-mono truncate">
{invoice.slice(0, 24)}…
</div>
</a>
);
}
@@ -0,0 +1,41 @@
import { cn } from '@/lib/utils';
interface LinkEmbedProps {
url: string;
className?: string;
/** Hide the thumbnail image (e.g. when a cover image is already displayed above). */
hideImage?: boolean;
}
/**
* Minimal link preview card — renders the URL as a clickable block.
*
* Ditto's richer `LinkEmbed` fetches OpenGraph metadata (title, description,
* thumbnail, YouTube/Tweet/ogimage extraction) and renders a proper preview
* card. Replace this stub with a version that queries a metadata endpoint
* of your choice (oEmbed, OG scrapers, etc.) when you want rich previews.
*/
export function LinkEmbed({ url, className, hideImage: _hideImage }: LinkEmbedProps) {
let display = url;
try {
display = new URL(url).hostname.replace(/^www\./, '');
} catch {
// keep raw url as display
}
return (
<a
href={url}
target="_blank"
rel="noopener noreferrer"
onClick={(e) => e.stopPropagation()}
className={cn(
'block border rounded-lg px-3 py-2 hover:bg-muted/50 transition-colors text-sm',
className,
)}
>
<div className="font-medium truncate">{display}</div>
<div className="text-xs text-muted-foreground truncate">{url}</div>
</a>
);
}
@@ -5,14 +5,14 @@ import { NoteContent } from './NoteContent';
import type { NostrEvent } from '@nostrify/nostrify';
describe('NoteContent', () => {
it('linkifies URLs in kind 1 events', () => {
it('linkifies URLs in kind 1 events', async () => {
const event: NostrEvent = {
id: 'test-id',
pubkey: 'test-pubkey',
created_at: Math.floor(Date.now() / 1000),
kind: 1,
tags: [],
content: 'Check out this link: https://example.com',
content: 'Check out this link: https://example.com for more info',
sig: 'test-sig',
};
@@ -22,13 +22,13 @@ describe('NoteContent', () => {
</TestApp>
);
const link = screen.getByRole('link', { name: 'https://example.com' });
const link = await screen.findByRole('link', { name: 'https://example.com' });
expect(link).toBeInTheDocument();
expect(link).toHaveAttribute('href', 'https://example.com');
expect(link).toHaveAttribute('target', '_blank');
});
it('linkifies URLs in kind 1111 events (comments)', () => {
it('linkifies URLs in kind 1111 events (comments)', async () => {
const event: NostrEvent = {
id: 'test-comment-id',
pubkey: 'test-pubkey',
@@ -39,7 +39,7 @@ describe('NoteContent', () => {
['k', '30040'],
['p', 'pubkey'],
],
content: 'I think the log events should be different kind numbers instead of having a `log-type` tag. That way you can use normal Nostr filters to filter the log types. Also, the `note` type should just b a kind 1111: https://nostrbook.dev/kinds/1111',
content: 'I think the log events should be different kind numbers instead of having a `log-type` tag. That way you can use normal Nostr filters to filter the log types. Also, the `note` type should just be a kind 1111: https://nostrbook.dev/kinds/1111 as specified in the spec.',
sig: 'test-sig',
};
@@ -49,13 +49,13 @@ describe('NoteContent', () => {
</TestApp>
);
const link = screen.getByRole('link', { name: 'https://nostrbook.dev/kinds/1111' });
const link = await screen.findByRole('link', { name: 'https://nostrbook.dev/kinds/1111' });
expect(link).toBeInTheDocument();
expect(link).toHaveAttribute('href', 'https://nostrbook.dev/kinds/1111');
expect(link).toHaveAttribute('target', '_blank');
});
it('handles text without URLs correctly', () => {
it('handles text without URLs correctly', async () => {
const event: NostrEvent = {
id: 'test-id',
pubkey: 'test-pubkey',
@@ -72,11 +72,11 @@ describe('NoteContent', () => {
</TestApp>
);
expect(screen.getByText('This is just plain text without any links.')).toBeInTheDocument();
expect(await screen.findByText('This is just plain text without any links.')).toBeInTheDocument();
expect(screen.queryByRole('link')).not.toBeInTheDocument();
});
it('renders hashtags as links', () => {
it('renders hashtags as links', async () => {
const event: NostrEvent = {
id: 'test-id',
pubkey: 'test-pubkey',
@@ -93,7 +93,7 @@ describe('NoteContent', () => {
</TestApp>
);
const nostrHashtag = screen.getByRole('link', { name: '#nostr' });
const nostrHashtag = await screen.findByRole('link', { name: '#nostr' });
const bitcoinHashtag = screen.getByRole('link', { name: '#bitcoin' });
expect(nostrHashtag).toBeInTheDocument();
@@ -102,7 +102,7 @@ describe('NoteContent', () => {
expect(bitcoinHashtag).toHaveAttribute('href', '/t/bitcoin');
});
it('generates deterministic names for users without metadata and styles them differently', () => {
it('generates deterministic names for users without metadata and styles them differently', async () => {
// Use a valid npub for testing
const event: NostrEvent = {
id: 'test-id',
@@ -121,12 +121,12 @@ describe('NoteContent', () => {
);
// The mention should be rendered with a deterministic name
const mention = screen.getByRole('link');
const mention = await screen.findByRole('link');
expect(mention).toBeInTheDocument();
// Should have muted styling for generated names (gray instead of blue)
expect(mention).toHaveClass('text-gray-500');
expect(mention).not.toHaveClass('text-blue-500');
// Should have muted styling for generated names (muted-foreground instead of primary)
expect(mention).toHaveClass('text-muted-foreground');
expect(mention).not.toHaveClass('text-primary');
// The text should start with @ and contain a generated name (not a truncated npub)
const linkText = mention.textContent;
@@ -0,0 +1,866 @@
import { useMemo, useState, useCallback, type ReactNode } from 'react';
import { type NostrEvent } from '@nostrify/nostrify';
import { Link } from 'react-router-dom';
import { nip19 } from 'nostr-tools';
import { useAuthor } from '@/hooks/useAuthor';
import { getDisplayName } from '@/lib/getDisplayName';
import { getAvatarShape } from '@/lib/avatarShape';
import { useProfileUrl } from '@/hooks/useProfileUrl';
import { LinkEmbed } from '@/components/LinkEmbed';
import { EmbeddedNote } from '@/components/EmbeddedNote';
import { EmbeddedNaddr } from '@/components/EmbeddedNaddr';
import { LightningInvoiceCard } from '@/components/LightningInvoiceCard';
import { VideoPlayer } from '@/components/VideoPlayer';
import { AudioVisualizer } from '@/components/AudioVisualizer';
import { WebxdcEmbed } from '@/components/WebxdcEmbed';
import { Lightbox, ImageGallery } from '@/components/ImageGallery';
import { ProfileHoverCard } from '@/components/ProfileHoverCard';
import { EmojifiedText, CustomEmojiImg } from '@/components/CustomEmoji';
import { buildEmojiMap } from '@/lib/customEmoji';
import { useCustomEmojis } from '@/hooks/useCustomEmojis';
import { useBlossomFallback } from '@/hooks/useBlossomFallback';
import { COUNTRIES } from '@/lib/countries';
import { IMAGE_URL_REGEX, EMBED_MEDIA_URL_REGEX } from '@/lib/mediaUrls';
import { parseImetaMap } from '@/lib/imeta';
import { sanitizeUrl } from '@/lib/sanitizeUrl';
import { cn } from '@/lib/utils';
/** Coordinates for an addressable event (naddr). */
export interface AddrCoords {
kind: number;
pubkey: string;
identifier: string;
}
interface NoteContentProps {
event: NostrEvent;
className?: string;
/** When true, renders URLs as inline links instead of link preview cards / embeds. */
disableEmbeds?: boolean;
/** When true, hides thumbnail images in link preview cards (useful when a cover image is already shown). */
hideEmbedImages?: boolean;
/** When true, nested nostr:nevent/note/naddr embeds render as inline links instead of cards.
* Used inside embedded quote cards to prevent unbounded recursive nesting. */
disableNoteEmbeds?: boolean;
/** When true, images, galleries, and video/audio players are suppressed (rendered as
* whitespace) while link preview cards and other non-media embeds are preserved.
* Used inside embedded quote cards to keep them lightweight. */
disableMediaEmbeds?: boolean;
}
/** Regex matching `:shortcode:` patterns in text. */
const SHORTCODE_REGEX = /:([a-zA-Z0-9_-]+):/g;
/**
* Replaces `:shortcode:` patterns in text with inline custom emoji images.
*/
function emojify(
text: string,
emojiMap: Map<string, string>,
imgClassName?: string,
): ReactNode[] {
if (emojiMap.size === 0) return [text];
const result: ReactNode[] = [];
let lastIndex = 0;
let match: RegExpExecArray | null;
SHORTCODE_REGEX.lastIndex = 0;
while ((match = SHORTCODE_REGEX.exec(text)) !== null) {
const [fullMatch, shortcode] = match;
const url = emojiMap.get(shortcode);
if (!url) continue;
if (match.index > lastIndex) {
result.push(text.substring(lastIndex, match.index));
}
result.push(
<CustomEmojiImg
key={`emoji-${match.index}`}
name={shortcode}
url={url}
className={imgClassName}
/>,
);
lastIndex = match.index + fullMatch.length;
}
if (lastIndex < text.length) {
result.push(text.substring(lastIndex));
}
return result.length > 0 ? result : [text];
}
/** Bech32 charset used by NIP-19 identifiers. */
const BECH32_CHARS = '023456789acdefghjklmnpqrstuvwxyz';
/** Regex to extract an naddr1 identifier from a URL path. */
const NADDR_IN_URL_REGEX = new RegExp(`naddr1[${BECH32_CHARS}]{10,}`, 'i');
/** Try to extract naddr coordinates from a URL containing an naddr1 identifier. */
function extractNaddrFromUrl(url: string): AddrCoords | null {
const match = url.match(NADDR_IN_URL_REGEX);
if (!match) return null;
try {
const decoded = nip19.decode(match[0]);
if (decoded.type === 'naddr') {
return decoded.data as AddrCoords;
}
} catch {
// invalid naddr
}
return null;
}
/** Regex matching flag emoji: pairs of Regional Indicator Symbol letters (U+1F1E6–U+1F1FF). */
const FLAG_EMOJI_REGEX = /([\u{1F1E6}-\u{1F1FF}]{2})/gu;
/**
* Convert a flag emoji (pair of Regional Indicator Symbols) to an ISO 3166-1 alpha-2 code.
* Returns the code if it maps to a known country, otherwise null.
*/
function flagToCountryCode(flag: string): string | null {
const codePoints = [...flag];
if (codePoints.length !== 2) return null;
const a = codePoints[0].codePointAt(0)! - 0x1F1E6 + 65;
const b = codePoints[1].codePointAt(0)! - 0x1F1E6 + 65;
const code = String.fromCharCode(a) + String.fromCharCode(b);
return COUNTRIES[code] ? code : null;
}
/**
* Process an array of ReactNodes (from emojify), splitting any string nodes
* to wrap flag emojis in <Link> elements pointing to /i/iso3166:<CODE>.
*/
function linkifyFlags(nodes: ReactNode[]): ReactNode[] {
const result: ReactNode[] = [];
let keyIdx = 0;
for (const node of nodes) {
if (typeof node !== 'string') {
result.push(node);
continue;
}
let lastIndex = 0;
FLAG_EMOJI_REGEX.lastIndex = 0;
let match: RegExpExecArray | null;
while ((match = FLAG_EMOJI_REGEX.exec(node)) !== null) {
const flag = match[1];
const code = flagToCountryCode(flag);
if (!code) continue;
if (match.index > lastIndex) {
result.push(node.substring(lastIndex, match.index));
}
result.push(
<Link
key={`flag-${keyIdx++}`}
to={`/i/iso3166:${code}`}
className="hover:opacity-70 transition-opacity"
onClick={(e) => e.stopPropagation()}
>
{flag}
</Link>,
);
lastIndex = match.index + match[0].length;
}
if (lastIndex < node.length) {
result.push(node.substring(lastIndex));
} else if (lastIndex === 0) {
result.push(node);
}
}
return result;
}
/** A parsed token from note content. */
type ContentToken =
| { type: 'text'; value: string }
| { type: 'image-embed'; url: string }
| { type: 'image-gallery'; urls: string[] }
| { type: 'media-embed'; url: string }
| { type: 'link-embed'; url: string }
| { type: 'inline-link'; url: string }
| { type: 'mention'; pubkey: string }
| { type: 'nevent-embed'; eventId: string; relays?: string[]; author?: string }
| { type: 'naddr-embed'; addr: AddrCoords; url?: string }
| { type: 'nostr-link'; id: string; raw: string }
| { type: 'hashtag'; tag: string; raw: string }
| { type: 'relay-link'; url: string }
| { type: 'lightning-invoice'; invoice: string };
/**
* Regex segment matching a single visual emoji unit, including:
* - ZWJ sequences (e.g. 👨‍👩‍👧‍👦, 👩‍💻)
* - Skin tone / hair style modifiers (e.g. 👋🏽)
* - Flag sequences (Regional Indicator pairs, e.g. 🇺🇸)
* - Keycap sequences (e.g. 1️⃣)
* - Tag sequences (e.g. 🏴󠁧󠁢󠁷󠁬󠁳󠁿)
* - Basic presentation emojis (with or without VS16)
*/
const EMOJI_UNIT = [
// ZWJ sequences: emoji (+ optional modifier) joined by ZWJ, repeated
'(?:' +
'(?:\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F)' + // base emoji
'[\\u{1F3FB}-\\u{1F3FF}]?' + // optional skin tone
'(?:\\u200D(?:\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F)[\\u{1F3FB}-\\u{1F3FF}]?)+' + // ZWJ + next
')',
// Flag sequences (two Regional Indicator symbols)
'(?:[\\u{1F1E6}-\\u{1F1FF}]{2})',
// Keycap sequences: digit/# /* + VS16 + combining enclosing keycap
'(?:[0-9#*]\\uFE0F\\u20E3)',
// Tag sequences (subdivision flags): 🏴 + tag chars + cancel tag
'(?:\\u{1F3F4}[\\u{E0020}-\\u{E007E}]+\\u{E007F})',
// Single emoji with optional skin tone modifier
'(?:(?:\\p{Emoji_Presentation}|\\p{Emoji}\\uFE0F)[\\u{1F3FB}-\\u{1F3FF}]?)',
].join('|');
/** NIP-30 custom emoji shortcode pattern. */
const CUSTOM_EMOJI_SHORTCODE = ':([a-zA-Z0-9_-]+):';
/** Regex matching a string of only NIP-30 custom emoji shortcodes and/or unicode emojis (with optional whitespace). Max 10 visual emojis. */
const EMOJI_OR_CUSTOM_ONLY_REGEX = new RegExp(
`^\\s*(?:(?:${CUSTOM_EMOJI_SHORTCODE}|${EMOJI_UNIT})\\s*){1,10}$`,
'u',
);
/** Check if a string contains only unicode emojis and/or NIP-30 custom emoji shortcodes (and whitespace). */
function isOnlyEmojisOrCustom(text: string, emojiMap: Map<string, string>): boolean {
if (!EMOJI_OR_CUSTOM_ONLY_REGEX.test(text)) return false;
// Verify all shortcodes in the text actually resolve to a custom emoji
const shortcodeMatches = text.matchAll(/:([a-zA-Z0-9_-]+):/g);
for (const m of shortcodeMatches) {
if (!emojiMap.has(m[1])) return false;
}
return true;
}
/** Parses content of text note events so that URLs and hashtags are linkified. */
export function NoteContent({
event,
className,
disableEmbeds = false,
hideEmbedImages = false,
disableNoteEmbeds = false,
disableMediaEmbeds = false,
}: NoteContentProps) {
const tokens = useMemo(() => {
const text = event.content;
// Match: BOLT11 invoices | URLs | nostr:-prefixed NIP-19 ids | @-prefixed or bare NIP-19 ids | hashtags
// BOLT11: optional "lightning:" prefix + lnbc/lntb/lnbcrt/lntbs + bech32 data (case-insensitive)
// NIP-19 ids can appear anywhere (with optional @ prefix that gets consumed)
const regex = /(?:lightning:)?(ln(?:bc|tb|bcrt|tbs)\d*[munp]?1[023456789acdefghjklmnpqrstuvwxyz]+)|((?:https?|wss?):\/\/[^\s]+)|nostr:(npub1|note1|nprofile1|nevent1|naddr1)([023456789acdefghjklmnpqrstuvwxyz]+)|@?(npub1|note1|nprofile1|nevent1|naddr1)([023456789acdefghjklmnpqrstuvwxyz]+)|(#[\p{L}\p{N}_]+)/giu;
const result: ContentToken[] = [];
let lastIndex = 0;
let match: RegExpExecArray | null;
let hadMatches = false;
while ((match = regex.exec(text)) !== null) {
let [fullMatch] = match;
const bolt11 = match[1];
let url = match[2];
const hashtag = match[7];
const { 3: nostrPrefix, 4: nostrData, 5: barePrefix, 6: bareData } = match;
const index = match.index;
hadMatches = true;
// Add text before this match
if (index > lastIndex) {
result.push({ type: 'text', value: text.substring(lastIndex, index) });
}
if (bolt11) {
result.push({ type: 'lightning-invoice', invoice: bolt11.toLowerCase() });
} else if (url) {
// Strip common trailing punctuation that's likely not part of the URL
// This handles cases like "(https://example.com)" or "Check this: https://example.com."
const trailingPunctMatch = url.match(/^(.*?)([.,;:!?)\]]+)$/);
if (trailingPunctMatch) {
const [, urlWithoutPunct] = trailingPunctMatch;
// Only strip the punctuation if the URL without it is still valid
if (urlWithoutPunct && urlWithoutPunct.length > 10) {
url = urlWithoutPunct;
fullMatch = urlWithoutPunct;
// The punctuation will be part of the next text token
}
}
// WebSocket relay URLs → link to internal relay page
if (/^wss?:\/\//i.test(url)) {
result.push({ type: 'relay-link', url });
lastIndex = index + fullMatch.length;
continue;
}
// Image URLs → render inline at their position in the text
if (IMAGE_URL_REGEX.test(url)) {
if (result.length > 0) {
const prev = result[result.length - 1];
if (prev.type === 'text') {
prev.value = prev.value.replace(/\s+$/, '');
}
}
result.push({ type: 'image-embed', url });
lastIndex = index + fullMatch.length;
// Strip leading whitespace that follows the image URL
const remaining = text.substring(lastIndex);
const leadingWs = remaining.match(/^\s+/);
if (leadingWs) {
lastIndex += leadingWs[0].length;
}
continue;
}
// Non-image media URLs (video, audio, webxdc) — render inline at their position.
if (EMBED_MEDIA_URL_REGEX.test(url)) {
if (result.length > 0) {
const prev = result[result.length - 1];
if (prev.type === 'text') {
prev.value = prev.value.replace(/\s+$/, '');
}
}
result.push({ type: 'media-embed', url });
lastIndex = index + fullMatch.length;
// Strip leading whitespace that follows the media URL
const remaining = text.substring(lastIndex);
const leadingWs = remaining.match(/^\s+/);
if (leadingWs) {
lastIndex += leadingWs[0].length;
}
continue;
}
// Determine if this URL ends a line (not followed by more text).
// A URL gets a preview card when nothing meaningful follows it on
// the same line (i.e., it ends the line or the content).
const afterUrl = text.substring(index + fullMatch.length);
const nextNewline = afterUrl.indexOf('\n');
const lineSuffix = nextNewline === -1 ? afterUrl : afterUrl.substring(0, nextNewline);
const isEndOfLine = lineSuffix.trim() === '';
// Check if the URL contains an naddr1 identifier → embed as Nostr event + preserve link
const naddrFromUrl = extractNaddrFromUrl(url);
if (naddrFromUrl) {
result.push({ type: 'naddr-embed', addr: naddrFromUrl, url });
} else if (isEndOfLine) {
// Standalone URL at end of line → rich embed (link preview)
result.push({ type: 'link-embed', url });
} else {
// Inline URL mid-sentence → plain clickable link
result.push({ type: 'inline-link', url });
}
} else if ((nostrPrefix && nostrData) || (barePrefix && bareData)) {
// Handle both nostr:-prefixed and bare NIP-19 identifiers
const prefix = nostrPrefix || barePrefix;
const data = nostrData || bareData;
try {
const nostrId = `${prefix}${data}`;
const decoded = nip19.decode(nostrId);
if (decoded.type === 'npub') {
result.push({ type: 'mention', pubkey: decoded.data });
} else if (decoded.type === 'nprofile') {
result.push({ type: 'mention', pubkey: decoded.data.pubkey });
} else if (decoded.type === 'note') {
result.push({ type: 'nevent-embed', eventId: decoded.data as string });
} else if (decoded.type === 'nevent') {
result.push({
type: 'nevent-embed',
eventId: decoded.data.id,
relays: decoded.data.relays,
author: decoded.data.author,
});
} else if (decoded.type === 'naddr') {
result.push({ type: 'naddr-embed', addr: decoded.data as AddrCoords });
} else {
result.push({ type: 'nostr-link', id: nostrId, raw: fullMatch });
}
} catch {
result.push({ type: 'text', value: fullMatch });
}
} else if (hashtag) {
const tag = hashtag.slice(1);
result.push({ type: 'hashtag', tag, raw: hashtag });
}
lastIndex = index + fullMatch.length;
}
// Add any remaining text
if (lastIndex < text.length) {
result.push({ type: 'text', value: text.substring(lastIndex) });
}
if (result.length === 0 && !hadMatches) {
result.push({ type: 'text', value: text });
}
// Enrich nevent-embed tokens with relay hints from `q` tags when the
// nevent URI itself didn't include any. This ensures quote posts whose
// inline nevent was encoded without relay hints can still resolve the
// quoted event via the relay hint stored in the q tag.
const qTagMap = new Map<string, { relay?: string; author?: string }>();
for (const tag of event.tags) {
if (tag[0] === 'q' && tag[1]) {
qTagMap.set(tag[1], { relay: tag[2] || undefined, author: tag[3] || undefined });
}
}
if (qTagMap.size > 0) {
for (const token of result) {
if (token.type === 'nevent-embed') {
const qInfo = qTagMap.get(token.eventId);
if (qInfo) {
if ((!token.relays || token.relays.length === 0) && qInfo.relay) {
token.relays = [qInfo.relay];
}
if (!token.author && qInfo.author) {
token.author = qInfo.author;
}
}
}
}
}
// Append media-embed tokens for imeta-declared media URLs not found in the content.
// Some clients attach audio/video/webxdc via imeta tags without including the URL in
// the content string. Without this, those attachments would be silently dropped.
// Only scan for text note kinds — other kinds (DMs, calendar events, etc.) may use
// imeta tags for different purposes.
const TEXT_NOTE_KINDS = new Set([1, 11, 1111]);
if (TEXT_NOTE_KINDS.has(event.kind)) {
const contentMediaUrls = new Set(
result.filter((t): t is { type: 'media-embed'; url: string } => t.type === 'media-embed').map((t) => t.url),
);
for (const tag of event.tags) {
if (tag[0] !== 'imeta') continue;
let rawUrl: string | undefined;
let mime: string | undefined;
for (let j = 1; j < tag.length; j++) {
const sp = tag[j].indexOf(' ');
if (sp === -1) continue;
const key = tag[j].slice(0, sp);
if (key === 'url') rawUrl = tag[j].slice(sp + 1);
else if (key === 'm') mime = tag[j].slice(sp + 1);
}
const url = sanitizeUrl(rawUrl);
if (!url || contentMediaUrls.has(url)) continue;
const isEmbeddableMedia = mime?.startsWith('audio/') || mime?.startsWith('video/')
|| mime === 'application/x-webxdc' || mime === 'application/vnd.webxdc+zip';
if (isEmbeddableMedia) {
result.push({ type: 'media-embed', url });
}
}
}
// Collapse excessive whitespace around block-level tokens (link-preview, nevent embed, etc.)
// Preserve formatting but prevent too much stacking with the card's own spacing.
for (let i = 0; i < result.length; i++) {
const token = result[i];
const isBlock = token.type === 'image-embed' || token.type === 'media-embed' || token.type === 'link-embed' || token.type === 'nevent-embed'
|| (token.type === 'naddr-embed' && !token.url) || token.type === 'lightning-invoice';
if (isBlock) {
// Strip all trailing whitespace from the preceding text token.
// The block's own margin (my-2.5) handles spacing, so preserved
// newlines just add redundant blank lines under whitespace-pre-wrap.
if (i > 0) {
const prev = result[i - 1];
if (prev.type === 'text') {
prev.value = prev.value.replace(/\s+$/, '');
}
}
// Strip all leading whitespace from the following text token.
if (i < result.length - 1) {
const next = result[i + 1];
if (next.type === 'text') {
next.value = next.value.replace(/^\s+/, '');
}
}
}
}
// Trim leading/trailing whitespace from edge text tokens
if (result.length > 0) {
const first = result[0];
if (first.type === 'text') {
first.value = first.value.replace(/^\s+/, '');
}
const last = result[result.length - 1];
if (last.type === 'text') {
last.value = last.value.replace(/\s+$/, '');
}
}
// Filter out empty text tokens
return result.filter((t) => !(t.type === 'text' && t.value === ''));
}, [event]);
// Build emoji map for NIP-30 custom emoji rendering.
// Merge the event's own emoji tags with the viewer's custom emoji collection
// so shortcodes render even when the published event omitted the tag.
const { emojis: viewerEmojis } = useCustomEmojis();
const emojiMap = useMemo(() => {
const map = buildEmojiMap(event.tags);
// Viewer's collection is a fallback — event tags take priority
for (const e of viewerEmojis) {
if (!map.has(e.shortcode)) {
map.set(e.shortcode, e.url);
}
}
return map;
}, [event.tags, viewerEmojis]);
// Parse imeta tags — used by ImageGallery (dim/blurhash) and inline media embeds
const imetaMap = useMemo(() => parseImetaMap(event.tags), [event.tags]);
// Only fetch author data when there are media embeds that need it (video artist, audio avatar)
const hasMedia = tokens.some((t) => t.type === 'media-embed');
const author = useAuthor(hasMedia ? event.pubkey : undefined);
const authorMetadata = author.data?.metadata;
const authorDisplayName = useMemo(
() => getDisplayName(authorMetadata, event.pubkey),
[authorMetadata, event.pubkey],
);
// Group consecutive image-embed tokens (≥2) into image-gallery tokens
const groupedTokens = useMemo(() => {
const result: ContentToken[] = [];
let i = 0;
while (i < tokens.length) {
const token = tokens[i];
if (token.type === 'image-embed') {
// Collect this and any immediately following image-embed tokens
const run: string[] = [token.url];
let j = i + 1;
while (j < tokens.length && tokens[j].type === 'image-embed') {
run.push((tokens[j] as { type: 'image-embed'; url: string }).url);
j++;
}
if (run.length >= 2) {
result.push({ type: 'image-gallery', urls: run });
} else {
result.push(token);
}
i = j;
} else {
result.push(token);
i++;
}
}
return result;
}, [tokens]);
// Collect all inline image URLs (in order) for the shared lightbox
const allImages = useMemo(
() => groupedTokens.flatMap((t) => {
if (t.type === 'image-embed') return [t.url];
if (t.type === 'image-gallery') return t.urls;
return [];
}),
[groupedTokens],
);
// Shared lightbox state for inline images
const [lightboxIndex, setLightboxIndex] = useState<number | null>(null);
const closeLightbox = useCallback(() => setLightboxIndex(null), []);
const goNext = useCallback(() => setLightboxIndex((p) => (p !== null ? (p + 1) % allImages.length : null)), [allImages.length]);
const goPrev = useCallback(() => setLightboxIndex((p) => (p !== null ? (p - 1 + allImages.length) % allImages.length : null)), [allImages.length]);
// Check if content is only emojis — unicode and/or NIP-30 custom emojis (single text token)
const isEmojiOnly = groupedTokens.length === 1 && groupedTokens[0].type === 'text' && isOnlyEmojisOrCustom(groupedTokens[0].value, emojiMap);
// Build a map from grouped token index → starting image list index for lightbox positioning
const tokenImageIndex = useMemo(() => {
const map = new Map<number, number>();
let imgCount = 0;
groupedTokens.forEach((t, i) => {
if (t.type === 'image-embed') {
map.set(i, imgCount++);
} else if (t.type === 'image-gallery') {
map.set(i, imgCount);
imgCount += t.urls.length;
}
});
return map;
}, [groupedTokens]);
return (
<div dir="auto" className={cn('whitespace-pre-wrap wrap-break-word overflow-hidden', className, isEmojiOnly && 'text-5xl leading-tight')}>
{groupedTokens.map((token, i) => {
switch (token.type) {
case 'text':
return <span key={i}>{linkifyFlags(emojify(token.value, emojiMap, isEmojiOnly ? 'inline h-12 w-12 object-contain align-text-bottom' : undefined))}</span>;
case 'image-embed': {
if (disableEmbeds || disableMediaEmbeds) {
// In preview contexts, replace image URLs with a newline so
// text flow is preserved without showing raw URLs.
return <span key={i}>{'\n'}</span>;
}
const imgIndex = tokenImageIndex.get(i) ?? 0;
return (
<InlineImage
key={i}
url={token.url}
onClick={(e) => { e.stopPropagation(); setLightboxIndex(imgIndex); }}
/>
);
}
case 'image-gallery': {
if (disableEmbeds || disableMediaEmbeds) {
return <span key={i}>{token.urls.map(() => '\n').join('')}</span>;
}
const galleryStartIndex = tokenImageIndex.get(i) ?? 0;
const galleryLightboxIndex =
lightboxIndex !== null &&
lightboxIndex >= galleryStartIndex &&
lightboxIndex < galleryStartIndex + token.urls.length
? lightboxIndex - galleryStartIndex
: null;
return (
<ImageGallery
key={i}
images={token.urls}
maxVisible={4}
maxGridHeight="480px"
imetaMap={imetaMap}
lightboxIndex={galleryLightboxIndex}
onLightboxOpen={(idx) => { setLightboxIndex(galleryStartIndex + idx); }}
onLightboxClose={closeLightbox}
/>
);
}
case 'link-embed':
if (disableEmbeds) {
return (
<a
key={i}
href={token.url}
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline break-all"
onClick={(e) => e.stopPropagation()}
>
{token.url}
</a>
);
}
return <LinkEmbed key={i} url={token.url} className="my-2.5" hideImage={hideEmbedImages} />;
case 'inline-link':
return (
<a
key={i}
href={token.url}
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline break-all"
onClick={(e) => e.stopPropagation()}
>
{token.url}
</a>
);
case 'media-embed': {
if (disableEmbeds || disableMediaEmbeds) {
return <span key={i}>{'\n'}</span>;
}
const imeta = imetaMap.get(token.url);
const mime = imeta?.mime ?? '';
const isWebxdc = mime === 'application/x-webxdc' || mime === 'application/vnd.webxdc+zip' || token.url.endsWith('.xdc');
const isAudio = mime.startsWith('audio/') || /\.(mp3|wav|ogg|flac|m4a|aac|opus)(\?[^\s]*)?$/i.test(token.url);
if (isWebxdc && imeta) {
return <WebxdcEmbed key={i} url={token.url} uuid={imeta.webxdc} name={imeta.summary} icon={imeta.thumbnail} />;
}
if (isAudio) {
return (
<AudioVisualizer
key={i}
src={token.url}
mime={imeta?.mime}
avatarUrl={authorMetadata?.picture}
avatarFallback={authorDisplayName[0]?.toUpperCase() ?? '?'}
avatarShape={getAvatarShape(authorMetadata)}
/>
);
}
// Default: video
return (
<VideoPlayer
key={i}
src={token.url}
poster={imeta?.thumbnail}
dim={imeta?.dim}
blurhash={imeta?.blurhash}
artist={authorDisplayName}
/>
);
}
case 'nevent-embed':
if (disableNoteEmbeds) {
const neventId = nip19.neventEncode({ id: token.eventId, ...(token.author ? { author: token.author } : {}), ...(token.relays?.length ? { relays: token.relays } : {}) });
return (
<Link
key={i}
to={`/${neventId}`}
className="text-primary hover:underline break-all"
onClick={(e) => e.stopPropagation()}
>
{neventId.slice(0, 16)}…
</Link>
);
}
return <EmbeddedNote key={i} eventId={token.eventId} relays={token.relays} authorHint={token.author} className="my-2.5" />;
case 'naddr-embed':
if (disableNoteEmbeds) {
const naddrId = nip19.naddrEncode({ kind: token.addr.kind, pubkey: token.addr.pubkey, identifier: token.addr.identifier });
return (
<Link
key={i}
to={`/${naddrId}`}
className="text-primary hover:underline break-all"
onClick={(e) => e.stopPropagation()}
>
{naddrId.slice(0, 16)}…
</Link>
);
}
return (
<span key={i}>
{token.url && (
<a
href={token.url}
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:underline break-all"
onClick={(e) => e.stopPropagation()}
>
{token.url}
</a>
)}
<EmbeddedNaddr addr={token.addr} className="my-2.5" />
</span>
);
case 'mention':
return <NostrMention key={i} pubkey={token.pubkey} />;
case 'nostr-link':
return (
<Link
key={i}
to={`/${token.id}`}
className="text-primary hover:underline break-all"
onClick={(e) => e.stopPropagation()}
>
{token.raw}
</Link>
);
case 'hashtag':
return (
<Link
key={i}
to={`/t/${token.tag}`}
className="text-primary hover:underline break-all"
onClick={(e) => e.stopPropagation()}
>
{token.raw}
</Link>
);
case 'relay-link':
return (
<Link
key={i}
to={`/r/${encodeURIComponent(token.url)}`}
className="text-primary hover:underline break-all"
onClick={(e) => e.stopPropagation()}
>
{token.url}
</Link>
);
case 'lightning-invoice':
if (disableEmbeds) {
return <span key={i} className="text-primary break-all">{token.invoice}</span>;
}
return <LightningInvoiceCard key={i} invoice={token.invoice} />;
}
})}
{/* Shared lightbox for standalone inline images (not gallery groups) */}
{lightboxIndex !== null && !groupedTokens.some(
(t, i) =>
t.type === 'image-gallery' &&
lightboxIndex >= (tokenImageIndex.get(i) ?? 0) &&
lightboxIndex < (tokenImageIndex.get(i) ?? 0) + t.urls.length,
) && (
<Lightbox
images={allImages}
currentIndex={lightboxIndex}
onClose={closeLightbox}
onNext={goNext}
onPrev={goPrev}
/>
)}
</div>
);
}
/** Inline image thumbnail that opens the shared lightbox on click.
* Uses a min-height placeholder to prevent layout shifts while loading. */
function InlineImage({ url, onClick }: { url: string; onClick: (e: React.MouseEvent) => void }) {
const { src, onError } = useBlossomFallback(url);
const [loaded, setLoaded] = useState(false);
return (
<button
type="button"
className="block my-2 rounded-lg overflow-hidden w-full cursor-pointer focus:outline-none focus-visible:ring-2 focus-visible:ring-primary"
onClick={onClick}
>
<div className={cn('relative w-full rounded-lg overflow-hidden', !loaded && 'bg-muted')} style={!loaded ? { minHeight: 200 } : undefined}>
<img
src={src}
alt=""
className="block w-full h-auto rounded-lg hover:opacity-90 transition-opacity"
loading="lazy"
onLoad={() => setLoaded(true)}
onError={() => { setLoaded(true); onError(); }}
/>
</div>
</button>
);
}
function NostrMention({ pubkey }: { pubkey: string }) {
const author = useAuthor(pubkey);
const hasRealName = !!author.data?.metadata?.name;
const displayName = author.data?.metadata?.name ?? 'Anonymous';
const profileUrl = useProfileUrl(pubkey, author.data?.metadata);
return (
<ProfileHoverCard pubkey={pubkey} asChild>
<Link
to={profileUrl}
className={cn(
'font-medium hover:underline',
hasRealName
? 'text-primary'
: 'text-muted-foreground hover:text-foreground',
)}
onClick={(e) => e.stopPropagation()}
>
@{author.data?.event ? (
<EmojifiedText tags={author.data.event.tags}>{displayName}</EmojifiedText>
) : displayName}
</Link>
</ProfileHoverCard>
);
}
@@ -0,0 +1,19 @@
import type { ReactNode } from 'react';
interface ProfileHoverCardProps {
pubkey: string;
asChild?: boolean;
children: ReactNode;
}
/**
* Minimal profile hover card — a passthrough wrapper.
*
* Ditto's richer `ProfileHoverCard` shows an avatar, display name,
* bio, follower count, and follow button on hover. To replicate,
* wrap with `@/components/ui/hover-card` and pull metadata via
* `useAuthor(pubkey)` inside the hover content.
*/
export function ProfileHoverCard({ children }: ProfileHoverCardProps) {
return <>{children}</>;
}
@@ -0,0 +1,43 @@
import { cn } from '@/lib/utils';
interface VideoPlayerProps {
src: string;
poster?: string;
/** Pixel dimensions from NIP-94 `dim` tag, e.g. "1280x720". */
dim?: string;
/** Blurhash placeholder from NIP-94 `blurhash` tag. */
blurhash?: string;
artist?: string;
className?: string;
}
/**
* Minimal inline video player — renders a native `<video controls>`.
*
* Ditto's richer `VideoPlayer` renders a blurhash placeholder, respects
* `dim` for correct aspect ratio, supports background scrubbing, picture-in-picture,
* and lightbox playback. Replace this stub with a richer player as needed.
*/
export function VideoPlayer({ src, poster, dim, blurhash: _blurhash, artist: _artist, className }: VideoPlayerProps) {
// Compute aspect ratio from "WxH" if provided
let aspectRatio: string | undefined;
if (dim) {
const match = dim.match(/^(\d+)x(\d+)$/);
if (match) {
aspectRatio = `${match[1]} / ${match[2]}`;
}
}
return (
<video
src={src}
poster={poster}
controls
preload="metadata"
playsInline
className={cn('block rounded-lg my-2.5 w-full max-h-[480px] bg-black', className)}
style={aspectRatio ? { aspectRatio } : undefined}
onClick={(e) => e.stopPropagation()}
/>
);
}
@@ -0,0 +1,40 @@
import { cn } from '@/lib/utils';
interface WebxdcEmbedProps {
url: string;
uuid?: string;
name?: string;
icon?: string;
className?: string;
}
/**
* Minimal WebXDC app embed — renders a download/launch link.
*
* WebXDC is a self-contained interactive app packaged as a .xdc zip.
* Ditto's richer `WebxdcEmbed` renders the app in an iframe with a
* message-passing bridge to Nostr for state sync. Replace this stub
* with a full WebXDC host when needed; see https://webxdc.org for the spec.
*/
export function WebxdcEmbed({ url, name, icon, className }: WebxdcEmbedProps) {
return (
<a
href={url}
target="_blank"
rel="noopener noreferrer"
onClick={(e) => e.stopPropagation()}
className={cn(
'flex items-center gap-3 border rounded-lg px-3 py-2 my-2.5 hover:bg-muted/50 transition-colors text-sm',
className,
)}
>
{icon && (
<img src={icon} alt="" className="w-10 h-10 rounded object-cover shrink-0" />
)}
<div className="min-w-0 flex-1">
<div className="font-medium truncate">{name ?? 'WebXDC app'}</div>
<div className="text-xs text-muted-foreground truncate">{url}</div>
</div>
</a>
);
}
@@ -0,0 +1,21 @@
import { useState, useCallback } from 'react';
/**
* Blossom-server fallback hook.
*
* When an image URL is hosted on a Blossom server that goes down,
* apps can retry the same hash on a different server. This minimal
* stub simply returns the original URL and a no-op `onError` handler.
* Replace with a richer implementation that parses the URL's hash
* suffix and rotates through the viewer's BUD-03 "User Server List"
* (kind 10063) or an app-configured server list.
*/
export function useBlossomFallback(url: string): { src: string; onError: () => void } {
const [src, setSrc] = useState(url);
const onError = useCallback(() => {
// Stub: no-op. A real implementation would swap `src` to the next
// known Blossom mirror here.
setSrc((prev) => prev);
}, []);
return { src, onError };
}
@@ -0,0 +1,13 @@
/**
* Viewer's own custom emoji collection (NIP-30).
*
* This minimal stub returns an empty list. To enable the viewer's
* custom emojis as a fallback when posts don't carry their own
* `emoji` tags, replace this implementation with one that fetches
* the user's kind 10030 "Emoji List" event and any kind 30030
* "Emoji Set" events it references, then exposes every shortcode
* → URL pair here.
*/
export function useCustomEmojis(): { emojis: Array<{ shortcode: string; url: string }> } {
return { emojis: [] };
}
@@ -0,0 +1,17 @@
import { nip19 } from 'nostr-tools';
import type { NostrMetadata } from '@nostrify/nostrify';
/**
* Returns the internal URL for a user's profile page.
*
* Defaults to `/<npub1...>`, matching the template's `/:nip19`
* route in AppRouter. If a user's metadata has a `nip05` identifier
* you want to prefer, swap the return statement accordingly
* (e.g. `/@${nip05}` with a corresponding `/:handle` route).
*
* The `metadata` argument is accepted for parity with richer
* implementations that route by NIP-05 handle; the stub ignores it.
*/
export function useProfileUrl(pubkey: string, _metadata?: NostrMetadata): string {
return `/${nip19.npubEncode(pubkey)}`;
}
@@ -0,0 +1,27 @@
/**
* An avatar shape is stored in kind-0 metadata as the `shape` property.
* Typically an emoji glyph used as a mask (e.g. "🐱", "⭐").
*
* This minimal stub exposes just enough surface for `NoteContent` to
* read the shape and pass it into `AudioVisualizer`. The stubbed
* `AudioVisualizer` ignores it; a richer implementation would use
* the shape to generate a CSS mask URL for the avatar.
*/
export type AvatarShape = string;
/**
* Extract the avatar shape from Nostr metadata. Returns `undefined`
* when the metadata is missing or has no `shape` field.
*/
export function getAvatarShape(
metadata: { [key: string]: unknown } | undefined,
): AvatarShape | undefined {
if (!metadata) return undefined;
const shape = metadata.shape;
if (typeof shape !== 'string') return undefined;
// Light guard: only return short, non-ASCII values (emoji-like)
if (shape.length === 0 || shape.length > 20) return undefined;
// eslint-disable-next-line no-control-regex
if (!/[^\x00-\x7F]/.test(shape)) return undefined;
return shape;
}
@@ -0,0 +1,316 @@
/** ISO 3166-1 alpha-2 country code to country name and flag emoji mapping. */
export const COUNTRIES: Record<string, { name: string; flag: string }> = {
AF: { name: 'Afghanistan', flag: '🇦🇫' },
AL: { name: 'Albania', flag: '🇦🇱' },
DZ: { name: 'Algeria', flag: '🇩🇿' },
AD: { name: 'Andorra', flag: '🇦🇩' },
AO: { name: 'Angola', flag: '🇦🇴' },
AG: { name: 'Antigua and Barbuda', flag: '🇦🇬' },
AR: { name: 'Argentina', flag: '🇦🇷' },
AM: { name: 'Armenia', flag: '🇦🇲' },
AU: { name: 'Australia', flag: '🇦🇺' },
AT: { name: 'Austria', flag: '🇦🇹' },
AZ: { name: 'Azerbaijan', flag: '🇦🇿' },
BS: { name: 'Bahamas', flag: '🇧🇸' },
BH: { name: 'Bahrain', flag: '🇧🇭' },
BD: { name: 'Bangladesh', flag: '🇧🇩' },
BB: { name: 'Barbados', flag: '🇧🇧' },
BY: { name: 'Belarus', flag: '🇧🇾' },
BE: { name: 'Belgium', flag: '🇧🇪' },
BZ: { name: 'Belize', flag: '🇧🇿' },
BJ: { name: 'Benin', flag: '🇧🇯' },
BT: { name: 'Bhutan', flag: '🇧🇹' },
BO: { name: 'Bolivia', flag: '🇧🇴' },
BA: { name: 'Bosnia and Herzegovina', flag: '🇧🇦' },
BW: { name: 'Botswana', flag: '🇧🇼' },
BR: { name: 'Brazil', flag: '🇧🇷' },
BN: { name: 'Brunei', flag: '🇧🇳' },
BG: { name: 'Bulgaria', flag: '🇧🇬' },
BF: { name: 'Burkina Faso', flag: '🇧🇫' },
BI: { name: 'Burundi', flag: '🇧🇮' },
CV: { name: 'Cabo Verde', flag: '🇨🇻' },
KH: { name: 'Cambodia', flag: '🇰🇭' },
CM: { name: 'Cameroon', flag: '🇨🇲' },
CA: { name: 'Canada', flag: '🇨🇦' },
CF: { name: 'Central African Republic', flag: '🇨🇫' },
TD: { name: 'Chad', flag: '🇹🇩' },
CL: { name: 'Chile', flag: '🇨🇱' },
CN: { name: 'China', flag: '🇨🇳' },
CO: { name: 'Colombia', flag: '🇨🇴' },
KM: { name: 'Comoros', flag: '🇰🇲' },
CG: { name: 'Congo', flag: '🇨🇬' },
CD: { name: 'Congo (DRC)', flag: '🇨🇩' },
CR: { name: 'Costa Rica', flag: '🇨🇷' },
CI: { name: "Cote d'Ivoire", flag: '🇨🇮' },
HR: { name: 'Croatia', flag: '🇭🇷' },
CU: { name: 'Cuba', flag: '🇨🇺' },
CY: { name: 'Cyprus', flag: '🇨🇾' },
CZ: { name: 'Czechia', flag: '🇨🇿' },
DK: { name: 'Denmark', flag: '🇩🇰' },
DJ: { name: 'Djibouti', flag: '🇩🇯' },
DM: { name: 'Dominica', flag: '🇩🇲' },
DO: { name: 'Dominican Republic', flag: '🇩🇴' },
EC: { name: 'Ecuador', flag: '🇪🇨' },
EG: { name: 'Egypt', flag: '🇪🇬' },
SV: { name: 'El Salvador', flag: '🇸🇻' },
GQ: { name: 'Equatorial Guinea', flag: '🇬🇶' },
ER: { name: 'Eritrea', flag: '🇪🇷' },
EE: { name: 'Estonia', flag: '🇪🇪' },
SZ: { name: 'Eswatini', flag: '🇸🇿' },
ET: { name: 'Ethiopia', flag: '🇪🇹' },
FJ: { name: 'Fiji', flag: '🇫🇯' },
FI: { name: 'Finland', flag: '🇫🇮' },
FR: { name: 'France', flag: '🇫🇷' },
GA: { name: 'Gabon', flag: '🇬🇦' },
GM: { name: 'Gambia', flag: '🇬🇲' },
GE: { name: 'Georgia', flag: '🇬🇪' },
DE: { name: 'Germany', flag: '🇩🇪' },
GH: { name: 'Ghana', flag: '🇬🇭' },
GR: { name: 'Greece', flag: '🇬🇷' },
GD: { name: 'Grenada', flag: '🇬🇩' },
GT: { name: 'Guatemala', flag: '🇬🇹' },
GN: { name: 'Guinea', flag: '🇬🇳' },
GW: { name: 'Guinea-Bissau', flag: '🇬🇼' },
GY: { name: 'Guyana', flag: '🇬🇾' },
HT: { name: 'Haiti', flag: '🇭🇹' },
HN: { name: 'Honduras', flag: '🇭🇳' },
HU: { name: 'Hungary', flag: '🇭🇺' },
IS: { name: 'Iceland', flag: '🇮🇸' },
IN: { name: 'India', flag: '🇮🇳' },
ID: { name: 'Indonesia', flag: '🇮🇩' },
IR: { name: 'Iran', flag: '🇮🇷' },
IQ: { name: 'Iraq', flag: '🇮🇶' },
IE: { name: 'Ireland', flag: '🇮🇪' },
IL: { name: 'Israel', flag: '🇮🇱' },
IT: { name: 'Italy', flag: '🇮🇹' },
JM: { name: 'Jamaica', flag: '🇯🇲' },
JP: { name: 'Japan', flag: '🇯🇵' },
JO: { name: 'Jordan', flag: '🇯🇴' },
KZ: { name: 'Kazakhstan', flag: '🇰🇿' },
KE: { name: 'Kenya', flag: '🇰🇪' },
KI: { name: 'Kiribati', flag: '🇰🇮' },
KP: { name: 'North Korea', flag: '🇰🇵' },
KR: { name: 'South Korea', flag: '🇰🇷' },
KW: { name: 'Kuwait', flag: '🇰🇼' },
KG: { name: 'Kyrgyzstan', flag: '🇰🇬' },
LA: { name: 'Laos', flag: '🇱🇦' },
LV: { name: 'Latvia', flag: '🇱🇻' },
LB: { name: 'Lebanon', flag: '🇱🇧' },
LS: { name: 'Lesotho', flag: '🇱🇸' },
LR: { name: 'Liberia', flag: '🇱🇷' },
LY: { name: 'Libya', flag: '🇱🇾' },
LI: { name: 'Liechtenstein', flag: '🇱🇮' },
LT: { name: 'Lithuania', flag: '🇱🇹' },
LU: { name: 'Luxembourg', flag: '🇱🇺' },
MG: { name: 'Madagascar', flag: '🇲🇬' },
MW: { name: 'Malawi', flag: '🇲🇼' },
MY: { name: 'Malaysia', flag: '🇲🇾' },
MV: { name: 'Maldives', flag: '🇲🇻' },
ML: { name: 'Mali', flag: '🇲🇱' },
MT: { name: 'Malta', flag: '🇲🇹' },
MH: { name: 'Marshall Islands', flag: '🇲🇭' },
MR: { name: 'Mauritania', flag: '🇲🇷' },
MU: { name: 'Mauritius', flag: '🇲🇺' },
MX: { name: 'Mexico', flag: '🇲🇽' },
FM: { name: 'Micronesia', flag: '🇫🇲' },
MD: { name: 'Moldova', flag: '🇲🇩' },
MC: { name: 'Monaco', flag: '🇲🇨' },
MN: { name: 'Mongolia', flag: '🇲🇳' },
ME: { name: 'Montenegro', flag: '🇲🇪' },
MA: { name: 'Morocco', flag: '🇲🇦' },
MZ: { name: 'Mozambique', flag: '🇲🇿' },
MM: { name: 'Myanmar', flag: '🇲🇲' },
NA: { name: 'Namibia', flag: '🇳🇦' },
NR: { name: 'Nauru', flag: '🇳🇷' },
NP: { name: 'Nepal', flag: '🇳🇵' },
NL: { name: 'Netherlands', flag: '🇳🇱' },
NZ: { name: 'New Zealand', flag: '🇳🇿' },
NI: { name: 'Nicaragua', flag: '🇳🇮' },
NE: { name: 'Niger', flag: '🇳🇪' },
NG: { name: 'Nigeria', flag: '🇳🇬' },
MK: { name: 'North Macedonia', flag: '🇲🇰' },
NO: { name: 'Norway', flag: '🇳🇴' },
OM: { name: 'Oman', flag: '🇴🇲' },
PK: { name: 'Pakistan', flag: '🇵🇰' },
PW: { name: 'Palau', flag: '🇵🇼' },
PA: { name: 'Panama', flag: '🇵🇦' },
PG: { name: 'Papua New Guinea', flag: '🇵🇬' },
PY: { name: 'Paraguay', flag: '🇵🇾' },
PE: { name: 'Peru', flag: '🇵🇪' },
PH: { name: 'Philippines', flag: '🇵🇭' },
PL: { name: 'Poland', flag: '🇵🇱' },
PT: { name: 'Portugal', flag: '🇵🇹' },
QA: { name: 'Qatar', flag: '🇶🇦' },
RO: { name: 'Romania', flag: '🇷🇴' },
RU: { name: 'Russia', flag: '🇷🇺' },
RW: { name: 'Rwanda', flag: '🇷🇼' },
KN: { name: 'Saint Kitts and Nevis', flag: '🇰🇳' },
LC: { name: 'Saint Lucia', flag: '🇱🇨' },
VC: { name: 'Saint Vincent and the Grenadines', flag: '🇻🇨' },
WS: { name: 'Samoa', flag: '🇼🇸' },
SM: { name: 'San Marino', flag: '🇸🇲' },
ST: { name: 'Sao Tome and Principe', flag: '🇸🇹' },
SA: { name: 'Saudi Arabia', flag: '🇸🇦' },
SN: { name: 'Senegal', flag: '🇸🇳' },
RS: { name: 'Serbia', flag: '🇷🇸' },
SC: { name: 'Seychelles', flag: '🇸🇨' },
SL: { name: 'Sierra Leone', flag: '🇸🇱' },
SG: { name: 'Singapore', flag: '🇸🇬' },
SK: { name: 'Slovakia', flag: '🇸🇰' },
SI: { name: 'Slovenia', flag: '🇸🇮' },
SB: { name: 'Solomon Islands', flag: '🇸🇧' },
SO: { name: 'Somalia', flag: '🇸🇴' },
ZA: { name: 'South Africa', flag: '🇿🇦' },
SS: { name: 'South Sudan', flag: '🇸🇸' },
ES: { name: 'Spain', flag: '🇪🇸' },
LK: { name: 'Sri Lanka', flag: '🇱🇰' },
SD: { name: 'Sudan', flag: '🇸🇩' },
SR: { name: 'Suriname', flag: '🇸🇷' },
SE: { name: 'Sweden', flag: '🇸🇪' },
CH: { name: 'Switzerland', flag: '🇨🇭' },
SY: { name: 'Syria', flag: '🇸🇾' },
TW: { name: 'Taiwan', flag: '🇹🇼' },
TJ: { name: 'Tajikistan', flag: '🇹🇯' },
TZ: { name: 'Tanzania', flag: '🇹🇿' },
TH: { name: 'Thailand', flag: '🇹🇭' },
TL: { name: 'Timor-Leste', flag: '🇹🇱' },
TG: { name: 'Togo', flag: '🇹🇬' },
TO: { name: 'Tonga', flag: '🇹🇴' },
TT: { name: 'Trinidad and Tobago', flag: '🇹🇹' },
TN: { name: 'Tunisia', flag: '🇹🇳' },
TR: { name: 'Turkey', flag: '🇹🇷' },
TM: { name: 'Turkmenistan', flag: '🇹🇲' },
TV: { name: 'Tuvalu', flag: '🇹🇻' },
UG: { name: 'Uganda', flag: '🇺🇬' },
UA: { name: 'Ukraine', flag: '🇺🇦' },
AE: { name: 'United Arab Emirates', flag: '🇦🇪' },
GB: { name: 'United Kingdom', flag: '🇬🇧' },
US: { name: 'United States', flag: '🇺🇸' },
UY: { name: 'Uruguay', flag: '🇺🇾' },
UZ: { name: 'Uzbekistan', flag: '🇺🇿' },
VU: { name: 'Vanuatu', flag: '🇻🇺' },
VA: { name: 'Vatican City', flag: '🇻🇦' },
VE: { name: 'Venezuela', flag: '🇻🇪' },
VN: { name: 'Vietnam', flag: '🇻🇳' },
YE: { name: 'Yemen', flag: '🇾🇪' },
ZM: { name: 'Zambia', flag: '🇿🇲' },
ZW: { name: 'Zimbabwe', flag: '🇿🇼' },
};
/** Pre-sorted array of country entries for searching. */
const COUNTRY_LIST = Object.entries(COUNTRIES)
.map(([code, { name, flag }]) => ({ code, name, flag }))
.sort((a, b) => a.name.localeCompare(b.name));
export type CountryEntry = typeof COUNTRY_LIST[number];
export interface CountryMatch {
country: CountryEntry;
exact: boolean;
}
/**
* Find a single country matching the query (case-insensitive).
* Matches exact code/name or name prefix (e.g. "angol" -> Angola).
* Returns the match with an `exact` flag indicating whether it was a full match.
*/
export function searchCountry(query: string): CountryMatch | null {
const q = query.trim().toLowerCase();
if (q.length < 2) return null;
// Exact code match
for (const entry of COUNTRY_LIST) {
if (entry.code.toLowerCase() === q) {
return { country: entry, exact: true };
}
}
// Exact name match
for (const entry of COUNTRY_LIST) {
if (entry.name.toLowerCase() === q) {
return { country: entry, exact: true };
}
}
// Prefix match (shortest name = most specific)
let best: CountryEntry | null = null;
for (const entry of COUNTRY_LIST) {
if (entry.name.toLowerCase().startsWith(q)) {
if (!best || entry.name.length < best.name.length) {
best = entry;
}
}
}
return best ? { country: best, exact: false } : null;
}
/**
* Map of ISO 3166-1 alpha-2 codes to their Wikipedia article titles,
* only for countries whose common name differs from the Wikipedia title.
*/
const WIKIPEDIA_TITLES: Record<string, string> = {
BS: 'The Bahamas',
BO: 'Bolivia',
CG: 'Republic of the Congo',
CD: 'Democratic Republic of the Congo',
CI: 'Ivory Coast',
CZ: 'Czech Republic',
SZ: 'Eswatini',
GM: 'The Gambia',
GE: 'Georgia (country)',
IR: 'Iran',
KP: 'North Korea',
KR: 'South Korea',
LA: 'Laos',
FM: 'Federated States of Micronesia',
MD: 'Moldova',
MM: 'Myanmar',
MK: 'North Macedonia',
RU: 'Russia',
ST: 'São Tomé and Príncipe',
SY: 'Syria',
TW: 'Taiwan',
TZ: 'Tanzania',
GB: 'United Kingdom',
US: 'United States',
VE: 'Venezuela',
VN: 'Vietnam',
};
/** Get the Wikipedia article title for a country. */
export function getWikipediaTitle(code: string): string | null {
const upper = code.toUpperCase();
if (upper.includes('-')) {
// Subdivision — fall back to parent country
const countryCode = upper.split('-')[0];
const country = COUNTRIES[countryCode];
if (!country) return null;
return WIKIPEDIA_TITLES[countryCode] ?? country.name;
}
const country = COUNTRIES[upper];
if (!country) return null;
return WIKIPEDIA_TITLES[upper] ?? country.name;
}
/** Get country info from an ISO 3166 code (country or subdivision). */
export function getCountryInfo(code: string): { name: string; flag: string; subdivision?: string } | null {
const upper = code.toUpperCase();
// Handle subdivision codes like "US-CA"
if (upper.includes('-')) {
const [countryCode] = upper.split('-');
const country = COUNTRIES[countryCode];
if (!country) return null;
return {
name: country.name,
flag: country.flag,
subdivision: upper,
};
}
const country = COUNTRIES[upper];
if (!country) return null;
return { name: country.name, flag: country.flag };
}
@@ -0,0 +1,77 @@
import type { NostrEvent } from '@nostrify/nostrify';
/**
* Checks if a string is a NIP-30 custom emoji shortcode (`:shortcode:` format).
*/
export function isCustomEmoji(content: string): boolean {
return /^:[a-zA-Z0-9_-]+:$/.test(content);
}
/**
* Extracts the custom emoji URL from a NostrEvent's tags for a given shortcode.
* The shortcode should include the colons (e.g., `:soapbox:`).
*/
export function getCustomEmojiUrl(shortcode: string, tags: string[][]): string | undefined {
const name = shortcode.slice(1, -1); // Remove surrounding colons
const emojiTag = tags.find(([tagName, tagShortcode]) => tagName === 'emoji' && tagShortcode === name);
return emojiTag?.[2];
}
/**
* Builds a map of shortcode -> URL from an event's emoji tags.
*/
export function buildEmojiMap(tags: string[][]): Map<string, string> {
const map = new Map<string, string>();
for (const tag of tags) {
if (tag[0] === 'emoji' && tag[1] && tag[2]) {
map.set(tag[1], tag[2]);
}
}
return map;
}
/**
* Represents a resolved reaction emoji that can be rendered.
* For custom emojis, includes the URL; for unicode, just the content string.
*/
export interface ResolvedEmoji {
/** The display content — unicode emoji string or `:shortcode:` */
content: string;
/** For custom emojis, the image URL. Undefined for unicode emojis. */
url?: string;
/** For custom emojis, the shortcode name (without colons). */
name?: string;
}
/**
* Checks whether a kind 7 reaction event is valid.
* Custom emoji reactions (`:shortcode:` content) are invalid without a matching `emoji` tag.
*/
export function isValidReaction(event: NostrEvent): boolean {
const content = event.content.trim();
const emoji = (content === '+' || content === '') ? '+' : content;
if (isCustomEmoji(emoji)) {
return getCustomEmojiUrl(emoji, event.tags) !== undefined;
}
return true;
}
/**
* Resolves a reaction emoji from a kind 7 event into a ResolvedEmoji.
* Returns `undefined` for malformed custom emoji reactions (missing emoji tag).
*/
export function resolveReactionEmoji(event: NostrEvent): ResolvedEmoji | undefined {
const content = event.content.trim();
const emoji = (content === '+' || content === '') ? '👍' : content === '-' ? '👎' : content;
if (isCustomEmoji(emoji)) {
const url = getCustomEmojiUrl(emoji, event.tags);
if (url) {
return { content: emoji, url, name: emoji.slice(1, -1) };
}
// Malformed: custom emoji shortcode without a matching emoji tag
return undefined;
}
return { content: emoji };
}
@@ -0,0 +1,14 @@
import type { NostrMetadata } from '@nostrify/nostrify';
/**
* Get a display name for a user.
* Uses metadata.name if available, otherwise falls back to "Anonymous".
* Visual truncation is handled by CSS (`truncate` class) on the containing element
* to avoid breaking NIP-30 custom emoji shortcodes.
*/
export function getDisplayName(
metadata: NostrMetadata | undefined,
_pubkey: string,
): string {
return metadata?.name || 'Anonymous';
}
@@ -0,0 +1,43 @@
/** Parsed imeta entry from NIP-94 tags. */
export interface ImetaEntry {
url: string;
thumbnail?: string;
mime?: string;
/** Summary text (used as webxdc app name for webxdc attachments). */
summary?: string;
/** Webxdc session UUID — present when the attachment is a stateful webxdc app. */
webxdc?: string;
/** Pixel dimensions from NIP-94 `dim` tag, e.g. "1280x720". */
dim?: string;
/** Blurhash placeholder from NIP-94 `blurhash` tag. */
blurhash?: string;
}
/** Parse all imeta tags into a map keyed by URL. Works for any event kind. */
export function parseImetaMap(tags: string[][]): Map<string, ImetaEntry> {
const map = new Map<string, ImetaEntry>();
for (const tag of tags) {
if (tag[0] !== 'imeta') continue;
const entry: Record<string, string> = {};
for (let i = 1; i < tag.length; i++) {
const part = tag[i];
const spaceIdx = part.indexOf(' ');
if (spaceIdx === -1) continue;
const key = part.slice(0, spaceIdx);
const value = part.slice(spaceIdx + 1);
entry[key] = value;
}
if (entry.url) {
map.set(entry.url, {
url: entry.url,
thumbnail: entry.image,
mime: entry.m,
summary: entry.summary,
webxdc: entry.webxdc,
dim: entry.dim,
blurhash: entry.blurhash,
});
}
}
return map;
}
@@ -0,0 +1,93 @@
/** Image extensions rendered inline. */
export const IMAGE_EXTS = 'jpg|jpeg|png|gif|webp|svg|avif';
/** Video extensions rendered as players. */
export const VIDEO_EXTS = 'mp4|webm|mov|qt|avi|mkv|flv';
/** Audio extensions rendered as players. */
export const AUDIO_EXTS = 'mp3|wav|ogg|flac|m4a|aac|opus';
/** All media extensions (image + video + audio + webxdc). */
export const ALL_MEDIA_EXTS = `${IMAGE_EXTS}|${VIDEO_EXTS}|${AUDIO_EXTS}|xdc`;
/** Matches image URLs. */
export const IMAGE_URL_REGEX = new RegExp(
`https?:\\/\\/[^\\s]+\\.(${IMAGE_EXTS})(\\?[^\\s]*)?`,
'i',
);
/** Matches video URLs. */
export const VIDEO_URL_REGEX = new RegExp(
`https?:\\/\\/[^\\s]+\\.(${VIDEO_EXTS})(\\?[^\\s]*)?`,
'gi',
);
/** Matches audio URLs. */
export const AUDIO_URL_REGEX = new RegExp(
`https?:\\/\\/[^\\s]+\\.(${AUDIO_EXTS})(\\?[^\\s]*)?`,
'gi',
);
/** Matches any media URL (video, audio, webxdc) that is rendered as an embed — not a link preview. */
export const EMBED_MEDIA_URL_REGEX = new RegExp(
`https?:\\/\\/[^\\s]+\\.(${VIDEO_EXTS}|${AUDIO_EXTS}|xdc)(\\?[^\\s]*)?`,
'i',
);
/** Matches all NIP-92 media URLs for imeta tag generation (images + video + audio + webxdc). */
export const IMETA_MEDIA_URL_REGEX = new RegExp(
`https?:\\/\\/[^\\s]+\\.(${ALL_MEDIA_EXTS})(\\?[^\\s]*)?`,
'gi',
);
/**
* Non-global variant of IMETA_MEDIA_URL_REGEX, safe for `.test()` calls.
*
* IMPORTANT: Never use the global (`g`) IMETA_MEDIA_URL_REGEX with `.test()` —
* the global flag makes `lastIndex` stateful, so repeated `.test()` calls
* (e.g. inside `.find()` or `.filter()`) will alternate between matching and
* not matching, causing every other URL to be misclassified.
*/
export const IMETA_MEDIA_URL_TEST_REGEX = new RegExp(
IMETA_MEDIA_URL_REGEX.source,
'i',
);
/** Infers a MIME type from a file extension string (lowercase). */
export function mimeFromExt(ext: string): string {
switch (ext) {
case 'jpg': case 'jpeg': return 'image/jpeg';
case 'png': return 'image/png';
case 'gif': return 'image/gif';
case 'webp': return 'image/webp';
case 'svg': return 'image/svg+xml';
case 'avif': return 'image/avif';
case 'mp4': return 'video/mp4';
case 'webm': return 'video/webm';
case 'mov': return 'video/quicktime';
case 'qt': return 'video/quicktime';
case 'avi': return 'video/x-msvideo';
case 'mkv': return 'video/x-matroska';
case 'flv': return 'video/x-flv';
case 'mp3': return 'audio/mpeg';
case 'wav': return 'audio/wav';
case 'ogg': return 'audio/ogg';
case 'flac': return 'audio/flac';
case 'm4a': return 'audio/mp4';
case 'aac': return 'audio/aac';
case 'opus': return 'audio/opus';
case 'xdc': return 'application/x-webxdc';
default: return 'application/octet-stream';
}
}
/** Extracts all video URLs from a string. */
export function extractVideoUrls(content: string): string[] {
return content.match(new RegExp(VIDEO_URL_REGEX.source, 'gi')) ?? [];
}
/** Extracts all audio URLs from a string. */
export function extractAudioUrls(content: string): string[] {
return content.match(new RegExp(AUDIO_URL_REGEX.source, 'gi')) ?? [];
}
@@ -0,0 +1,21 @@
/**
* Validate that a string is a well-formed HTTPS URL.
*
* Returns the normalised `href` when valid, or `undefined` otherwise.
* This **must** be used whenever a URL originates from untrusted Nostr
* event data (tags, metadata fields, etc.) and will be placed into an
* `href`, `window.open()`, or `openUrl()` call. Without this check a
* malicious `javascript:` URI could execute arbitrary code.
*/
export function sanitizeUrl(raw: string | undefined | null): string | undefined {
if (!raw) return undefined;
try {
const parsed = new URL(raw);
if (parsed.protocol === 'https:') {
return parsed.href;
}
} catch {
// not a valid URL
}
return undefined;
}
+256
View File
@@ -0,0 +1,256 @@
---
name: nwc
description: Add Nostr Wallet Connect (NWC), WebLN wallet detection, and Lightning zap functionality (NIP-57) to the application. Use when the user wants to connect a Lightning wallet, send zaps, or display zap counts on Nostr events.
---
# Nostr Wallet Connect (NWC) & Lightning Zaps
This skill adds Lightning wallet connectivity and zap (NIP-57) functionality. It is **not included in the project by default**. When the user wants to add wallet/zap features, follow the setup instructions below to install the files, wire up the provider, and add the required dependencies.
## What This Skill Provides
- **NWC** (Nostr Wallet Connect, NIP-47) — connect remote Lightning wallets via `nostr+walletconnect://` URIs
- **WebLN detection** — auto-detect browser extension wallets (Alby, Mutiny, etc.)
- **NIP-57 Zaps** — create zap requests, fetch LNURL invoices, pay them via NWC/WebLN/QR fallback
- **UI components** — `ZapButton`, `ZapDialog`, `WalletModal` ready to drop into the app
## Files Provided by This Skill
All files live under `.agents/skills/nwc/files/` and must be copied into `src/` preserving the directory structure:
| Skill file | Copy to |
|---|---|
| `files/hooks/useNWC.ts` | `src/hooks/useNWC.ts` |
| `files/hooks/useNWCContext.ts` | `src/hooks/useNWCContext.ts` |
| `files/hooks/useWallet.ts` | `src/hooks/useWallet.ts` |
| `files/hooks/useZaps.ts` | `src/hooks/useZaps.ts` |
| `files/lib/bolt11.ts` | `src/lib/bolt11.ts` |
| `files/lib/lnurlPay.ts` | `src/lib/lnurlPay.ts` |
| `files/contexts/NWCContext.tsx` | `src/contexts/NWCContext.tsx` |
| `files/components/WalletModal.tsx` | `src/components/WalletModal.tsx` |
| `files/components/ZapDialog.tsx` | `src/components/ZapDialog.tsx` |
| `files/components/ZapButton.tsx` | `src/components/ZapButton.tsx` |
## Setup Instructions
### 1. Install Dependencies
Add these packages to the project:
```bash
npm install @getalby/sdk @webbtc/webln-types
```
- `@getalby/sdk` — NWC client used by `useNWC.ts` to open connections and pay invoices
- `@webbtc/webln-types` — TypeScript types for the browser WebLN provider
`ZapDialog` also uses the `qrcode` package to render invoices. It should already be installed in the project (it's used by `src/components/ui/qrcode.tsx`). If it's missing for any reason, also run `npm install qrcode && npm install --save-dev @types/qrcode`.
### 2. Copy the Skill Files Into `src/`
Copy every file listed in the table above from `.agents/skills/nwc/files/` into its corresponding location under `src/`. Preserve the exact paths — the files use `@/hooks/...` / `@/contexts/...` / `@/components/...` imports that depend on these locations.
### 3. Wire Up the `NWCProvider` in `src/App.tsx`
The `NWCProvider` must wrap any component that uses NWC, wallet, or zap hooks/components. Place it inside `NostrProvider` (it depends on a logged-in user) and around `TooltipProvider`:
```tsx
// Add this import near the other provider imports at the top of src/App.tsx
import { NWCProvider } from '@/contexts/NWCContext';
// Then wrap TooltipProvider with NWCProvider inside the existing provider tree:
export function App() {
return (
<UnheadProvider head={head}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<NostrSync />
<NWCProvider>
<TooltipProvider>
<Toaster />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</NWCProvider>
</NostrProvider>
</NostrLoginProvider>
</QueryClientProvider>
</AppProvider>
</UnheadProvider>
);
}
```
### 4. Wire Up `NWCProvider` in `src/test/TestApp.tsx` (if tests need it)
If you're writing tests that mount components depending on NWC/zap/wallet hooks, wrap `TestApp`'s provider tree the same way:
```tsx
import { NWCProvider } from '@/contexts/NWCContext';
// ...
<NostrProvider>
<NWCProvider>
<BrowserRouter>
{children}
</BrowserRouter>
</NWCProvider>
</NostrProvider>
```
## Hooks
Once installed and wired up, the following hooks are available:
| Hook | Purpose |
|---|---|
| `useNWC` (from `@/hooks/useNWCContext`) | Manage NWC connections — `addConnection`, `removeConnection`, `setActiveConnection`, `getActiveConnection`, `sendPayment` |
| `useWallet` | Unified wallet status — returns `{ hasNWC, webln, activeNWC, preferredMethod }` |
| `useZaps` | Zap functionality — fetch zap receipts/totals, create invoices, pay via NWC/WebLN, fallback to QR |
### `useNWC`
```tsx
import { useNWC } from '@/hooks/useNWCContext';
function MyComponent() {
const {
connections, // NWCConnection[]
activeConnection, // string | null (connection string of active wallet)
addConnection, // (uri: string, alias?: string) => Promise<boolean>
removeConnection, // (connectionString: string) => void
setActiveConnection,// (connectionString: string) => void
getActiveConnection,// () => NWCConnection | null
sendPayment, // (connection, invoice, expectedAmountMsat) => Promise<{ preimage: string }>
} = useNWC();
}
```
Connections are persisted to `localStorage` under the keys `nwc-connections` and `nwc-active-connection`.
### `useWallet`
```tsx
import { useWallet } from '@/hooks/useWallet';
function ZapContext() {
const { hasNWC, webln, activeNWC, preferredMethod } = useWallet();
// preferredMethod: 'nwc' | 'webln' | 'manual'
}
```
`useWallet` combines NWC connection state with the browser's global `window.webln` to give a single source of truth for "can this user pay a Lightning invoice right now, and how?"
### `useZaps`
```tsx
import { useZaps } from '@/hooks/useZaps';
import { useWallet } from '@/hooks/useWallet';
import type { Event } from 'nostr-tools';
function MyZapTotal({ event }: { event: Event }) {
const { webln, activeNWC } = useWallet();
const { zapCount, totalSats, zap, isZapping, invoice } = useZaps(event, webln, activeNWC);
return <div>{totalSats} sats from {zapCount} zaps</div>;
}
```
The `zap(amount, comment)` function will:
1. Look up the author's LNURL endpoint from their profile's `lud16`/`lud06`
2. Create and sign a NIP-57 zap request
3. Fetch a Lightning invoice from the LNURL service
4. **Decode the invoice and reject it unless it charges exactly the requested amount**
5. Try to pay it via NWC (preferred), then WebLN, then expose the invoice for QR/manual payment
6. Show toast feedback and invalidate zap query caches on success
### Never pay an invoice you haven't read
Step 4 is not optional. The LNURL endpoint is chosen by the **recipient**, so the
invoice it returns is attacker-controlled whenever the recipient is hostile:
anyone who posts a note and runs their own pay server otherwise decides how much
their victims spend, *after* the victim has approved a figure. A user who
approves 776 sats can be charged 5,000,000, and — since the wallet is handed only
the invoice string — nothing downstream will notice.
`lib/bolt11.ts` provides `assertInvoiceAmount(invoice, expectedMsat)`, which
decodes the BOLT11 and throws unless the amount matches exactly. Amountless
invoices are rejected outright, since they let the wallet or payee pick the sum.
`useNWC.sendPayment` takes the approved amount and re-checks it, so no caller can
hand a wallet an unvetted invoice.
If you add another payment path, put the check in front of it. Do not use a
regex on the human-readable part for this — that is a display heuristic, not an
authentication check.
## Components
### `ZapButton`
Drop-in button that shows total sats for an event and opens a zap dialog when clicked. Hides itself automatically if the viewer isn't logged in, is the author, or the author has no Lightning address.
```tsx
import { ZapButton } from '@/components/ZapButton';
<ZapButton target={event} />
```
Pre-computed zap data can be passed in to avoid extra queries in feed views:
```tsx
<ZapButton target={event} zapData={{ count: 5, totalSats: 1234, isLoading: false }} />
```
### `ZapDialog`
The full zap flow UI (amount presets, custom amount, comment, invoice QR). Usually rendered indirectly via `ZapButton`, but can be used standalone for custom triggers:
```tsx
import { ZapDialog } from '@/components/ZapDialog';
<ZapDialog target={event}>
<button>Send a zap</button>
</ZapDialog>
```
### `WalletModal`
Settings UI for connecting/removing NWC wallets and viewing WebLN status. Good for a wallet settings page or a header icon:
```tsx
import { WalletModal } from '@/components/WalletModal';
// Default trigger button
<WalletModal />
// Or custom trigger
<WalletModal>
<Button variant="ghost"><Wallet /></Button>
</WalletModal>
```
## Payment Method Priority
When a user sends a zap, the skill tries payment methods in this order:
1. **NWC** — if there is an active connection in `useNWC`, `sendPayment` is called with the fetched invoice
2. **WebLN** — if `window.webln` exists, it's `enable()`d (if needed) and used to pay the invoice
3. **Manual/QR** — the invoice is exposed as a QR code and `lightning:` URI; the user pays from any wallet
Errors at each stage fall through to the next method, with a toast explaining what happened.
## Protocol Notes
- **NIP-47 (NWC)** — wallet connection strings start with `nostr+walletconnect://` (or legacy `nostrwalletconnect://`). The `@getalby/sdk` `LN` client handles the underlying encrypted request/response events with the wallet service pubkey over relays defined in the URI.
- **NIP-57 (Zaps)** — `nip57.makeZapRequest` builds the kind-9734 zap request. For addressable events (kinds 30000–39999) the skill passes the event object (so an `a` tag is included); for all other kinds it passes just the event id (so an `e` tag is included). The zap request is **signed but not published** — it's sent directly to the LNURL endpoint in the query string, which returns a BOLT11 invoice.
- **LNURL** — resolved from the author's `lud16` (email-style) or `lud06` (bech32) metadata field by `lib/lnurlPay.ts`. It does not use `nip57.getZapEndpoint`, which returns only the callback URL and discards the `minSendable`/`maxSendable` bounds and the `metadata` string needed to validate the response. HTTPS is required for both the LNURL and the callback it names.
- **Zap receipts** — kind 9735 events published by the LNURL service after payment. The skill queries them by `#e` (regular events) or `#a` (addressable events) and sums sats from the `amount` tag, BOLT11 invoice, or zap request description (in that order of preference).
## Tips
- **Loading the skill doesn't modify the project.** You must actually copy the files and edit `App.tsx` and `package.json` as described above. Without the provider, every hook will throw `"useNWC must be used within a NWCProvider"`.
- **Place `ZapButton` next to other engagement buttons** (reply, repost, like) on posts. It returns `null` for self-authored posts and authors without a Lightning address, so it's safe to render unconditionally.
- **Don't store connection strings anywhere else.** NWC connection strings contain a secret key. The skill keeps them in `localStorage` only; treat them like passwords.
- **The `WebLNProvider` type import is `import type { WebLNProvider } from '@webbtc/webln-types';`** — types-only, so it disappears at build time.
@@ -1,4 +1,4 @@
import { useState, forwardRef } from 'react';
import { useState } from 'react';
import { Wallet, Plus, Trash2, Zap, Globe, WalletMinimal, CheckCircle, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import {
@@ -29,6 +29,7 @@ import { useWallet } from '@/hooks/useWallet';
import { useToast } from '@/hooks/useToast';
import { useIsMobile } from '@/hooks/useIsMobile';
import type { NWCConnection, NWCInfo } from '@/hooks/useNWC';
import type { WebLNProvider } from "@webbtc/webln-types";
interface WalletModalProps {
children?: React.ReactNode;
@@ -36,12 +37,13 @@ interface WalletModalProps {
}
// Extracted AddWalletContent to prevent re-renders
const AddWalletContent = forwardRef<HTMLDivElement, {
const AddWalletContent = ({ alias, setAlias, connectionUri, setConnectionUri, ref }: {
alias: string;
setAlias: (value: string) => void;
connectionUri: string;
setConnectionUri: (value: string) => void;
}>(({ alias, setAlias, connectionUri, setConnectionUri }, ref) => (
ref?: React.Ref<HTMLDivElement>;
}) => (
<div className="space-y-4 px-4" ref={ref}>
<div>
<Label htmlFor="alias">Wallet Name (optional)</Label>
@@ -63,13 +65,21 @@ const AddWalletContent = forwardRef<HTMLDivElement, {
/>
</div>
</div>
));
AddWalletContent.displayName = 'AddWalletContent';
);
// Extracted WalletContent to prevent re-renders
const WalletContent = forwardRef<HTMLDivElement, {
hasWebLN: boolean;
isDetecting: boolean;
const WalletContent = ({
webln,
hasNWC,
connections,
connectionInfo,
activeConnection,
handleSetActive,
handleRemoveConnection,
setAddDialogOpen,
ref,
}: {
webln: WebLNProvider | null;
hasNWC: boolean;
connections: NWCConnection[];
connectionInfo: Record<string, NWCInfo>;
@@ -77,17 +87,8 @@ const WalletContent = forwardRef<HTMLDivElement, {
handleSetActive: (cs: string) => void;
handleRemoveConnection: (cs: string) => void;
setAddDialogOpen: (open: boolean) => void;
}>(({
hasWebLN,
isDetecting,
hasNWC,
connections,
connectionInfo,
activeConnection,
handleSetActive,
handleRemoveConnection,
setAddDialogOpen
}, ref) => (
ref?: React.Ref<HTMLDivElement>;
}) => (
<div className="space-y-6 px-4 pb-4" ref={ref}>
{/* Current Status */}
<div className="space-y-3">
@@ -103,9 +104,9 @@ const WalletContent = forwardRef<HTMLDivElement, {
</div>
</div>
<div className="flex items-center gap-2">
{hasWebLN && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={hasWebLN ? "default" : "secondary"} className="text-xs">
{isDetecting ? "..." : hasWebLN ? "Ready" : "Not Found"}
{webln && <CheckCircle className="h-4 w-4 text-green-600" />}
<Badge variant={webln ? "default" : "secondary"} className="text-xs">
{webln ? "Ready" : "Not Found"}
</Badge>
</div>
</div>
@@ -191,7 +192,7 @@ const WalletContent = forwardRef<HTMLDivElement, {
)}
</div>
{/* Help */}
{!hasWebLN && connections.length === 0 && (
{!webln && connections.length === 0 && (
<>
<Separator />
<div className="text-center py-4 space-y-2">
@@ -202,8 +203,7 @@ const WalletContent = forwardRef<HTMLDivElement, {
</>
)}
</div>
));
WalletContent.displayName = 'WalletContent';
);
export function WalletModal({ children, className }: WalletModalProps) {
const [open, setOpen] = useState(false);
@@ -222,7 +222,7 @@ export function WalletModal({ children, className }: WalletModalProps) {
setActiveConnection
} = useNWC();
const { hasWebLN, isDetecting } = useWallet();
const { webln } = useWallet();
const hasNWC = connections.length > 0 && connections.some(c => c.isConnected);
const { toast } = useToast();
@@ -263,8 +263,7 @@ export function WalletModal({ children, className }: WalletModalProps) {
};
const walletContentProps = {
hasWebLN,
isDetecting,
webln,
hasNWC,
connections,
connectionInfo,
@@ -1,4 +1,4 @@
import { useState, useEffect, useRef, forwardRef } from 'react';
import { useState, useEffect, useRef } from 'react';
import { Zap, Copy, Check, ExternalLink, Sparkle, Sparkles, Star, Rocket, ArrowLeft, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { cn } from '@/lib/utils';
@@ -33,6 +33,7 @@ import { useWallet } from '@/hooks/useWallet';
import { useIsMobile } from '@/hooks/useIsMobile';
import type { Event } from 'nostr-tools';
import QRCode from 'qrcode';
import type { WebLNProvider } from "@webbtc/webln-types";
interface ZapDialogProps {
target: Event;
@@ -55,25 +56,26 @@ interface ZapContentProps {
isZapping: boolean;
qrCodeUrl: string;
copied: boolean;
hasWebLN: boolean;
webln: WebLNProvider | null;
handleZap: () => void;
handleCopy: () => void;
openInWallet: () => void;
setAmount: (amount: number | string) => void;
setComment: (comment: string) => void;
inputRef: React.RefObject<HTMLInputElement>;
inputRef: React.RefObject<HTMLInputElement | null>;
zap: (amount: number, comment: string) => void;
ref?: React.Ref<HTMLDivElement>;
}
// Moved ZapContent outside of ZapDialog to prevent re-renders causing focus loss
const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
const ZapContent = ({
invoice,
amount,
comment,
isZapping,
qrCodeUrl,
copied,
hasWebLN,
webln,
handleZap,
handleCopy,
openInWallet,
@@ -81,7 +83,8 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
setComment,
inputRef,
zap,
}, ref) => (
ref,
}: ZapContentProps) => (
<div ref={ref}>
{invoice ? (
<div className="flex flex-col h-full min-h-0">
@@ -118,7 +121,7 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
id="invoice"
value={invoice}
readOnly
className="font-mono text-xs min-w-0 flex-1 overflow-hidden text-ellipsis"
className="font-mono text-base md:text-xs min-w-0 flex-1 overflow-hidden text-ellipsis"
onClick={(e) => e.currentTarget.select()}
/>
<Button
@@ -138,7 +141,7 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
{/* Payment buttons */}
<div className="space-y-3 mt-4">
{hasWebLN && (
{webln && (
<Button
onClick={() => {
const finalAmount = typeof amount === 'string' ? parseInt(amount, 10) : amount;
@@ -205,14 +208,14 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
placeholder="Custom amount"
value={amount}
onChange={(e) => setAmount(e.target.value)}
className="w-full text-sm"
className="w-full"
/>
<Textarea
id="custom-comment"
placeholder="Add a comment (optional)"
value={comment}
onChange={(e) => setComment(e.target.value)}
className="w-full resize-none text-sm"
className="w-full resize-none"
rows={2}
/>
</div>
@@ -231,16 +234,14 @@ const ZapContent = forwardRef<HTMLDivElement, ZapContentProps>(({
</>
)}
</div>
));
ZapContent.displayName = 'ZapContent';
);
export function ZapDialog({ target, children, className }: ZapDialogProps) {
const [open, setOpen] = useState(false);
const { user } = useCurrentUser();
const { data: author } = useAuthor(target.pubkey);
const { toast } = useToast();
const { webln, activeNWC, hasWebLN, detectWebLN } = useWallet();
const { webln, activeNWC } = useWallet();
const { zap, isZapping, invoice, setInvoice } = useZaps(target, webln, activeNWC, () => setOpen(false));
const [amount, setAmount] = useState<number | string>(100);
const [comment, setComment] = useState<string>('');
@@ -251,17 +252,11 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
useEffect(() => {
if (target) {
// eslint-disable-next-line react-hooks/set-state-in-effect
setComment('Zapped with MKStack!');
}
}, [target]);
// Detect WebLN when dialog opens
useEffect(() => {
if (open && !hasWebLN) {
detectWebLN();
}
}, [open, hasWebLN, detectWebLN]);
// Generate QR code
useEffect(() => {
let isCancelled = false;
@@ -319,6 +314,10 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
};
useEffect(() => {
// Reset dialog state when opened/closed. The canonical React pattern
// for this is a `key` prop on the caller, but the dialog's public API
// is a simple open/close boolean.
/* eslint-disable react-hooks/set-state-in-effect */
if (open) {
setAmount(100);
setInvoice(null);
@@ -331,6 +330,7 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
setCopied(false);
setQrCodeUrl('');
}
/* eslint-enable react-hooks/set-state-in-effect */
}, [open, setInvoice]);
const handleZap = () => {
@@ -345,7 +345,7 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
isZapping,
qrCodeUrl,
copied,
hasWebLN,
webln,
handleZap,
handleCopy,
openInWallet,
@@ -420,10 +420,10 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
</Button>
</DrawerClose>
<DrawerTitle className="text-lg break-words pt-2">
<DrawerTitle className="text-lg wrap-break-word pt-2">
{invoice ? 'Lightning Payment' : 'Send a Zap'}
</DrawerTitle>
<DrawerDescription className="text-sm break-words text-center">
<DrawerDescription className="text-sm wrap-break-word text-center">
{invoice ? (
'Pay with Bitcoin Lightning Network'
) : (
@@ -448,10 +448,10 @@ export function ZapDialog({ target, children, className }: ZapDialogProps) {
</DialogTrigger>
<DialogContent className="sm:max-w-[425px] max-h-[95vh] overflow-hidden" data-testid="zap-modal">
<DialogHeader>
<DialogTitle className="text-lg break-words">
<DialogTitle className="text-lg wrap-break-word">
{invoice ? 'Lightning Payment' : 'Send a Zap'}
</DialogTitle>
<DialogDescription className="text-sm text-center break-words">
<DialogDescription className="text-sm text-center wrap-break-word">
{invoice ? (
'Pay with Bitcoin Lightning Network'
) : (
File renamed without changes.
@@ -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,18 +160,27 @@ 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);
} catch (error) {
console.error('Failed to create NWC client:', error);
throw new Error(`Failed to create NWC client: ${error instanceof Error ? error.message : 'Unknown error'}`);
throw new Error(`Failed to create NWC client: ${error instanceof Error ? error.message : 'Unknown error'}`, { cause: error });
}
try {
@@ -194,17 +204,17 @@ export function useNWCInternal() {
if (error instanceof Error) {
if (error.message.includes('timeout')) {
throw new Error('Payment timed out. Please try again.');
throw new Error('Payment timed out. Please try again.', { cause: error });
} else if (error.message.includes('insufficient')) {
throw new Error('Insufficient balance in connected wallet.');
throw new Error('Insufficient balance in connected wallet.', { cause: error });
} else if (error.message.includes('invalid')) {
throw new Error('Invalid invoice or connection. Please check your wallet.');
throw new Error('Invalid invoice or connection. Please check your wallet.', { cause: error });
} else {
throw new Error(`Payment failed: ${error.message}`);
throw new Error(`Payment failed: ${error.message}`, { cause: error });
}
}
throw new Error('Payment failed with unknown error');
throw new Error('Payment failed with unknown error', { cause: error });
}
}, []);
File renamed without changes.
@@ -0,0 +1,41 @@
import { useMemo } from 'react';
import { useNWC } from '@/hooks/useNWCContext';
import type { WebLNProvider } from '@webbtc/webln-types';
export interface WalletStatus {
hasNWC: boolean;
webln: WebLNProvider | null;
activeNWC: ReturnType<typeof useNWC>['getActiveConnection'] extends () => infer T ? T : null;
preferredMethod: 'nwc' | 'webln' | 'manual';
}
export function useWallet() {
const { connections, getActiveConnection } = useNWC();
// Get the active connection directly - no memoization to avoid stale state
const activeNWC = getActiveConnection();
// Access WebLN directly from browser global scope
const webln = (globalThis as { webln?: WebLNProvider }).webln || null;
// Calculate status values reactively
const hasNWC = useMemo(() => {
return connections.length > 0 && connections.some(c => c.isConnected);
}, [connections]);
// Determine preferred payment method
const preferredMethod: WalletStatus['preferredMethod'] = activeNWC
? 'nwc'
: webln
? 'webln'
: 'manual';
const status: WalletStatus = {
hasNWC,
webln,
activeNWC,
preferredMethod,
};
return status;
}
@@ -7,10 +7,12 @@ import { useNWC } from '@/hooks/useNWCContext';
import type { NWCConnection } from '@/hooks/useNWC';
import { nip57 } from 'nostr-tools';
import type { Event } from 'nostr-tools';
import type { WebLNProvider } from 'webln';
import type { WebLNProvider } from '@webbtc/webln-types';
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[],
@@ -41,16 +43,16 @@ export function useZaps(
}, []);
const { data: zapEvents, ...query } = useQuery<NostrEvent[], Error>({
queryKey: ['zaps', actualTarget?.id],
queryKey: ['nostr', 'zaps', actualTarget?.id],
staleTime: 30000, // 30 seconds
refetchInterval: (query) => {
// Only refetch if the query is currently being observed (component is mounted)
return query.getObserversCount() > 0 ? 60000 : false;
},
queryFn: async (c) => {
queryFn: async () => {
if (!actualTarget) return [];
const signal = AbortSignal.any([c.signal, AbortSignal.timeout(5000)]);
const signal = AbortSignal.timeout(5000);
// Query for zap receipts for this specific event
if (actualTarget.kind >= 30000 && actualTarget.kind < 40000) {
@@ -180,12 +182,29 @@ 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. `nip57.getZapEndpoint`
// returns only the callback URL and discards the `minSendable` /
// `maxSendable` bounds and the `metadata` string needed to check that
// the invoice we get back is the one we asked for.
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);
return;
}
if (!lnurlParams.allowsNostr || !lnurlParams.nostrPubkey) {
toast({
title: 'Zaps not supported',
description: "This author's lightning address does not support zaps.",
variant: 'destructive',
});
setIsZapping(false);
@@ -201,11 +220,25 @@ 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 zapRequest = nip57.makeZapRequest({
profile: actualTarget.pubkey,
event: event,
amount: zapAmount,
relays: [config.relayUrl],
relays: config.relayMetadata.relays.map(r => r.url),
comment
});
@@ -214,9 +247,17 @@ 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))}`);
// Build the query with URLSearchParams: `encodeURI` leaves `&`, `+`
// and `#` alone, so a comment containing any of them corrupted the
// request.
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) {
@@ -228,13 +269,28 @@ 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,
// and nothing downstream ever reads the invoice. 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.');
}
// 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);
@@ -246,7 +302,7 @@ export function useZaps(
});
// Invalidate zap queries to refresh counts
queryClient.invalidateQueries({ queryKey: ['zaps'] });
queryClient.invalidateQueries({ queryKey: ['nostr', 'zaps'] });
// Close dialog last to ensure clean state
onZapSuccess?.();
@@ -263,10 +319,22 @@ export function useZaps(
});
}
}
if (webln) { // Try WebLN next
try {
await webln.sendPayment(newInvoice);
// For native WebLN, we may need to enable it first
let webLnProvider = webln;
if (webln.enable && typeof webln.enable === 'function') {
const enabledProvider = await webln.enable();
// Some implementations return the provider, others return void
// Cast to WebLNProvider to handle both cases
const provider = enabledProvider as WebLNProvider | undefined;
if (provider) {
webLnProvider = provider;
}
}
await webLnProvider.sendPayment(newInvoice);
// Clear states immediately on success
setIsZapping(false);
@@ -278,12 +346,12 @@ export function useZaps(
});
// Invalidate zap queries to refresh counts
queryClient.invalidateQueries({ queryKey: ['zaps'] });
queryClient.invalidateQueries({ queryKey: ['nostr', 'zaps'] });
// Close dialog last to ensure clean state
onZapSuccess?.();
} catch (weblnError) {
console.error('webln payment failed, falling back:', weblnError);
console.error('WebLN payment failed, falling back:', weblnError);
// Show specific WebLN error to user for debugging
const errorMessage = weblnError instanceof Error ? weblnError.message : 'Unknown WebLN error';
+257
View File
@@ -0,0 +1,257 @@
/**
* 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. The regex in `LightningInvoiceCard` 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 } 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;
const encoder = new TextEncoder();
return candidates.some(
(candidate) => bytesToHex(sha256(encoder.encode(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,
};
}
+426
View File
@@ -0,0 +1,426 @@
---
name: onchain-bitcoin
description: Add an onchain Bitcoin wallet derived from the user's Nostr identity. Every Nostr keypair maps deterministically to a Taproot (P2TR) address via shared secp256k1 + BIP-340 cryptography, so the same nsec receives, signs PSBTs, and broadcasts transactions through mempool.space — with no LNURL, custodian, or HD derivation. Includes balance/tx queries, send pipeline (build → sign → broadcast), capability detection across nsec / NIP-07 / NIP-46 signers, and kind 8333 onchain zaps with on-chain verification.
---
# Onchain Bitcoin Wallet
Nostr public keys (`npub` / 32-byte hex) are byte-for-byte identical to Bitcoin Taproot internal keys (BIP-340 / BIP-341): both are 32-byte x-only secp256k1 keys. This means **every Nostr identity already owns a Bitcoin address** — no key conversion, no HD derivation, no LNURL provider needed.
This skill ships a complete in-app wallet:
- Derive the user's `bc1p…` Taproot address from their pubkey
- Display balance, USD value, and transaction history
- Send Bitcoin via a PSBT pipeline that works with **all three** Nostrify signer types
- Publish and verify NIP-73 / kind 8333 "onchain zaps"
- Render NIP-73 `bitcoin:tx:` and `bitcoin:address:` identifiers in the existing `/:nip19` router
## Why It Works
| Property | Nostr | Bitcoin Taproot |
|---|---|---|
| Curve | secp256k1 | secp256k1 |
| Signature scheme | Schnorr (BIP-340) | Schnorr (BIP-340) |
| Public key format | 32-byte x-only | 32-byte x-only |
Because the formats match, a Nostr pubkey **is** a Taproot internal key (`P`). The on-chain output key is the standard BIP-341 tweak `Q = P + taggedHash("TapTweak", P) · G` with no script tree (key-path-only spend), encoded as bech32m with HRP `bc` and witness version 1 — always producing a `bc1p…` address.
`bitcoinjs-lib`'s `payments.p2tr({ internalPubkey })` performs the tweak + bech32m encoding internally.
## Files Provided by This Skill
| Skill file | Copy to |
|---|---|
| `files/lib/bitcoin.ts` | `src/lib/bitcoin.ts` |
| `files/lib/bitcoin-signers.ts` | `src/lib/bitcoin-signers.ts` |
| `files/hooks/useBitcoinWallet.ts` | `src/hooks/useBitcoinWallet.ts` |
| `files/hooks/useBitcoinAddress.ts` | `src/hooks/useBitcoinAddress.ts` |
| `files/hooks/useBitcoinTx.ts` | `src/hooks/useBitcoinTx.ts` |
| `files/hooks/useBitcoinSigner.ts` | `src/hooks/useBitcoinSigner.ts` |
| `files/hooks/useOnchainZap.ts` | `src/hooks/useOnchainZap.ts` |
| `files/hooks/useOnchainZaps.ts` | `src/hooks/useOnchainZaps.ts` |
These files are framework-only. The wallet page, send dialog, and on-chain zap UI are built on top of them.
## Setup Instructions
### 1. Install Dependencies
```bash
npm install bitcoinjs-lib @bitcoinerlab/secp256k1 ecpair tiny-secp256k1
```
`buffer` is already a dependency of the template; if you removed it, also `npm install buffer`.
| Package | Role |
|---|---|
| `bitcoinjs-lib` | P2TR address derivation, PSBT construction & finalization |
| `@bitcoinerlab/secp256k1` | secp256k1 ECC backend (Schnorr, key tweaking) |
| `ecpair` | Key pair creation and BIP-341 tweaking for local nsec signing |
| `tiny-secp256k1` | Peer dep of `ecpair` (low-level ECC) |
### 2. Initialize ECC in `main.tsx`
The Buffer polyfill is already imported in mkstack's `main.tsx`. Add the ECC initialization right after it. **`bitcoin.initEccLib(ecc)` must run before any wallet code** — otherwise `payments.p2tr()` and Schnorr operations throw.
```tsx
// src/main.tsx
import { createRoot } from 'react-dom/client';
// Import polyfills first (Buffer must exist before bitcoinjs-lib is loaded)
import './lib/polyfills.ts';
// Initialize ECC for bitcoinjs-lib (Taproot / Schnorr support)
import * as bitcoin from 'bitcoinjs-lib';
import * as ecc from '@bitcoinerlab/secp256k1';
bitcoin.initEccLib(ecc);
import { ErrorBoundary } from '@/components/ErrorBoundary';
import App from './App.tsx';
import './index.css';
createRoot(document.getElementById('root')!).render(
<ErrorBoundary>
<App />
</ErrorBoundary>
);
```
`src/lib/bitcoin.ts` calls `initEccLib` again lazily inside signing/finalizing functions as a defensive measure, so test files and ad-hoc imports also work — but the early init in `main.tsx` is what the live app relies on.
### 3. Copy the Skill Files
Copy every file from `files/` into the matching directory under `src/`. The hook files import each other and `@/lib/bitcoin` / `@/lib/bitcoin-signers`, so paths must match exactly.
### 4. Wire the BTC-Capable Signers into `useCurrentUser`
The default `useCurrentUser` uses Nostrify's `NUser.from*Login` factories, which return signers without a `signPsbt` method. Replace them with the BTC-extended subclasses from this skill so the same `user.signer` instance can also sign PSBTs.
Edit `src/hooks/useCurrentUser.ts`:
```tsx
import { useNostr } from '@nostrify/react';
import { type NLoginType, NUser, useNostrLogin } from '@nostrify/react/login';
import { NSecSigner } from '@nostrify/nostrify';
import { nip19 } from 'nostr-tools';
import { useCallback, useMemo } from 'react';
import { useAuthor } from './useAuthor.ts';
import { NSecSignerBtc, NBrowserSignerBtc, NConnectSignerBtc } from '@/lib/bitcoin-signers';
export function useCurrentUser() {
const { nostr } = useNostr();
const { logins } = useNostrLogin();
const loginToUser = useCallback((login: NLoginType): NUser => {
switch (login.type) {
case 'nsec': {
const sk = nip19.decode(login.data.nsec) as { type: 'nsec'; data: Uint8Array };
return new NUser(login.type, login.pubkey, new NSecSignerBtc(sk.data));
}
case 'bunker': {
const clientSk = nip19.decode(login.data.clientNsec) as { type: 'nsec'; data: Uint8Array };
const clientSigner = new NSecSigner(clientSk.data);
return new NUser(
login.type,
login.pubkey,
new NConnectSignerBtc({
relay: nostr.group(login.data.relays),
pubkey: login.data.bunkerPubkey,
signer: clientSigner,
timeout: 60_000,
}),
);
}
case 'extension':
return new NUser(login.type, login.pubkey, new NBrowserSignerBtc({ pubkey: login.pubkey }));
default:
throw new Error(`Unsupported login type: ${login.type}`);
}
}, [nostr]);
const users = useMemo(() => {
const users: NUser[] = [];
for (const login of logins) {
try { users.push(loginToUser(login)); }
catch (error) { console.warn('Skipped invalid login', login.id, error); }
}
return users;
}, [logins, loginToUser]);
const user = users[0] as NUser | undefined;
const author = useAuthor(user?.pubkey);
return { user, users, ...author.data };
}
```
This is the **only** change required for the wallet to function across all three login types. If you skip it, the hooks still compile but `useBitcoinSigner` will report `'unsupported'` for every user.
## Core APIs
### Address derivation
```ts
import { nostrPubkeyToBitcoinAddress, npubToBitcoinAddress } from '@/lib/bitcoin';
nostrPubkeyToBitcoinAddress('d6889cb0…300a961d'); // 'bc1p2wsldez…'
npubToBitcoinAddress('npub1…'); // 'bc1p…'
```
Both return `''` for malformed input or off-curve pubkeys (so UIs can render an empty state without try/catch).
### `useBitcoinWallet()` — current user's wallet
```tsx
import { useBitcoinWallet } from '@/hooks/useBitcoinWallet';
import { satsToUSD, formatBTC } from '@/lib/bitcoin';
function WalletWidget() {
const { bitcoinAddress, addressData, btcPrice, transactions, isLoading } = useBitcoinWallet();
if (isLoading) return <Skeleton className="h-10 w-40" />;
if (!addressData) return null;
return (
<div>
<div>{btcPrice ? satsToUSD(addressData.totalBalance, btcPrice) : '—'}</div>
<div>{formatBTC(addressData.totalBalance)} BTC</div>
<code>{bitcoinAddress}</code>
</div>
);
}
```
Auto-refreshes every 30 s (balance + transactions) and 60 s (BTC price).
### `useBitcoinAddress(address)` / `useBitcoinTx(txid)` — NIP-73 detail pages
Use these from the `/:nip19` router (`src/pages/NIP19Page.tsx`) when an `i` tag is `bitcoin:address:bc1p…` or `bitcoin:tx:abc123…`. Both also return the BTC price for USD display.
Parse NIP-73 Bitcoin identifiers with this regex:
```ts
const txMatch = uri.match(/^bitcoin:tx:([0-9a-f]{64})$/i);
const addrMatch = uri.match(/^bitcoin:address:(.+)$/);
```
### Sending Bitcoin: the PSBT pipeline
The send flow is intentionally split into three pure functions so any signer (local key, NIP-07, NIP-46) can plug in at step 2:
```ts
import {
buildUnsignedPsbt,
finalizePsbt,
broadcastTransaction,
fetchUTXOs,
getFeeRates,
} from '@/lib/bitcoin';
import { useBitcoinSigner } from '@/hooks/useBitcoinSigner';
import { useCurrentUser } from '@/hooks/useCurrentUser';
const { user } = useCurrentUser();
const { signPsbt, canSignPsbt } = useBitcoinSigner();
if (!canSignPsbt || !signPsbt || !user) throw new Error("Login can't sign PSBTs.");
const senderAddress = nostrPubkeyToBitcoinAddress(user.pubkey);
const [utxos, rates] = await Promise.all([fetchUTXOs(senderAddress), getFeeRates()]);
// 1. Build (no key material required — pubkey only)
const { psbtHex, fee } = buildUnsignedPsbt(
user.pubkey,
recipientAddress,
amountSats,
utxos,
rates.halfHourFee, // sat/vB
);
// 2. Sign — dispatched through the user's signer
const signedHex = await signPsbt(psbtHex);
// 3. Finalize + broadcast
const txHex = finalizePsbt(signedHex);
const txid = await broadcastTransaction(txHex);
```
Key facts about `buildUnsignedPsbt`:
- All available UTXOs are consumed as inputs (no coin selection — keep it predictable).
- Fee uses `ceil((numInputs · 57.5 + numOutputs · 43 + 10.5) · feeRate)`.
- Change is added back to the sender's own Taproot address **only** if it's ≥ 546 sats (dust limit). Below dust, change is donated to fees and the tx has 1 output instead of 2.
- Throws `Insufficient funds` if `amount + fee > total UTXO value`.
- Throws `Invalid fee rate` if `feeRate` is not a finite number ≥ 1.
That last guard is load-bearing. A `NaN` fee rate produces a `NaN` fee, and
every check downstream of the fee — the dust comparison, the balance check, the
"is there a fee to show" check in the UI — is a `<` or `>=` comparison, and
*every* comparison with NaN is false. So NaN doesn't fail: it silently skips the
change output, passes the balance check, renders as "Fee 0", and builds a
perfectly valid transaction that pays the wallet's entire balance to miners.
`getFeeRates` sanitizes the remote response for the same reason — the old
`Math.ceil(data['1'] || 1)` caught a *missing* key but turned a truthy
non-number like `{"1": "5"}` into NaN.
For send-max, use `maxSendable(totalBalance, numInputs, feeRate)` — it correctly subtracts a 1-output fee.
### Signer capability detection
`useBitcoinSigner()` returns one of three states for the active login:
| Login | Capability |
|---|---|
| **nsec** | Always `'supported'` — local signing with the private key. |
| **NIP-07 extension** | Probes `window.nostr.signPsbt` (re-tries every 250 ms for up to 3 s). `'supported'`, `'unsupported'`, or `'unknown'` while the extension is still injecting. |
| **NIP-46 bunker** | `'unknown'` initially (NIP-46 has no capability-discovery RPC). Flips to `'unsupported'` for the rest of the session once a `sign_psbt` call returns a "method not found"-style error — see `reportSignerUnsupported()` and `isSignerCapabilityError()`. |
The send dialog should render an "unsupported" panel (with QR-code fallback for receiving funds) whenever `capability === 'unsupported'`, and let `'unknown'` users attempt the send. `useOnchainZap`'s `onError` handler already calls `reportSignerUnsupported(user.pubkey)` automatically, so the second send attempt with the same bunker won't re-attempt.
## Onchain Zaps (kind 8333)
A Bitcoin equivalent of NIP-57 Lightning zaps. Defined in this skill — the kind number mirrors the convention `9735 = Lightning P2P port`, `8333 = Bitcoin mainnet P2P port`.
> If the project has a `NIP.md` file, **document this kind there**. If it doesn't exist, create one with the kind 8333 schema below.
### Event Structure
```json
{
"kind": 8333,
"pubkey": "<sender-pubkey>",
"content": "Great post!",
"tags": [
["i", "bitcoin:tx:<txid>"],
["p", "<recipient-pubkey>"],
["amount", "<sats>"],
["e", "<target-event-id>"],
["alt", "Bitcoin zap: 25000 sats"]
]
}
```
| Tag | Required | Notes |
|---|---|---|
| `i` | Yes | NIP-73 identifier `bitcoin:tx:<txid>` (64-char lowercase hex). |
| `p` | Yes | Recipient pubkey. |
| `amount` | Yes | Sats paid to the recipient (may be capped by verifier). |
| `e` | If zapping an event | Event being zapped. |
| `a` | If zapping an addressable event (kind 30000–39999) | `<kind>:<pubkey>:<d-tag>`. |
| `alt` | Yes | NIP-31 fallback. |
If neither `e` nor `a` is present, the zap targets the recipient's profile.
### Publishing — `useOnchainZap(target)`
Builds + signs + broadcasts the Bitcoin transaction, then publishes the kind 8333 event:
```tsx
import { useOnchainZap } from '@/hooks/useOnchainZap';
function ZapButton({ target }: { target: NostrEvent }) {
const { zap, isZapping, progress, canZap } = useOnchainZap(target);
if (!canZap) return null; // not logged in, self-zap, or PSBT-incapable signer
return (
<button
disabled={isZapping}
onClick={() => zap({ amountSats: 5000, comment: 'Great post!', feeSpeed: 'halfHour' })}
>
{isZapping ? `${progress}…` : 'Zap 5k sats'}
</button>
);
}
```
`progress` cycles through `'building' → 'signing' → 'broadcasting' → 'publishing' → 'idle'`.
### Verification — never trust the `amount` tag
The `amount` tag is self-reported. **Always verify on-chain before counting it toward zap totals.** The skill's verifier:
1. Extracts the txid from the `i` tag.
2. Fetches the transaction from mempool.space.
3. Derives the recipient's expected Taproot address from the `p` pubkey.
4. Sums tx outputs paying that address. **Change outputs to the sender are excluded automatically** — they go to a different address.
5. Caps the displayed amount at the verified amount.
6. Rejects events where verified amount = 0, where sender = recipient (self-zap), or where the txid is malformed.
Use `useOnchainZaps(target)` for a list of verified zaps targeting an event, or `useVerifiedOnchainZap(event)` for a single event:
```tsx
import { useOnchainZaps } from '@/hooks/useOnchainZaps';
function OnchainZapList({ target }: { target: NostrEvent }) {
const { zaps, totalSats, isLoading } = useOnchainZaps(target);
if (isLoading) return <Skeleton className="h-6 w-24" />;
return <div>{totalSats.toLocaleString()} sats from {zaps.length} zappers</div>;
}
```
`useOnchainZaps` queries `{ kinds: [8333], '#e': [target.id] }` (and `#a` for addressables), dedupes by txid (preferring the earliest event for any given tx), and verifies each one via mempool.space. Cached for 60 s per (txid, recipient).
### Combining with NIP-57 totals
When showing total zaps for a post, sum verified amounts from **both** kind 9735 (Lightning) and kind 8333 (onchain) — they're complementary settlement layers, not alternatives.
## Mempool.space API Cheat Sheet
All endpoints are public and unauthenticated:
| Endpoint | Used by |
|---|---|
| `GET /address/{addr}` | `fetchAddressData` — balance + tx counts |
| `GET /address/{addr}/txs` | `fetchTransactions` — recent tx history |
| `GET /address/{addr}/utxo` | `fetchUTXOs` — for building send PSBTs |
| `GET /tx/{txid}` | `fetchTxDetail` + zap verifier — full inputs/outputs |
| `GET /fee-estimates` | `getFeeRates` — sat/vB per block target |
| `POST /tx` | `broadcastTransaction` — body is raw tx hex, returns txid |
You can swap to a self-hosted Esplora instance by changing the `MEMPOOL_API` constant in `src/lib/bitcoin.ts`.
## Security Considerations
> **The same private key controls both the user's Nostr identity and the Bitcoin funds at the derived address.** This is by design, but increases the blast radius of every common Nostr-client risk.
- **localStorage nsec is now spendable Bitcoin.** The `nostr-security` skill's XSS warnings apply doubly here. Treat `dangerouslySetInnerHTML`, unsanitized URLs, and CSS injection as on-par with stealing money. Load the `nostr-security` skill before merging anything that touches user input.
- **Extensions and bunkers never see the raw key.** Only the unsigned PSBT (no secret material) is passed to the signer. The PSBT format (BIP-174) carries `witnessUtxo` values and outputs, so a properly-implemented signer can show users what they're signing before approving.
- **Mainnet only.** This skill ships mainnet derivation and uses the public mempool.space API. Testnet/signet support would require a different `network`, a different Esplora endpoint, and is out of scope for kind 8333 verification.
- **Single-key, no HD.** Every Nostr keypair maps to exactly one Bitcoin address. There's no BIP-32 path. This is fine for a wallet tied to identity, but means the user has no way to rotate the address without losing their identity.
- **Users need a backup of their nsec before receiving funds.** Surfacing this to the user (e.g. on the wallet page) is the implementing app's responsibility.
- **Self-zap rejection.** `verifyOnchainZap` already drops events where `event.pubkey === recipient pubkey`. Don't relax this check — self-zaps are trivial to fabricate.
## Testing the Wallet
For end-to-end manual testing without spending real BTC:
1. Generate two Nostr keys (`nak generate` or any client).
2. Send a small amount of mainnet BTC (e.g. 5,000 sats) to key A's derived address.
3. Log in as key A, open the wallet page, confirm balance appears within ~30 s.
4. Use the send flow to forward sats to key B's derived address.
5. Verify the transaction shows up in B's wallet and the kind 8333 event (if zapping a post) is queryable from a relay.
Mempool.space confirms unconfirmed transactions within ~10 s of broadcast and provides a `/tx/<txid>` web view for verification.
## Building UI On Top
This skill provides only the framework. To build the user-facing surfaces:
- **Wallet page** (`/wallet`) — balance + QR code (`bitcoin:<address>`) + tx list. Use `useBitcoinWallet`. Render the QR with the `qrcode` package (`npm install qrcode`).
- **Send dialog** — recipient input (accepts both raw `bc1…` addresses and `npub1…`), amount input with USD conversion, fee-speed selector, confirm/success steps. Use `useBitcoinSigner` to gate the form, `validateBitcoinAddress` for validation, `npubToBitcoinAddress` for npub recipients, and the PSBT pipeline shown above.
- **NIP-73 detail pages** — extend `NIP19Page.tsx` to dispatch `bitcoin:tx:` and `bitcoin:address:` identifiers to detail components powered by `useBitcoinTx` / `useBitcoinAddress`.
- **Onchain zap button** — drop `useOnchainZap` into the existing zap dialog as a Bitcoin tab, alongside Lightning. Show the QR-code BIP-21 fallback (`bitcoin:<address>?amount=<btc>`) when capability is `'unsupported'`.
## References
- [BIP-340: Schnorr Signatures for secp256k1](https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki) — shared with NIP-01 keys
- [BIP-341: Taproot](https://github.com/bitcoin/bips/blob/master/bip-0341.mediawiki) — defines the TapTweak and key-path spend
- [BIP-350: Bech32m](https://github.com/bitcoin/bips/blob/master/bip-0350.mediawiki) — `bc1p…` encoding
- [BIP-174: PSBT format](https://github.com/bitcoin/bips/blob/master/bip-0174.mediawiki) — what `signPsbt` operates on
- [NIP-01](https://github.com/nostr-protocol/nips/blob/master/01.md) — defines secp256k1 x-only keys for Nostr
- [NIP-07](https://github.com/nostr-protocol/nips/blob/master/07.md) — `window.nostr` extension API; `signPsbt` is the optional Bitcoin extension
- [NIP-46](https://github.com/nostr-protocol/nips/blob/master/46.md) — remote signers; `sign_psbt` is the optional Bitcoin command
- [NIP-57](https://github.com/nostr-protocol/nips/blob/master/57.md) — Lightning zaps (the kind 8333 design mirrors this)
- [NIP-73](https://github.com/nostr-protocol/nips/blob/master/73.md) — external content identifiers (`bitcoin:tx:` / `bitcoin:address:`)
- [mempool.space API docs](https://mempool.space/docs/api/rest)
@@ -0,0 +1,25 @@
import { useQuery } from '@tanstack/react-query';
import { fetchAddressDetail, fetchBtcPrice } from '@/lib/bitcoin';
/**
* Fetch full address details (balance + recent txs) via the mempool.space API.
* Also fetches the current BTC/USD price for display.
*/
export function useBitcoinAddress(address: string) {
const { data: addressDetail, isLoading, error, refetch } = useQuery({
queryKey: ['bitcoin-address-detail', address],
queryFn: () => fetchAddressDetail(address),
enabled: !!address,
refetchInterval: 30_000,
});
const { data: btcPrice } = useQuery({
queryKey: ['btc-price'],
queryFn: fetchBtcPrice,
refetchInterval: 60_000,
staleTime: 30_000,
});
return { addressDetail, btcPrice, isLoading, error, refetch };
}
@@ -0,0 +1,201 @@
import { useEffect, useMemo, useState } from 'react';
import { useNostrLogin } from '@nostrify/react/login';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { type BtcSigner, hasBtcSigning } from '@/lib/bitcoin-signers';
/**
* Three possible states for Bitcoin PSBT signing capability:
*
* - `supported` — Known to work (nsec login, or extension that exposes `signPsbt`).
* - `unsupported` — Known not to work (extension without `signPsbt`, or a remote
* signer that has already rejected a `sign_psbt` request).
* - `unknown` — Cannot be determined in advance. Applies to NIP-46 bunker
* logins, since NIP-46 has no standard capability-discovery
* RPC. Treat as "attempt, then propagate the error if it
* fails" — the UI should allow the attempt but fall back to
* the unsupported state when a `sign_psbt` call rejects with
* a capability error (see `reportSignerUnsupported`).
*/
export type BitcoinSignerCapability = 'supported' | 'unsupported' | 'unknown';
/**
* Module-level registry of bunker pubkeys that have been observed to reject
* `sign_psbt`. Persists for the lifetime of the page so that the user doesn't
* see the "attempt then fail" path twice for the same bunker.
*/
const knownUnsupportedBunkers = new Set<string>();
/**
* Mark a bunker (keyed by user pubkey) as known-unsupported for PSBT signing.
* Subsequent renders of `useBitcoinSigner` will return `'unsupported'` for
* that user.
*/
export function reportSignerUnsupported(pubkey: string): void {
knownUnsupportedBunkers.add(pubkey);
// Dispatch a DOM event so hook consumers can re-render without plumbing a
// shared store through the app. Listened to by `useBitcoinSigner`.
window.dispatchEvent(new CustomEvent('bitcoin-signer-unsupported', { detail: pubkey }));
}
/**
* Clear the unsupported-bunker memo for a pubkey (or all pubkeys). Called
* when the user logs out or switches accounts, so that a re-login with a
* potentially-upgraded bunker doesn't inherit the previous rejection.
*/
export function clearSignerUnsupported(pubkey?: string): void {
if (pubkey === undefined) {
knownUnsupportedBunkers.clear();
} else {
knownUnsupportedBunkers.delete(pubkey);
}
window.dispatchEvent(new CustomEvent('bitcoin-signer-cleared', { detail: pubkey ?? '*' }));
}
/**
* Hook that exposes Bitcoin PSBT signing capability for the current login.
*
* Capability is probed eagerly for known login types so that the UI can
* replace itself with an "unsupported" state before the user attempts to
* sign anything (rather than surfacing a toast after the fact).
*
* - **nsec** → always `'supported'` (local signing).
* - **extension** → probes `window.nostr.signPsbt`. Returns `'supported'` if
* present, `'unsupported'` if absent, or `'unknown'` while
* still waiting for the extension to inject `window.nostr`.
* - **bunker** → `'unknown'` by default (NIP-46 has no capability RPC).
* Flips to `'unsupported'` for the session once a
* `sign_psbt` attempt has rejected with a capability error
* (see `reportSignerUnsupported`).
*/
export function useBitcoinSigner() {
const { user } = useCurrentUser();
const { logins } = useNostrLogin();
const loginType = logins[0]?.type;
// ── Extension: probe window.nostr.signPsbt ───────────────────
const [extensionProbe, setExtensionProbe] = useState<BitcoinSignerCapability>(() => {
if (loginType !== 'extension') return 'unknown';
const n = (globalThis as { nostr?: Record<string, unknown> }).nostr;
if (n && typeof n.signPsbt === 'function') return 'supported';
if (n) return 'unsupported';
return 'unknown';
});
useEffect(() => {
if (loginType !== 'extension') return;
// Re-probe periodically in case the extension injects `window.nostr` late.
let cancelled = false;
const probe = () => {
const n = (globalThis as { nostr?: Record<string, unknown> }).nostr;
if (!n) return false;
setExtensionProbe(typeof n.signPsbt === 'function' ? 'supported' : 'unsupported');
return true;
};
if (probe()) return;
const interval = setInterval(() => {
if (cancelled) return;
if (probe()) clearInterval(interval);
}, 250);
// Stop polling after 3 s — if the extension hasn't shown up by then it
// likely isn't going to.
const stop = setTimeout(() => clearInterval(interval), 3000);
return () => { cancelled = true; clearInterval(interval); clearTimeout(stop); };
}, [loginType]);
// ── Bunker: listen for capability-failure events ─────────────
const [bunkerUnsupported, setBunkerUnsupported] = useState(() =>
user ? knownUnsupportedBunkers.has(user.pubkey) : false,
);
// Reset memoised state whenever the active user changes (login/logout/
// account switch) so a fresh login with a potentially-upgraded signer
// isn't permanently tainted by a previous session's rejection. On full
// logout we also clear the module-level registry entirely, so logging back
// in lets the user try their bunker again.
useEffect(() => {
if (!user) {
setBunkerUnsupported(false);
knownUnsupportedBunkers.clear();
return;
}
setBunkerUnsupported(knownUnsupportedBunkers.has(user.pubkey));
}, [user?.pubkey]); // eslint-disable-line react-hooks/exhaustive-deps
useEffect(() => {
if (loginType !== 'bunker' || !user) return;
const onUnsupported = (e: Event) => {
const detail = (e as CustomEvent<string>).detail;
if (detail === user.pubkey) setBunkerUnsupported(true);
};
const onCleared = (e: Event) => {
const detail = (e as CustomEvent<string>).detail;
if (detail === '*' || detail === user.pubkey) setBunkerUnsupported(false);
};
window.addEventListener('bitcoin-signer-unsupported', onUnsupported);
window.addEventListener('bitcoin-signer-cleared', onCleared);
return () => {
window.removeEventListener('bitcoin-signer-unsupported', onUnsupported);
window.removeEventListener('bitcoin-signer-cleared', onCleared);
};
}, [loginType, user]);
// ── Aggregate capability ─────────────────────────────────────
const capability: BitcoinSignerCapability = useMemo(() => {
if (!user) return 'unsupported';
switch (loginType) {
case 'nsec':
// Local signing is always available for nsec logins.
return 'supported';
case 'extension':
return extensionProbe;
case 'bunker':
return bunkerUnsupported ? 'unsupported' : 'unknown';
default:
// Unknown login type: fall back to the structural check.
return hasBtcSigning(user.signer) ? 'unknown' : 'unsupported';
}
}, [user, loginType, extensionProbe, bunkerUnsupported]);
const btcSigner = useMemo((): BtcSigner | null => {
if (!user || capability === 'unsupported') return null;
if (hasBtcSigning(user.signer)) return user.signer;
return null;
}, [user, capability]);
return {
/** Detailed capability state. See {@link BitcoinSignerCapability}. */
capability,
/** True when capability is `'supported'` or `'unknown'` (attempt allowed). */
canSignPsbt: capability !== 'unsupported' && btcSigner !== null,
/**
* Sign a hex-encoded PSBT. Throws if the signer doesn't support it.
* The returned hex is a signed (but not finalized) PSBT.
*/
signPsbt: btcSigner
? (psbtHex: string) => btcSigner.signPsbt(psbtHex)
: null,
};
}
/**
* Classify a signer error as a "capability error" (the signer fundamentally
* cannot sign PSBTs) versus a transient/operational error (network blip,
* user cancellation, malformed PSBT, etc.).
*
* Used by `useOnchainZap` to decide whether a failed send should flip the
* UI into the `'unsupported'` state or just surface a normal error toast.
*/
export function isSignerCapabilityError(err: unknown): boolean {
if (!err) return false;
const msg = (err instanceof Error ? err.message : String(err)).toLowerCase();
return (
msg.includes('does not support') ||
msg.includes("doesn't support") ||
msg.includes('signpsbt') ||
msg.includes('sign_psbt')
);
}
@@ -0,0 +1,25 @@
import { useQuery } from '@tanstack/react-query';
import { fetchTxDetail, fetchBtcPrice } from '@/lib/bitcoin';
/**
* Fetch full transaction details for a Bitcoin txid via the mempool.space API.
* Also fetches the current BTC/USD price for display.
*/
export function useBitcoinTx(txid: string) {
const { data: tx, isLoading, error } = useQuery({
queryKey: ['bitcoin-tx-detail', txid],
queryFn: () => fetchTxDetail(txid),
enabled: !!txid,
staleTime: 60_000,
});
const { data: btcPrice } = useQuery({
queryKey: ['btc-price'],
queryFn: fetchBtcPrice,
refetchInterval: 60_000,
staleTime: 30_000,
});
return { tx, btcPrice, isLoading, error };
}
@@ -0,0 +1,71 @@
import { useMemo } from 'react';
import { useQuery } from '@tanstack/react-query';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { nostrPubkeyToBitcoinAddress, fetchAddressData, fetchBtcPrice, fetchTransactions } from '@/lib/bitcoin';
/**
* Hook that derives a Bitcoin Taproot address from the current user's Nostr
* pubkey and fetches the on-chain balance from the mempool.space API.
*
* Balance auto-refreshes every 30 seconds while the component is mounted.
* BTC/USD price refreshes every 60 seconds.
*/
export function useBitcoinWallet() {
const { user } = useCurrentUser();
const bitcoinAddress = useMemo(() => {
if (!user) return '';
return nostrPubkeyToBitcoinAddress(user.pubkey);
}, [user]);
const {
data: addressData,
isLoading,
error,
refetch,
} = useQuery({
queryKey: ['bitcoin-balance', bitcoinAddress],
queryFn: () => fetchAddressData(bitcoinAddress),
enabled: !!bitcoinAddress,
refetchInterval: 30_000,
});
const { data: btcPrice } = useQuery({
queryKey: ['btc-price'],
queryFn: fetchBtcPrice,
refetchInterval: 60_000,
staleTime: 30_000,
});
const {
data: transactions,
isLoading: isLoadingTxs,
} = useQuery({
queryKey: ['bitcoin-txs', bitcoinAddress],
queryFn: () => fetchTransactions(bitcoinAddress),
enabled: !!bitcoinAddress,
refetchInterval: 30_000,
});
return {
/** The derived bc1p... Taproot address. */
bitcoinAddress,
/** Balance and transaction data (undefined while loading). */
addressData,
/** Current BTC price in USD. */
btcPrice,
/** Transaction history for the address. */
transactions,
/** Whether the initial balance fetch is in progress. */
isLoading,
/** Whether transactions are still loading. */
isLoadingTxs,
/** Error from the balance query, if any. */
error,
/** Manually trigger a balance refresh. */
refetch,
/** The current user's hex pubkey (convenience). */
pubkey: user?.pubkey ?? '',
};
}
@@ -0,0 +1,217 @@
import { useState } from 'react';
import { useMutation, useQueryClient } from '@tanstack/react-query';
import type { NostrEvent } from '@nostrify/nostrify';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useBitcoinSigner, isSignerCapabilityError, reportSignerUnsupported } from '@/hooks/useBitcoinSigner';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useToast } from '@/hooks/useToast';
import {
nostrPubkeyToBitcoinAddress,
fetchUTXOs,
getFeeRates,
buildUnsignedPsbt,
finalizePsbt,
broadcastTransaction,
estimateFee,
} from '@/lib/bitcoin';
import type { FeeRates } from '@/lib/bitcoin';
export type OnchainFeeSpeed = 'fastest' | 'halfHour' | 'hour' | 'economy';
/**
* Resolves the fee rate for a given speed preset from a FeeRates bundle.
*/
function feeRateForSpeed(rates: FeeRates, speed: OnchainFeeSpeed): number {
switch (speed) {
case 'fastest': return rates.fastestFee;
case 'halfHour': return rates.halfHourFee;
case 'hour': return rates.hourFee;
case 'economy': return rates.economyFee;
}
}
interface OnchainZapArgs {
/** Amount to zap in satoshis. */
amountSats: number;
/** Optional comment to include in the kind 8333 event content. */
comment?: string;
/** Fee speed preset. Defaults to "halfHour". */
feeSpeed?: OnchainFeeSpeed;
}
interface OnchainZapResult {
/** The broadcast Bitcoin transaction ID. */
txid: string;
/** Amount sent in satoshis. */
amountSats: number;
/** Fee paid in satoshis. */
fee: number;
/** The published kind 8333 event. */
event: NostrEvent;
}
/**
* Hook for sending on-chain (Bitcoin L1) zaps to a Nostr event or profile.
*
* Flow:
* 1. Build, sign, and broadcast a Bitcoin transaction paying the target
* author's derived Taproot address.
* 2. Publish a kind 8333 "onchain zap" event referencing the txid, the
* target event (`e` or `a` tag), and the recipient's pubkey.
*
* Unlike NIP-57 Lightning zaps, this works for *any* Nostr user — there is
* no LNURL dependency because every pubkey has a derived Taproot address.
*/
export function useOnchainZap(
target: NostrEvent,
onSuccess?: (result: OnchainZapResult) => void,
) {
const { user } = useCurrentUser();
const { canSignPsbt, signPsbt } = useBitcoinSigner();
const { mutateAsync: publishEvent } = useNostrPublish();
const { toast } = useToast();
const queryClient = useQueryClient();
const [isZapping, setIsZapping] = useState(false);
const [progress, setProgress] = useState<'idle' | 'building' | 'signing' | 'broadcasting' | 'publishing'>('idle');
const mutation = useMutation<OnchainZapResult, Error, OnchainZapArgs>({
mutationFn: async ({ amountSats, comment = '', feeSpeed = 'halfHour' }) => {
if (!user) throw new Error('You must be logged in to zap.');
if (user.pubkey === target.pubkey) throw new Error("You can't zap yourself.");
if (!canSignPsbt || !signPsbt) {
throw new Error(
"Your login doesn't support sending Bitcoin. Log in with your secret key to send Bitcoin zaps.",
);
}
if (!Number.isFinite(amountSats) || amountSats <= 0) {
throw new Error('Invalid amount.');
}
setIsZapping(true);
setProgress('building');
const senderAddress = nostrPubkeyToBitcoinAddress(user.pubkey);
const recipientAddress = nostrPubkeyToBitcoinAddress(target.pubkey);
if (!senderAddress || !recipientAddress) {
throw new Error('Failed to derive Bitcoin address.');
}
// Fetch UTXOs and fee rates
const [utxos, rates] = await Promise.all([
fetchUTXOs(senderAddress),
getFeeRates(),
]);
if (utxos.length === 0) {
throw new Error('Your Bitcoin wallet has no spendable funds.');
}
const feeRate = feeRateForSpeed(rates, feeSpeed);
const totalBalance = utxos.reduce((s, u) => s + u.value, 0);
const estFee = estimateFee(utxos.length, 2, feeRate);
if (amountSats + estFee > totalBalance) {
throw new Error(
`Insufficient funds. Need ~${(amountSats + estFee).toLocaleString()} sats, have ${totalBalance.toLocaleString()}.`,
);
}
// Build unsigned PSBT
const { psbtHex, fee } = buildUnsignedPsbt(
user.pubkey,
recipientAddress,
amountSats,
utxos,
feeRate,
);
// Sign
setProgress('signing');
const signedHex = await signPsbt(psbtHex);
const txHex = finalizePsbt(signedHex);
// Broadcast
setProgress('broadcasting');
const txid = await broadcastTransaction(txHex);
// Publish kind 8333 event
setProgress('publishing');
const isAddressable = target.kind >= 30000 && target.kind < 40000;
const tags: string[][] = [
['i', `bitcoin:tx:${txid}`],
['p', target.pubkey],
['amount', String(amountSats)],
];
if (isAddressable) {
const dTag = target.tags.find(([n]) => n === 'd')?.[1] ?? '';
tags.push(['a', `${target.kind}:${target.pubkey}:${dTag}`]);
}
// Always include `e` for a concrete event reference (even for addressable events)
tags.push(['e', target.id]);
tags.push(['alt', `Bitcoin zap: ${amountSats.toLocaleString()} sats`]);
const event = await publishEvent({
kind: 8333,
content: comment,
tags,
});
return { txid, amountSats, fee, event };
},
onSuccess: (result) => {
// Optimistically mark the target as zapped-by-me so any UI tracking
// user zaps updates immediately, without waiting for the relay echo.
queryClient.setQueryData(['user-zap', target.id], true);
// Invalidate caches that track zaps / balances
queryClient.invalidateQueries({ queryKey: ['onchain-zaps'] });
queryClient.invalidateQueries({ queryKey: ['event-interactions'] });
queryClient.invalidateQueries({ queryKey: ['bitcoin-utxos'] });
queryClient.invalidateQueries({ queryKey: ['bitcoin-balance'] });
queryClient.invalidateQueries({ queryKey: ['bitcoin-txs'] });
// If the caller opted into handling success themselves, skip the toast.
if (onSuccess) {
onSuccess(result);
} else {
toast({
title: 'Bitcoin zap sent!',
description: `Broadcast txid ${result.txid.slice(0, 12)}… (fee ${result.fee.toLocaleString()} sats)`,
});
}
},
onError: (err) => {
// If the signer turned out to not support PSBT signing (common for
// NIP-46 bunkers where capability can't be probed up front), mark the
// signer as unsupported for the rest of the session. The dialog UI
// watches this state and replaces itself with an "unsupported" panel
// instead of relying on this toast.
if (isSignerCapabilityError(err) && user) {
reportSignerUnsupported(user.pubkey);
return;
}
toast({
title: 'Bitcoin zap failed',
description: err.message,
variant: 'destructive',
});
},
onSettled: () => {
setIsZapping(false);
setProgress('idle');
},
});
return {
zap: mutation.mutate,
zapAsync: mutation.mutateAsync,
isZapping,
progress,
canZap: !!user && user.pubkey !== target.pubkey && canSignPsbt,
/** Whether the logged-in user has a PSBT-capable signer. */
canSignPsbt,
};
}
@@ -0,0 +1,205 @@
import { useQueries, useQuery } from '@tanstack/react-query';
import { useNostr } from '@nostrify/react';
import type { NostrEvent } from '@nostrify/nostrify';
import { fetchTxDetail, nostrPubkeyToBitcoinAddress } from '@/lib/bitcoin';
/** A single verified on-chain zap, with the amount that actually paid the recipient on-chain. */
export interface OnchainZapEntry {
/** The kind 8333 event. */
event: NostrEvent;
/** Bitcoin transaction id (lowercase hex). */
txid: string;
/** Pubkey of the sender (the 8333 event author). */
senderPubkey: string;
/** Pubkey of the recipient (from `p` tag). */
recipientPubkey: string;
/** Verified amount in sats — sum of tx outputs that pay the recipient's derived Taproot address. */
amountSats: number;
/** Sender's self-reported amount (may differ from verified). */
claimedAmountSats: number;
/** Comment from the 8333 event content. */
comment: string;
/** Unix timestamp of the 8333 event. */
createdAt: number;
/** Whether the Bitcoin tx is confirmed on-chain. */
confirmed: boolean;
}
/** Parse the txid from a kind 8333 event's `i` tag. Returns null if missing or malformed. */
export function extractOnchainZapTxid(event: NostrEvent): string | null {
const iTag = event.tags.find(([n, v]) => n === 'i' && typeof v === 'string' && v.startsWith('bitcoin:tx:'));
if (!iTag?.[1]) return null;
const txid = iTag[1].slice('bitcoin:tx:'.length).toLowerCase();
if (!/^[0-9a-f]{64}$/.test(txid)) return null;
return txid;
}
/** Parse the claimed amount (sats) from a kind 8333 event. */
export function extractOnchainZapClaimedAmount(event: NostrEvent): number {
const tag = event.tags.find(([n]) => n === 'amount');
if (!tag?.[1]) return 0;
const n = parseInt(tag[1], 10);
return Number.isFinite(n) && n > 0 ? n : 0;
}
/** Parse the recipient pubkey from a kind 8333 event (first `p` tag). */
export function extractOnchainZapRecipient(event: NostrEvent): string {
const tag = event.tags.find(([n]) => n === 'p');
return tag?.[1] ?? '';
}
/**
* Verify a kind 8333 on-chain zap event against the Bitcoin blockchain.
*
* Returns the verified amount (sum of tx outputs paying the recipient's
* derived Taproot address) and confirmation status. Returns `null` if the
* event is malformed or the transaction cannot be verified.
*
* A verified amount of 0 means the transaction exists but does not pay
* the claimed recipient — callers should discard such events.
*/
export async function verifyOnchainZap(event: NostrEvent): Promise<OnchainZapEntry | null> {
const txid = extractOnchainZapTxid(event);
const recipientPubkey = extractOnchainZapRecipient(event);
if (!txid || !recipientPubkey) return null;
// Reject self-zaps (sender == recipient). The sender already controls the
// destination address, so self-zaps are trivial to fabricate and contribute
// nothing meaningful to zap totals.
if (event.pubkey === recipientPubkey) return null;
const recipientAddress = nostrPubkeyToBitcoinAddress(recipientPubkey);
if (!recipientAddress) return null;
let detail;
try {
detail = await fetchTxDetail(txid);
} catch {
return null;
}
const amountSats = detail.outputs
.filter((o) => o.address === recipientAddress)
.reduce((sum, o) => sum + o.value, 0);
if (amountSats === 0) return null;
const claimed = extractOnchainZapClaimedAmount(event);
// If the sender is claiming more than the tx actually paid, cap it at the verified amount.
const effectiveClaim = Math.min(claimed || amountSats, amountSats);
return {
event,
txid,
senderPubkey: event.pubkey,
recipientPubkey,
amountSats: effectiveClaim,
claimedAmountSats: claimed,
comment: event.content,
createdAt: event.created_at,
confirmed: detail.confirmed,
};
}
/**
* Query all kind 8333 on-chain zaps targeting a specific event, then verify
* each one on-chain. Returns only verified entries (deduped by txid).
*/
export function useOnchainZaps(target: NostrEvent | undefined) {
const { nostr } = useNostr();
const isAddressable = target && target.kind >= 30000 && target.kind < 40000;
const dTag = isAddressable
? target.tags.find(([n]) => n === 'd')?.[1] ?? ''
: '';
const aCoord = isAddressable && target ? `${target.kind}:${target.pubkey}:${dTag}` : '';
// Step 1: fetch the raw kind 8333 events for this target
const eventsQuery = useQuery({
queryKey: ['onchain-zaps', 'events', target?.id ?? '', aCoord],
queryFn: async ({ signal }) => {
if (!target) return [] as NostrEvent[];
const timeout = AbortSignal.timeout(5000);
const combined = AbortSignal.any([signal, timeout]);
const filters: Parameters<typeof nostr.query>[0] = [
{ kinds: [8333], '#e': [target.id], limit: 100 },
];
if (aCoord) {
filters.push({ kinds: [8333], '#a': [aCoord], limit: 100 });
}
const events = await nostr.query(filters, { signal: combined });
// Dedupe by event id, then by txid (one canonical zap per tx per target).
const byId = new Map<string, NostrEvent>();
for (const e of events) byId.set(e.id, e);
const byTxid = new Map<string, NostrEvent>();
for (const e of byId.values()) {
const txid = extractOnchainZapTxid(e);
if (!txid) continue;
const existing = byTxid.get(txid);
// Prefer the earliest event for each txid (first to claim this tx).
if (!existing || e.created_at < existing.created_at) {
byTxid.set(txid, e);
}
}
return Array.from(byTxid.values());
},
enabled: !!target,
staleTime: 30_000,
});
// Step 2: verify each event on-chain (parallel, cached per txid)
const events = eventsQuery.data ?? [];
const verifications = useQueries({
queries: events.map((event) => ({
queryKey: ['onchain-zaps', 'verify', extractOnchainZapTxid(event), extractOnchainZapRecipient(event)],
queryFn: () => verifyOnchainZap(event),
staleTime: 60_000,
})),
});
const verified: OnchainZapEntry[] = verifications
.map((v) => v.data)
.filter((v): v is OnchainZapEntry => !!v);
// Sort by verified amount (largest first)
verified.sort((a, b) => b.amountSats - a.amountSats);
const totalSats = verified.reduce((s, v) => s + v.amountSats, 0);
const isLoading = eventsQuery.isLoading || verifications.some((v) => v.isLoading);
return {
zaps: verified,
totalSats,
count: verified.length,
isLoading,
};
}
/**
* Verify a single kind 8333 event against the Bitcoin blockchain and return
* the resulting `OnchainZapEntry`. Used by standalone surfaces (embedded
* cards, detail page) that need to display a verified amount without doing
* a full `#e`/`#a` fan-out.
*
* Returns `undefined` while loading, `null` if the event fails verification
* (invalid tx, wrong recipient, self-zap, etc.), or the entry.
*/
export function useVerifiedOnchainZap(event: NostrEvent | undefined): OnchainZapEntry | null | undefined {
const txid = event ? extractOnchainZapTxid(event) : null;
const recipient = event ? extractOnchainZapRecipient(event) : '';
const { data } = useQuery({
queryKey: ['onchain-zaps', 'verify', txid, recipient],
queryFn: () => verifyOnchainZap(event!),
enabled: !!event && !!txid && !!recipient,
staleTime: 60_000,
});
if (!event) return null;
return data;
}
@@ -0,0 +1,144 @@
import type { NostrSigner } from '@nostrify/types';
import { NSecSigner, NConnectSigner } from '@nostrify/nostrify';
import type { NConnectSignerOpts } from '@nostrify/nostrify';
import { signPsbtLocal } from '@/lib/bitcoin';
import { Nip07Signer } from '@/lib/Nip07Signer';
// ---------------------------------------------------------------------------
// BtcSigner interface
// ---------------------------------------------------------------------------
/**
* A Nostr signer extended with Bitcoin PSBT signing capability.
*
* Implementations receive a hex-encoded unsigned PSBT, sign all Taproot
* inputs whose `tapInternalKey` matches the signer's key, and return the
* hex-encoded signed (but not finalized) PSBT.
*/
export interface BtcSigner extends NostrSigner {
signPsbt(psbtHex: string): Promise<string>;
}
/** Runtime check for whether a signer supports `signPsbt`. */
export function hasBtcSigning(signer: NostrSigner): signer is BtcSigner {
return typeof (signer as BtcSigner).signPsbt === 'function';
}
// ---------------------------------------------------------------------------
// NSecSignerBtc — local nsec signing
// ---------------------------------------------------------------------------
/**
* Extends `NSecSigner` with local Taproot PSBT signing.
*
* `NSecSigner` stores the secret key in a JS `#private` field that subclasses
* cannot access. To work around this, the constructor accepts the raw secret
* key bytes, passes them to `super()`, and keeps its own copy in a true
* runtime-private `#secretKeyBytes` field so the key is not reachable via
* property enumeration or reflection on the instance.
*/
export class NSecSignerBtc extends NSecSigner implements BtcSigner {
readonly #secretKeyBytes: Uint8Array;
constructor(secretKey: Uint8Array) {
super(secretKey);
this.#secretKeyBytes = new Uint8Array(secretKey);
}
async signPsbt(psbtHex: string): Promise<string> {
const privateKeyHex = Buffer.from(this.#secretKeyBytes).toString('hex');
return signPsbtLocal(psbtHex, privateKeyHex);
}
}
// ---------------------------------------------------------------------------
// NBrowserSignerBtc — NIP-07 extension signing
// ---------------------------------------------------------------------------
/**
* Extends the template's `Nip07Signer` with NIP-07 `window.nostr.signPsbt()`
* support. Like `Nip07Signer`, it acts as the login's account (`pubkey`)
* through the extension's `getSigner` where the extension offers it.
*
* Calls the extension's `signPsbt` method if available. If the extension does
* not expose `signPsbt`, an error is thrown with a user-friendly message.
*/
export class NBrowserSignerBtc extends Nip07Signer implements BtcSigner {
constructor(opts?: { pubkey?: string; timeout?: number }) {
super(opts);
}
async signPsbt(psbtHex: string): Promise<string> {
const signer = await this.signer();
if (typeof signer.signPsbt !== 'function') {
throw new Error(
"Your browser extension doesn't support sending Bitcoin. Try a different extension, or log in with your secret key.",
);
}
return signer.signPsbt(psbtHex);
}
}
// ---------------------------------------------------------------------------
// NConnectSignerBtc — NIP-46 remote signer
// ---------------------------------------------------------------------------
/**
* Heuristics for detecting whether a NIP-46 `sign_psbt` error reflects a
* missing-capability rejection (e.g. "method not supported", "unknown
* command") versus a transient operational failure (network, user rejection,
* malformed input). We have to match on strings because NIP-46 errors are
* plain strings without structured codes.
*/
const CAPABILITY_ERROR_PATTERNS = [
/unknown\s+(method|command)/i,
/not\s+(implemented|supported|found)/i,
/unsupported\s+method/i,
/method\s+not\s+found/i,
/invalid\s+method/i,
/no\s+such\s+method/i,
];
function looksLikeCapabilityError(msg: string): boolean {
return CAPABILITY_ERROR_PATTERNS.some((re) => re.test(msg));
}
/**
* Extends `NConnectSigner` with NIP-46 `sign_psbt` RPC support.
*
* Sends a `sign_psbt` command over the NIP-46 relay channel. The remote
* signer handles the TapTweak and Schnorr signing internally.
*
* NIP-46 returns unstructured string errors, so we use pattern matching to
* distinguish capability failures (the signer doesn't know the method) from
* operational failures (network, user rejection, bad input). Only capability
* failures are re-wrapped with the "doesn't support sending Bitcoin" message
* that flips the UI into the unsupported state; everything else propagates
* unchanged so the caller can surface the real error.
*/
export class NConnectSignerBtc extends NConnectSigner implements BtcSigner {
constructor(opts: NConnectSignerOpts) {
super(opts);
}
async signPsbt(psbtHex: string): Promise<string> {
// `cmd` is TypeScript-private but JavaScript-public at runtime.
const cmd = (this as unknown as { cmd(method: string, params: string[]): Promise<string> }).cmd;
try {
return await cmd.call(this, 'sign_psbt', [psbtHex]);
} catch (error) {
const msg = error instanceof Error ? error.message : String(error);
if (looksLikeCapabilityError(msg)) {
throw new Error(
`Your remote signer doesn't support sending Bitcoin. Update your signer, or log in with your secret key. (${msg})`,
);
}
// Not a capability failure — propagate the original error so the user
// sees the actual reason (timeout, rejection, malformed PSBT, etc.).
throw error;
}
}
}
@@ -0,0 +1,683 @@
import * as bitcoin from 'bitcoinjs-lib';
import { toXOnly } from 'bitcoinjs-lib';
import { nip19 } from 'nostr-tools';
import * as ecc from '@bitcoinerlab/secp256k1';
import { ECPairFactory, type ECPairAPI } from 'ecpair';
// ---------------------------------------------------------------------------
// Constants
// ---------------------------------------------------------------------------
/** Base URL for the mempool.space Esplora-compatible REST API. */
const MEMPOOL_API = 'https://mempool.space/api';
/** Standard Bitcoin dust limit in satoshis. */
const DUST_LIMIT = 546;
/** Estimated vBytes per P2TR input. */
const VBYTES_PER_INPUT = 57.5;
/** Estimated vBytes per P2TR output. */
const VBYTES_PER_OUTPUT = 43;
/** Estimated vBytes for transaction overhead (version, locktime, etc.). */
const VBYTES_OVERHEAD = 10.5;
// ---------------------------------------------------------------------------
// ECC initialisation (lazy)
// ---------------------------------------------------------------------------
let _ECPair: ECPairAPI | null = null;
function getECPair(): ECPairAPI {
if (!_ECPair) {
bitcoin.initEccLib(ecc);
_ECPair = ECPairFactory(ecc);
}
return _ECPair;
}
/**
* Strict 32-byte hex validator. Rejects anything that isn't exactly 64
* lowercase-or-uppercase hex characters.
*/
function isValidPubkeyHex(hex: string): boolean {
return typeof hex === 'string' && /^[0-9a-fA-F]{64}$/.test(hex);
}
/**
* Convert a Nostr public key (32-byte hex) to a Bitcoin Taproot (P2TR) address.
*
* Both Nostr and Bitcoin Taproot use secp256k1 with 32-byte x-only public keys
* (Schnorr / BIP-340), so the key can be used directly as a Taproot internal
* public key with no mathematical conversion.
*
* Returns an empty string if the input is malformed or not a valid x-only key
* on the secp256k1 curve.
*/
export function nostrPubkeyToBitcoinAddress(pubkeyHex: string): string {
if (!isValidPubkeyHex(pubkeyHex)) return '';
try {
const pubkeyBuffer = Buffer.from(pubkeyHex, 'hex');
const { address } = bitcoin.payments.p2tr({
internalPubkey: pubkeyBuffer,
network: bitcoin.networks.bitcoin,
});
return address || '';
} catch (error) {
console.error('Error generating Bitcoin address:', error);
return '';
}
}
/**
* Convert a bech32 `npub1...` identifier to a Bitcoin Taproot (P2TR) address.
* Decodes the npub to a hex pubkey, then delegates to {@link nostrPubkeyToBitcoinAddress}.
*/
export function npubToBitcoinAddress(npub: string): string {
const decoded = nip19.decode(npub);
if (decoded.type !== 'npub') {
throw new Error('Invalid npub format');
}
return nostrPubkeyToBitcoinAddress(decoded.data);
}
// ---------------------------------------------------------------------------
// Balance / Address data (wallet page)
// ---------------------------------------------------------------------------
/** Balance data returned by the Esplora API. */
export interface AddressData {
/** Confirmed on-chain balance in satoshis. */
balance: number;
/** Unconfirmed mempool balance in satoshis. */
pendingBalance: number;
/** Sum of confirmed + pending balance. */
totalBalance: number;
/** Total satoshis ever received (confirmed). */
totalReceived: number;
/** Total satoshis ever sent (confirmed). */
totalSent: number;
/** Confirmed transaction count. */
txCount: number;
/** Pending (mempool) transaction count. */
pendingTxCount: number;
}
/**
* Fetch balance and transaction stats for a Bitcoin address from the
* mempool.space Esplora API.
*/
export async function fetchAddressData(address: string): Promise<AddressData> {
const response = await fetch(`${MEMPOOL_API}/address/${address}`);
if (!response.ok) {
throw new Error('Failed to fetch balance');
}
const data = await response.json();
const confirmedBalance = data.chain_stats.funded_txo_sum - data.chain_stats.spent_txo_sum;
const pendingBalance = data.mempool_stats.funded_txo_sum - data.mempool_stats.spent_txo_sum;
return {
balance: confirmedBalance,
pendingBalance,
totalBalance: confirmedBalance + pendingBalance,
totalReceived: data.chain_stats.funded_txo_sum,
totalSent: data.chain_stats.spent_txo_sum,
txCount: data.chain_stats.tx_count,
pendingTxCount: data.mempool_stats.tx_count,
};
}
// ---------------------------------------------------------------------------
// Formatting helpers
// ---------------------------------------------------------------------------
/** Convert satoshis to a BTC string with up to 8 decimal places. */
export function satsToBTC(sats: number): string {
return (sats / 100_000_000).toFixed(8);
}
/**
* Convert satoshis to a BTC string with trailing zeros stripped.
* E.g. `formatBTC(100_000_000)` → `"1"`, `formatBTC(1_234_560)` → `"0.0123456"`.
*/
export function formatBTC(sats: number): string {
return satsToBTC(sats).replace(/\.?0+$/, '');
}
/** Format a satoshi amount with locale-aware thousand separators. */
export function formatSats(sats: number): string {
return sats.toLocaleString();
}
/** Fetch the current BTC price in USD from the CoinGecko API. */
export async function fetchBtcPrice(): Promise<number> {
const response = await fetch(
'https://api.coingecko.com/api/v3/simple/price?ids=bitcoin&vs_currencies=usd',
);
if (!response.ok) {
throw new Error('Failed to fetch BTC price');
}
const data = await response.json();
return data.bitcoin.usd;
}
/** Convert a BTC amount to satoshis (rounded to nearest integer). */
export function btcToSats(btc: number): number {
return Math.round(btc * 100_000_000);
}
/**
* USD threshold above which Bitcoin send/zap flows should require explicit
* confirmation (two-tap). Chosen to catch meaningful dollar amounts without
* nagging on everyday $5–$25 zaps.
*/
export const LARGE_AMOUNT_USD_THRESHOLD = 100;
/**
* Whether a given satoshi amount crosses the "large amount" threshold at the
* current BTC/USD price. Returns false when `btcPrice` is unavailable, so the
* UI does not arm confirmation without a known USD value.
*/
export function isLargeAmount(sats: number, btcPrice: number | undefined): boolean {
if (!btcPrice || !Number.isFinite(btcPrice) || btcPrice <= 0) return false;
if (!Number.isFinite(sats) || sats <= 0) return false;
const usd = (sats / 100_000_000) * btcPrice;
return usd >= LARGE_AMOUNT_USD_THRESHOLD;
}
/** Convert satoshis to USD given a BTC price. */
export function satsToUSD(sats: number, btcPrice: number): string {
const btc = sats / 100_000_000;
return (btc * btcPrice).toLocaleString('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
}
// ---------------------------------------------------------------------------
// Wallet-page transaction list (simplified per-address view)
// ---------------------------------------------------------------------------
/** A simplified transaction relevant to a specific address. */
export interface Transaction {
/** Transaction ID (hex). */
txid: string;
/** Net satoshi change for the address (always positive — see `type`). */
amount: number;
/** Whether this is a receive or send relative to the address. */
type: 'receive' | 'send';
/** Whether the transaction is confirmed. */
confirmed: boolean;
/** Unix timestamp of the block (undefined if unconfirmed). */
timestamp?: number;
}
/**
* Fetch transactions for a Bitcoin address from the mempool.space Esplora API.
* Returns simplified transactions with net amount relative to the address.
*/
export async function fetchTransactions(address: string): Promise<Transaction[]> {
const response = await fetch(`${MEMPOOL_API}/address/${address}/txs`);
if (!response.ok) {
throw new Error('Failed to fetch transactions');
}
const txs = await response.json();
return txs.map((tx: Record<string, unknown>) => {
const vin = tx.vin as Array<{ prevout: { scriptpubkey_address?: string; value: number } | null }>;
const vout = tx.vout as Array<{ scriptpubkey_address?: string; value: number }>;
const status = tx.status as { confirmed: boolean; block_time?: number };
// Sum sats flowing out of this address (inputs we owned)
const totalIn = vin.reduce((sum, input) => {
if (input.prevout?.scriptpubkey_address === address) {
return sum + input.prevout.value;
}
return sum;
}, 0);
// Sum sats flowing into this address (outputs we own)
const totalOut = vout.reduce((sum, output) => {
if (output.scriptpubkey_address === address) {
return sum + output.value;
}
return sum;
}, 0);
const net = totalOut - totalIn;
return {
txid: tx.txid as string,
amount: Math.abs(net),
type: net >= 0 ? 'receive' : 'send',
confirmed: status.confirmed,
timestamp: status.block_time,
} satisfies Transaction;
});
}
// ---------------------------------------------------------------------------
// Full transaction detail (NIP-73 /:nip19 bitcoin:tx:... page)
// ---------------------------------------------------------------------------
/** A single input in a full transaction. */
export interface TxInput {
txid: string;
vout: number;
address?: string;
value: number;
isCoinbase: boolean;
}
/** A single output in a full transaction. */
export interface TxOutput {
address?: string;
value: number;
scriptpubkeyType: string;
/** True if the output has been spent. */
spent: boolean;
}
/** Full transaction detail returned by the Esplora API. */
export interface TxDetail {
txid: string;
version: number;
locktime: number;
size: number;
weight: number;
fee: number;
confirmed: boolean;
blockHeight?: number;
blockHash?: string;
blockTime?: number;
inputs: TxInput[];
outputs: TxOutput[];
/** Total value of all inputs (sats). */
totalInput: number;
/** Total value of all outputs (sats). */
totalOutput: number;
}
/** Fetch full transaction details from mempool.space. */
export async function fetchTxDetail(txid: string): Promise<TxDetail> {
const response = await fetch(`${MEMPOOL_API}/tx/${txid}`);
if (!response.ok) throw new Error('Failed to fetch transaction');
const tx = await response.json();
const vin = tx.vin as Array<{
txid: string;
vout: number;
prevout: { scriptpubkey_address?: string; value: number } | null;
is_coinbase: boolean;
}>;
const vout = tx.vout as Array<{
scriptpubkey_address?: string;
value: number;
scriptpubkey_type: string;
}>;
const status = tx.status as { confirmed: boolean; block_height?: number; block_hash?: string; block_time?: number };
const inputs: TxInput[] = vin.map((input) => ({
txid: input.txid,
vout: input.vout,
address: input.prevout?.scriptpubkey_address,
value: input.prevout?.value ?? 0,
isCoinbase: input.is_coinbase,
}));
const outputs: TxOutput[] = vout.map((output) => ({
address: output.scriptpubkey_address,
value: output.value,
scriptpubkeyType: output.scriptpubkey_type,
spent: false, // Esplora /tx endpoint doesn't include spending info
}));
const totalInput = inputs.reduce((sum, i) => sum + i.value, 0);
const totalOutput = outputs.reduce((sum, o) => sum + o.value, 0);
return {
txid: tx.txid as string,
version: tx.version as number,
locktime: tx.locktime as number,
size: tx.size as number,
weight: tx.weight as number,
fee: tx.fee as number,
confirmed: status.confirmed,
blockHeight: status.block_height,
blockHash: status.block_hash,
blockTime: status.block_time,
inputs,
outputs,
totalInput,
totalOutput,
};
}
// ---------------------------------------------------------------------------
// Full address detail (NIP-73 /:nip19 bitcoin:address:... page)
// ---------------------------------------------------------------------------
/** Full address detail combining balance stats + recent transactions. */
export interface AddressDetail {
address: string;
balance: number;
pendingBalance: number;
totalBalance: number;
totalReceived: number;
totalSent: number;
txCount: number;
pendingTxCount: number;
/** Most recent transactions (up to 25). */
recentTxs: Transaction[];
}
/** Fetch full address details (balance + recent txs) from mempool.space. */
export async function fetchAddressDetail(address: string): Promise<AddressDetail> {
const [addrData, txs] = await Promise.all([
fetchAddressData(address),
fetchTransactions(address),
]);
return {
address,
...addrData,
recentTxs: txs.slice(0, 25),
};
}
// ---------------------------------------------------------------------------
// Sending: UTXOs, fee estimation, transaction construction, broadcast
// ---------------------------------------------------------------------------
/** An unspent transaction output. */
export interface UTXO {
txid: string;
vout: number;
/** Value in satoshis. */
value: number;
status: {
confirmed: boolean;
block_height?: number;
block_hash?: string;
block_time?: number;
};
}
/** Fetch UTXOs for a Bitcoin address from mempool.space. */
export async function fetchUTXOs(address: string): Promise<UTXO[]> {
const response = await fetch(`${MEMPOOL_API}/address/${address}/utxo`);
if (!response.ok) throw new Error('Failed to fetch UTXOs');
return response.json();
}
/** Fee rate estimates keyed by confirmation speed. */
export interface FeeRates {
/** ~10 min / next block (target 1). */
fastestFee: number;
/** ~30 min (target 3). */
halfHourFee: number;
/** ~1 hour (target 6). */
hourFee: number;
/** ~1 day (target 144). */
economyFee: number;
/** Minimum relay fee (target 504). */
minimumFee: number;
}
/** Fetch recommended fee rates (sat/vB) from mempool.space. */
export async function getFeeRates(): Promise<FeeRates> {
const response = await fetch(`${MEMPOOL_API}/fee-estimates`);
if (!response.ok) throw new Error('Failed to fetch fee estimates');
const data = await response.json();
return {
fastestFee: sanitizeFeeRate(data?.['1']),
halfHourFee: sanitizeFeeRate(data?.['3']),
hourFee: sanitizeFeeRate(data?.['6']),
economyFee: sanitizeFeeRate(data?.['144']),
minimumFee: sanitizeFeeRate(data?.['504']),
};
}
/**
* Highest fee rate we will accept from a remote endpoint, in sat/vB. Well
* above any real congestion (mainnet peaks have not passed ~2000 sat/vB) and
* far below anything that could quietly consume a wallet.
*/
const MAX_PLAUSIBLE_FEE_RATE = 5_000;
/**
* Coerce a fee rate from an Esplora `/fee-estimates` response to a usable
* sat/vB number, falling back to 1 for anything implausible.
*
* The endpoint is remote, and this used to be `Math.ceil(data['1'] || 1)`.
* `||` only catches *falsy* values, so a missing key was safe but a truthy
* non-number — `{"1": "5"}`, `{"1": {"fee": 5}}`, the sort of thing an
* API-version mismatch produces — yielded `NaN`. NaN then passed every
* downstream guard, because they are all `<` / `>=` comparisons and every
* comparison with NaN is false: no change output was added, nothing threw, the
* balance check passed, and the UI rendered "Fee 0" because `!NaN` is true.
* The result was a valid, broadcastable transaction that paid the wallet's
* entire remaining balance to miners.
*/
function sanitizeFeeRate(value: unknown): number {
if (typeof value !== 'number' || !Number.isFinite(value)) return 1;
if (value < 1) return 1;
if (value > MAX_PLAUSIBLE_FEE_RATE) return MAX_PLAUSIBLE_FEE_RATE;
return Math.ceil(value);
}
/**
* Estimate the fee for a P2TR transaction in satoshis.
*
* @param numInputs Number of Taproot inputs.
* @param numOutputs Number of outputs (recipient + optional change).
* @param feeRate Fee rate in sat/vB.
*/
export function estimateFee(numInputs: number, numOutputs: number, feeRate: number): number {
// Assert rather than infer. A non-finite rate produces a NaN fee, and every
// guard downstream of this is a `<` or `>=` comparison, all of which are
// false for NaN — so the failure surfaces as a transaction that hands the
// wallet's balance to miners rather than as an error.
if (!Number.isFinite(feeRate) || feeRate < 1) {
throw new Error(`Invalid fee rate: ${feeRate} sat/vB.`);
}
const vBytes = numInputs * VBYTES_PER_INPUT + numOutputs * VBYTES_PER_OUTPUT + VBYTES_OVERHEAD;
return Math.ceil(vBytes * feeRate);
}
/**
* Validate a Bitcoin address (mainnet). Returns `true` if the address has a
* valid format and checksum, `false` otherwise.
*/
export function validateBitcoinAddress(address: string): boolean {
try {
bitcoin.address.toOutputScript(address, bitcoin.networks.bitcoin);
return true;
} catch {
return false;
}
}
/** Broadcast a signed transaction hex to the Bitcoin network via mempool.space. Returns the txid. */
export async function broadcastTransaction(txHex: string): Promise<string> {
const response = await fetch(`${MEMPOOL_API}/tx`, {
method: 'POST',
body: txHex,
});
if (!response.ok) {
const body = await response.text();
throw new Error(`Broadcast failed: ${body}`);
}
return response.text();
}
/**
* Compute the maximum sendable amount (in sats) after fees.
*
* @param totalBalance Total spendable sats across all UTXOs.
* @param numInputs Number of UTXOs that will be consumed.
* @param feeRate Fee rate in sat/vB.
* @returns The max amount in sats, or 0 if the balance cannot cover fees.
*/
export function maxSendable(totalBalance: number, numInputs: number, feeRate: number): number {
// When sending max there is no change output, so only 1 output.
const fee = estimateFee(numInputs, 1, feeRate);
return Math.max(0, totalBalance - fee);
}
/** Result of building an unsigned PSBT. */
export interface UnsignedPsbt {
/** Hex-encoded unsigned PSBT. */
psbtHex: string;
/** Fee in satoshis. */
fee: number;
}
/**
* Build an unsigned Taproot PSBT ready for signing.
*
* This function constructs the PSBT with all inputs and outputs but does NOT
* sign it. The returned hex can be passed to any signer (local nsec, NIP-07
* extension, or NIP-46 remote signer).
*
* @param senderPubkeyHex 32-byte hex x-only public key of the sender.
* @param toAddress Recipient Bitcoin address.
* @param amountSats Amount to send in satoshis.
* @param utxos Available UTXOs (all will be consumed).
* @param feeRate Fee rate in sat/vB.
*/
export function buildUnsignedPsbt(
senderPubkeyHex: string,
toAddress: string,
amountSats: number,
utxos: UTXO[],
feeRate: number,
): UnsignedPsbt {
const internalPubkey = Buffer.from(senderPubkeyHex, 'hex');
// Derive change address (same Taproot address as sender)
const { address: changeAddress } = bitcoin.payments.p2tr({
internalPubkey,
network: bitcoin.networks.bitcoin,
});
if (!changeAddress) throw new Error('Failed to derive change address');
// Build PSBT, add all UTXOs as inputs
const psbt = new bitcoin.Psbt({ network: bitcoin.networks.bitcoin });
let totalInput = 0;
for (const utxo of utxos) {
psbt.addInput({
hash: utxo.txid,
index: utxo.vout,
witnessUtxo: {
script: bitcoin.payments.p2tr({
internalPubkey,
network: bitcoin.networks.bitcoin,
}).output!,
value: BigInt(utxo.value),
},
tapInternalKey: internalPubkey,
});
totalInput += utxo.value;
}
// Estimate fee — first assume 2 outputs (recipient + change). Change at the
// dust limit exactly is still standard, so use >= (not >) per BIP-141/P2TR
// relay policy (minimum non-dust output is 546 sats).
const change2Out = totalInput - amountSats - estimateFee(utxos.length, 2, feeRate);
const hasChange = change2Out >= DUST_LIMIT;
const numOutputs = hasChange ? 2 : 1;
const fee = estimateFee(utxos.length, numOutputs, feeRate);
const change = totalInput - amountSats - fee;
if (change < 0) {
throw new Error(
`Insufficient funds. Need ${(amountSats + fee).toLocaleString()} sats, have ${totalInput.toLocaleString()} sats.`,
);
}
// Add outputs
psbt.addOutput({ address: toAddress, value: BigInt(amountSats) });
if (hasChange) {
psbt.addOutput({ address: changeAddress, value: BigInt(change) });
}
return { psbtHex: psbt.toHex(), fee };
}
/**
* Sign a PSBT locally using a raw private key (nsec).
*
* Applies the BIP-341 TapTweak to the private key, signs all inputs whose
* `tapInternalKey` matches, and returns the signed (but not finalized) PSBT hex.
*
* @param psbtHex Hex-encoded unsigned PSBT.
* @param privateKeyHex 32-byte hex private key.
* @returns Hex-encoded signed PSBT (not finalized).
*/
export function signPsbtLocal(psbtHex: string, privateKeyHex: string): string {
bitcoin.initEccLib(ecc);
const psbt = bitcoin.Psbt.fromHex(psbtHex, { network: bitcoin.networks.bitcoin });
const keyPair = getECPair().fromPrivateKey(Buffer.from(privateKeyHex, 'hex'));
const internalPubkey = toXOnly(keyPair.publicKey);
// Tweak private key for Taproot key-path spending (BIP-341)
const tweakedSigner = keyPair.tweak(
bitcoin.crypto.taggedHash('TapTweak', internalPubkey),
);
// Per BITCOIN-SIGNING.md: inputs whose `tapInternalKey` does not match the
// signer's x-only pubkey MUST be left unchanged. This matters for future
// multi-signer PSBTs; today `buildUnsignedPsbt` only ever adds the user's
// own UTXOs, so in practice every input matches.
let signedAny = false;
for (let i = 0; i < psbt.inputCount; i++) {
const input = psbt.data.inputs[i];
const inputInternalKey = input.tapInternalKey;
if (!inputInternalKey || !Buffer.from(inputInternalKey).equals(Buffer.from(internalPubkey))) {
continue;
}
psbt.signInput(i, tweakedSigner);
signedAny = true;
}
if (!signedAny) {
throw new Error('No inputs in this PSBT are owned by the signer.');
}
return psbt.toHex();
}
/**
* Finalize a signed PSBT and extract the raw transaction hex.
*
* @param psbtHex Hex-encoded signed PSBT.
* @returns Raw transaction hex ready for broadcast.
*/
export function finalizePsbt(psbtHex: string): string {
bitcoin.initEccLib(ecc);
const psbt = bitcoin.Psbt.fromHex(psbtHex, { network: bitcoin.networks.bitcoin });
psbt.finalizeAllInputs();
return psbt.extractTransaction().toHex();
}
+121
View File
@@ -0,0 +1,121 @@
---
name: plausible-analytics
description: Add Plausible Analytics tracking to the application, configured through AppConfig and environment variables.
---
# Plausible Analytics
Add privacy-friendly analytics with [Plausible](https://plausible.io/) using the `@plausible-analytics/tracker` npm package. Configuration lives in `AppConfig` so it can be set via `VITE_` environment variables.
## 1. Install the package
```bash
npm install @plausible-analytics/tracker
```
## 2. Add fields to `AppConfig`
In `src/contexts/AppContext.ts`, add two fields to the `AppConfig` interface:
```typescript
export interface AppConfig {
// ...existing fields...
/** Plausible Analytics domain (empty string = disabled). */
plausibleDomain: string;
/** Plausible Analytics API endpoint (empty string = use default). */
plausibleEndpoint: string;
}
```
## 3. Update the Zod schema in `AppProvider.tsx`
Add the new fields to the `AppConfigSchema`:
```typescript
const AppConfigSchema = z.object({
// ...existing fields...
plausibleDomain: z.string(),
plausibleEndpoint: z.string(),
}) satisfies z.ZodType<AppConfig>;
```
## 4. Create `PlausibleProvider`
Create `src/components/PlausibleProvider.tsx`:
```tsx
import { ReactNode, useEffect, useRef } from 'react';
import { useAppContext } from '@/hooks/useAppContext';
interface PlausibleProviderProps {
children: ReactNode;
}
/**
* Reactively initializes Plausible Analytics from AppConfig.
* Plausible's `init()` can only be called once, so we guard with a ref.
*/
export function PlausibleProvider({ children }: PlausibleProviderProps) {
const { config } = useAppContext();
const initializedRef = useRef(false);
useEffect(() => {
if (initializedRef.current || !config.plausibleDomain) return;
initializedRef.current = true;
import('@plausible-analytics/tracker').then(({ init }) => {
init({
domain: config.plausibleDomain,
...(config.plausibleEndpoint && { endpoint: config.plausibleEndpoint }),
});
}).catch(console.error);
}, [config.plausibleDomain, config.plausibleEndpoint]);
return <>{children}</>;
}
```
## 5. Wire into `App.tsx`
Import `PlausibleProvider` and add it inside `AppProvider` (it needs access to `useAppContext`):
```tsx
import { PlausibleProvider } from '@/components/PlausibleProvider';
// In the defaultConfig, add:
const defaultConfig: AppConfig = {
// ...existing fields...
plausibleDomain: import.meta.env.VITE_PLAUSIBLE_DOMAIN || '',
plausibleEndpoint: import.meta.env.VITE_PLAUSIBLE_ENDPOINT || '',
};
// In the JSX, wrap children of AppProvider:
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
<PlausibleProvider>
{/* ...rest of providers... */}
</PlausibleProvider>
</AppProvider>
```
## 6. Update `TestApp.tsx`
Add the new fields to the test default config with empty strings (disabled):
```typescript
const defaultConfig: AppConfig = {
// ...existing fields...
plausibleDomain: '',
plausibleEndpoint: '',
};
```
## 7. Configure via environment variables
Create or update `.env`:
```
VITE_PLAUSIBLE_DOMAIN="example.com"
VITE_PLAUSIBLE_ENDPOINT="https://plausible.example.com/api/event"
```
`VITE_PLAUSIBLE_ENDPOINT` is optional -- it defaults to Plausible Cloud's endpoint if omitted. Set it when using a self-hosted Plausible instance.
+85
View File
@@ -0,0 +1,85 @@
---
name: relay-management
description: Add a UI for users to view, add, remove, and configure their NIP-65 relay list with per-relay read/write permissions. Publishes kind 10002 events via useNostrPublish and keeps AppContext in sync.
---
# Relay List Manager (NIP-65)
This skill provides `RelayListManager`, a drop-in settings UI that lets the user inspect and edit their NIP-65 relay list. Each row has a URL plus read/write switches, with an add/remove flow and automatic NIP-65 (kind 10002) publishing when the user is logged in.
**The underlying NIP-65 relay state is already active in the template** — it lives in `AppContext`, is synced on login by `NostrSync`, and persists to local storage. This skill only adds the *UI* for managing that state; the core wiring stays untouched.
**This component is not included in the project by default.** When the user wants a relay settings screen, follow the setup instructions below to install the component.
## Files Provided by This Skill
| Skill file | Copy to |
|---|---|
| `files/components/RelayListManager.tsx` | `src/components/RelayListManager.tsx` |
## Setup Instructions
### 1. Dependencies
No extra npm packages are required. The component uses packages already present in the template:
- `lucide-react` — icons (`Plus`, `X`, `Wifi`, `Settings`)
- shadcn/ui — `Button`, `Input`, `Label`, `Switch`, `Popover`
### 2. Copy the Skill File Into `src/`
Copy `.agents/skills/relay-management/files/components/RelayListManager.tsx` into `src/components/RelayListManager.tsx`. The component imports:
- `@/hooks/useAppContext` — reads and updates `config.relayMetadata.relays`
- `@/hooks/useCurrentUser` — determines whether to publish a NIP-65 event on change
- `@/hooks/useNostrPublish` — publishes kind 10002 events
- `@/hooks/useToast` — user feedback
All of these are standard in the template; no extra work is needed beyond copying the file.
## Usage
Drop the component anywhere you want a relay settings panel — typically a dedicated settings page:
```tsx
import { RelayListManager } from '@/components/RelayListManager';
export default function SettingsPage() {
return (
<div className="container mx-auto max-w-2xl py-8 space-y-6">
<h1 className="text-2xl font-semibold">Settings</h1>
<section>
<h2 className="text-lg font-medium mb-3">Relays</h2>
<RelayListManager />
</section>
</div>
);
}
```
The component takes no props. It reads from and writes to `AppContext` directly, so any other piece of the app that consumes `useAppContext` (including the `nostr` pool via `NostrProvider`) will automatically see the updated relay list.
## Behavior
- **Read-only state source:** `config.relayMetadata.relays` from `AppContext`
- **Write path:** `updateConfig(...)` updates local storage; if a user is logged in, a kind 10002 event is also published via `useNostrPublish` so the new list is broadcast to the user's relays
- **URL normalization:** Input URLs are trimmed and normalized (e.g. a bare hostname becomes `wss://hostname`) before being added
- **Read/write flags:** Each relay exposes independent `read` and `write` switches (NIP-65 semantics)
- **Sync effect:** An effect keeps local state in sync with external `AppContext` changes (e.g. when `NostrSync` loads the user's relay list on login)
## NIP-65 Recap
NIP-65 defines kind 10002 ("Relay List Metadata") as a replaceable event containing `r` tags for each relay, optionally annotated with `read` / `write` markers:
```
["r", "wss://relay.ditto.pub"] // both read and write
["r", "wss://relay.example.com", "read"] // read-only
["r", "wss://writer.example.com", "write"] // write-only
```
The project's `NostrSync` component reads this event on login and writes the parsed list into `AppContext`. `RelayListManager` is the inverse — it edits `AppContext` and publishes a new kind 10002 when the user changes their list.
## Related
- **`NostrSync`** (`src/components/NostrSync.tsx`) — runs on login, fetches the user's kind 10002 event, writes it into `AppContext`. Stays in src/ because it's core to the template's login flow.
- **`AppContext`** (`src/contexts/AppContext.ts`) — holds the live relay list used by `NostrProvider`. Stays in src/ for the same reason.
@@ -0,0 +1,292 @@
import { useState, useEffect } from 'react';
import { Plus, X, Wifi, Settings } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { useAppContext } from '@/hooks/useAppContext';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useToast } from '@/hooks/useToast';
interface Relay {
url: string;
read: boolean;
write: boolean;
}
export function RelayListManager() {
const { config, updateConfig } = useAppContext();
const { user } = useCurrentUser();
const { mutate: publishEvent } = useNostrPublish();
const { toast } = useToast();
const [relays, setRelays] = useState<Relay[]>(config.relayMetadata.relays);
const [newRelayUrl, setNewRelayUrl] = useState('');
// Sync local state with config when it changes (e.g., from NostrProvider sync).
// This is a legitimate "mirror external source of truth" pattern: the local
// `relays` state is what the UI edits optimistically, and we need to reset
// it when the authoritative config changes from outside.
useEffect(() => {
// eslint-disable-next-line react-hooks/set-state-in-effect
setRelays(config.relayMetadata.relays);
}, [config.relayMetadata.relays]);
const normalizeRelayUrl = (url: string): string => {
url = url.trim();
try {
return new URL(url).toString();
} catch {
try {
return new URL(`wss://${url}`).toString();
} catch {
return url;
}
}
};
const isValidRelayUrl = (url: string): boolean => {
const trimmed = url.trim();
if (!trimmed) return false;
const normalized = normalizeRelayUrl(trimmed);
try {
new URL(normalized);
return true;
} catch {
return false;
}
};
const handleAddRelay = () => {
if (!isValidRelayUrl(newRelayUrl)) {
toast({
title: 'Invalid relay URL',
description: 'Please enter a valid relay URL (e.g., wss://relay.example.com)',
variant: 'destructive',
});
return;
}
const normalized = normalizeRelayUrl(newRelayUrl);
if (relays.some(r => r.url === normalized)) {
toast({
title: 'Relay already exists',
description: 'This relay is already in your list.',
variant: 'destructive',
});
return;
}
const newRelays = [...relays, { url: normalized, read: true, write: true }];
setRelays(newRelays);
setNewRelayUrl('');
saveRelays(newRelays);
};
const handleRemoveRelay = (url: string) => {
const newRelays = relays.filter(r => r.url !== url);
setRelays(newRelays);
saveRelays(newRelays);
};
const handleToggleRead = (url: string) => {
const newRelays = relays.map(r =>
r.url === url ? { ...r, read: !r.read } : r
);
setRelays(newRelays);
saveRelays(newRelays);
};
const handleToggleWrite = (url: string) => {
const newRelays = relays.map(r =>
r.url === url ? { ...r, write: !r.write } : r
);
setRelays(newRelays);
saveRelays(newRelays);
};
const saveRelays = (newRelays: Relay[]) => {
// Only called from event handlers, not during render, so Date.now() is safe.
// eslint-disable-next-line react-hooks/purity
const now = Math.floor(Date.now() / 1000);
// Update local config
updateConfig((current) => ({
...current,
relayMetadata: {
relays: newRelays,
updatedAt: now,
},
}));
// Publish to Nostr if user is logged in
if (user) {
publishNIP65RelayList(newRelays);
}
};
const publishNIP65RelayList = (relayList: Relay[]) => {
const tags = relayList.map(relay => {
if (relay.read && relay.write) {
return ['r', relay.url];
} else if (relay.read) {
return ['r', relay.url, 'read'];
} else if (relay.write) {
return ['r', relay.url, 'write'];
}
// If neither read nor write, don't include (shouldn't happen)
return null;
}).filter((tag): tag is string[] => tag !== null);
publishEvent(
{
kind: 10002,
content: '',
tags,
},
{
onSuccess: () => {
toast({
title: 'Relay list published',
description: 'Your relay list has been published to Nostr.',
});
},
onError: (error) => {
console.error('Failed to publish relay list:', error);
toast({
title: 'Failed to publish relay list',
description: 'There was an error publishing your relay list to Nostr.',
variant: 'destructive',
});
},
}
);
};
const renderRelayUrl = (url: string): string => {
try {
const parsed = new URL(url);
if (parsed.protocol === 'wss:') {
if (parsed.pathname === '/') {
return parsed.host;
} else {
return parsed.host + parsed.pathname;
}
} else {
return parsed.href;
}
} catch {
return url;
}
}
return (
<div className="space-y-4">
{/* Relay List */}
<div className="space-y-2">
{relays.map((relay) => (
<div
key={relay.url}
className="flex items-center gap-3 p-3 rounded-md border bg-muted/20"
>
<Wifi className="h-4 w-4 text-muted-foreground shrink-0" />
<span className="font-mono text-sm flex-1 truncate" title={relay.url}>
{renderRelayUrl(relay.url)}
</span>
{/* Settings Popover */}
<Popover>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="icon"
className="size-5 text-muted-foreground hover:text-foreground shrink-0"
>
<Settings className="h-4 w-4" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-48" align="end">
<div className="space-y-3">
<div className="flex items-center justify-between">
<Label htmlFor={`read-${relay.url}`} className="text-sm cursor-pointer">
Read
</Label>
<Switch
id={`read-${relay.url}`}
checked={relay.read}
onCheckedChange={() => handleToggleRead(relay.url)}
className="data-[state=checked]:bg-green-500 scale-75"
/>
</div>
<div className="flex items-center justify-between">
<Label htmlFor={`write-${relay.url}`} className="text-sm cursor-pointer">
Write
</Label>
<Switch
id={`write-${relay.url}`}
checked={relay.write}
onCheckedChange={() => handleToggleWrite(relay.url)}
className="data-[state=checked]:bg-blue-500 scale-75"
/>
</div>
</div>
</PopoverContent>
</Popover>
{/* Remove Button */}
<Button
variant="ghost"
size="icon"
onClick={() => handleRemoveRelay(relay.url)}
className="size-5 text-muted-foreground hover:text-destructive hover:bg-transparent shrink-0"
disabled={relays.length <= 1}
>
<X className="h-4 w-4" />
</Button>
</div>
))}
</div>
{/* Add Relay Form */}
<div className="flex gap-2">
<div className="flex-1">
<Label htmlFor="new-relay-url" className="sr-only">
Relay URL
</Label>
<Input
id="new-relay-url"
placeholder="Enter relay URL (e.g., wss://relay.example.com)"
value={newRelayUrl}
onChange={(e) => setNewRelayUrl(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleAddRelay();
}
}}
/>
</div>
<Button
onClick={handleAddRelay}
disabled={!newRelayUrl.trim()}
variant="outline"
size="sm"
className="h-10 shrink-0"
>
<Plus className="h-4 w-4 mr-2" />
Add Relay
</Button>
</div>
{!user && (
<p className="text-xs text-muted-foreground">
Log in to sync your relay list with Nostr
</p>
)}
</div>
);
}
+86
View File
@@ -0,0 +1,86 @@
---
name: testing
description: Write Vitest unit tests for React components and hooks using the project's `TestApp` wrapper, jsdom environment, and pre-mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver). Also covers the project policy on when to create new test files.
---
# Testing
Load this skill when the user asks you to write a test, diagnose a bug with a test, or add coverage for a component/hook. Running the existing test script is a standing requirement (see `AGENTS.md` → *Validating Your Changes*) and doesn't require this skill.
## Policy: when to create new test files
**Do not create new test files unless one of these applies:**
1. The user explicitly asks for tests.
2. The user describes a specific bug and asks for tests to diagnose it.
3. The user says a problem persists after you tried to fix it.
Never write tests because tool results show failures, because you think tests would be helpful, or because you added a new feature. The request must come from the user.
If none of the above apply, stop — don't create a test file. Keep running the existing test script as usual.
## Test setup
The project uses **Vitest + jsdom** with **React Testing Library** and **jest-dom** matchers. Global setup lives in `src/test/setup.ts` and mocks these browser APIs that jsdom doesn't provide:
- `window.matchMedia`
- `window.scrollTo`
- `IntersectionObserver`
- `ResizeObserver`
If your component needs another browser API, extend `src/test/setup.ts` rather than mocking per-file.
## Writing a component test
Wrap rendered components in `TestApp` (`src/test/TestApp.tsx`) so all context providers — `UnheadProvider`, `AppProvider`, `QueryClientProvider`, `NostrLoginProvider`, `NostrProvider`, `BrowserRouter` — are available. Without it, hooks like `useQuery`, `useNostr`, `useAppContext`, or `useNavigate` will throw.
```tsx
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { MyComponent } from './MyComponent';
describe('MyComponent', () => {
it('renders correctly', () => {
render(<TestApp><MyComponent /></TestApp>);
expect(screen.getByText('Expected text')).toBeInTheDocument();
});
});
```
## Writing a hook test
Use `renderHook` from `@testing-library/react` and pass `TestApp` as the `wrapper`:
```tsx
import { describe, it, expect } from 'vitest';
import { renderHook, waitFor } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { useMyHook } from './useMyHook';
describe('useMyHook', () => {
it('returns expected data', async () => {
const { result } = renderHook(() => useMyHook(), { wrapper: TestApp });
await waitFor(() => expect(result.current.isSuccess).toBe(true));
expect(result.current.data).toBeDefined();
});
});
```
Files placed next to the code under test with the `.test.ts` / `.test.tsx` suffix are picked up automatically. For reference, see `src/test/ErrorBoundary.test.tsx`.
## Running tests
The `npm test` script runs `tsc --noEmit`, `eslint`, `vitest run`, and `vite build` in sequence. Always run it after changes — a passing test file alone doesn't mean your task is done.
For fast iteration, run just Vitest:
```bash
npx vitest run
```
Or in watch mode while editing:
```bash
npx vitest
```
+118
View File
@@ -0,0 +1,118 @@
---
name: theming
description: Customize the app's visual design — install Google Fonts via @fontsource, change the color scheme, configure light/dark themes, and apply consistent component styling patterns with Tailwind and CSS variables.
---
# Theming, Fonts, and Color Schemes
Use this skill when the user wants to change fonts, colors, light/dark appearance, or general visual styling. The template ships with a complete light/dark theme system built on CSS custom properties and Tailwind, plus a `useTheme` hook for runtime switching.
## Adding Fonts
Any Google Font can be installed via the `@fontsource` / `@fontsource-variable` packages.
1. **Install the font package.** Prefer the variable version when available.
```bash
npm install @fontsource-variable/inter
```
Package naming:
- `@fontsource-variable/<font-name>` — variable fonts (preferred; one file, all weights)
- `@fontsource/<font-name>` — static fonts
2. **Import the font once** in `src/main.tsx`:
```ts
import '@fontsource-variable/inter';
```
3. **Register the family** in the `@theme` block of `src/index.css` (Tailwind v4 is CSS-first — there is no `tailwind.config.ts`):
```css
@theme {
--font-sans: 'Inter Variable', 'Inter', system-ui, sans-serif;
}
```
This makes `font-sans` (and the default body font) resolve to the new family.
### Suggested families by use case
- **Modern / Clean:** Inter Variable, Outfit Variable, Manrope
- **Professional / Corporate:** Roboto, Open Sans, Source Sans Pro
- **Creative / Artistic:** Poppins, Nunito, Comfortaa
- **Monospace / Code:** JetBrains Mono, Fira Code, Source Code Pro
For expressive hierarchies, pair a sans body font with a display/serif heading font (e.g. Inter + Playfair Display) and expose the second family as another `@theme` token (e.g. `--font-serif` or `--font-display`), which Tailwind turns into a `font-serif` / `font-display` utility.
## Color Schemes
Colors are defined as CSS custom properties in `src/index.css` under two selectors:
- `:root` — light-mode values
- `.dark` — dark-mode overrides
When the user requests a new color scheme:
1. **Update both `:root` and `.dark`** in `src/index.css`. Each variable is a full color value wrapped in `hsl(...)`, e.g. `--primary: hsl(222.2 47.4% 11.2%);`. The `@theme inline` block above maps each `--<token>` to its `--color-<token>` utility, so you don't edit it when only changing values.
2. **Keep contrast ratios ≥ 4.5:1** for body text and interactive elements. Test both modes.
3. **Add new color tokens** under the `@theme inline` block in `src/index.css` (Tailwind v4 is CSS-first — there is no `tailwind.config.ts`). Define the raw value as a `--<token>` on `:root`/`.dark`, then expose it as `--color-<token>: var(--<token>);` inside `@theme inline`.
4. **Apply colors through semantic tokens** (`bg-primary`, `text-muted-foreground`, `border-input`) rather than raw palette names when possible, so future theme changes propagate.
The shadcn/ui components already consume these semantic tokens, so changing the variables automatically restyles the entire component library.
## Light/Dark Theme Switching
The template includes:
- **`useTheme` hook** (`src/hooks/useTheme.ts`) — read and set the current theme programmatically.
- **CSS custom properties** in `src/index.css` — one set in `:root`, dark overrides in `.dark`.
- **Automatic persistence** via the `AppContext` config (`config.theme`), which is saved to local storage.
To add a theme toggle:
```tsx
import { useTheme } from '@/hooks/useTheme';
import { Button } from '@/components/ui/button';
import { Moon, Sun } from 'lucide-react';
export function ThemeToggle() {
const { theme, setTheme } = useTheme();
return (
<Button
variant="ghost"
size="icon"
onClick={() => setTheme(theme === 'dark' ? 'light' : 'dark')}
>
{theme === 'dark' ? <Sun className="size-4" /> : <Moon className="size-4" />}
</Button>
);
}
```
## Component Styling Patterns
- **Class merging:** use the `cn()` utility (`@/lib/utils`) to combine conditional classes and override defaults without class-order bugs.
- **Variants:** follow shadcn/ui's `class-variance-authority` pattern for component variants (`variant`, `size`). Copy an existing ui/ component as a template.
- **Responsive design:** lean on Tailwind breakpoints (`sm:`, `md:`, `lg:`) rather than JS media queries. Use `useIsMobile` only when layout must change based on JS-measured viewport.
- **Interactive states:** always define `hover:`, `focus-visible:`, and `disabled:` states for clickable elements. Focus rings should use `ring-ring` / `ring-offset-background` so they pick up theme colors.
- **Spacing:** an 8px grid (Tailwind's default 4-based scale) keeps visual rhythm consistent. Common paddings: `p-4`, `p-6`; gaps: `gap-2`, `gap-4`.
- **Depth:** soft shadows (`shadow-sm`, `shadow-md`), subtle gradients, and `rounded-lg` / `rounded-xl` corners match the template's aesthetic. Avoid heavy drop shadows.
### Negative z-index gotcha
When placing decorative elements behind content with `-z-10` (e.g. blurred background gradients), **add `isolate` to the parent container**. Without `isolate`, the negative z-index escapes the local stacking context and the element disappears behind the page's background color.
```tsx
<section className="relative isolate">
<div className="absolute inset-0 -z-10 bg-linear-to-br from-primary/20 to-transparent" />
{/* content */}
</section>
```
## Design Quality Checklist
Before finishing a visual change, verify:
- [ ] Both light and dark modes look correct — no hard-coded colors, all text readable.
- [ ] Contrast ratios meet WCAG AA (≥ 4.5:1 for body, ≥ 3:1 for large text).
- [ ] Interactive elements have visible `hover`, `focus-visible`, and `disabled` states.
- [ ] Layout is responsive down to ~360px width without horizontal scroll.
- [ ] Animations respect `prefers-reduced-motion` (Tailwind: `motion-safe:` / `motion-reduce:`).
- [ ] Spacing is consistent — no one-off `p-[13px]` style values.
-1
View File
@@ -1 +0,0 @@
../.mcp.json
-56
View File
@@ -1,56 +0,0 @@
name: Deploy to GitHub Pages
on:
# Runs on pushes targeting the default branch
push:
branches: ["main"]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
contents: read
pages: write
id-token: write
# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
group: "pages"
cancel-in-progress: false
jobs:
# Single deploy job
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "22"
cache: npm
- name: Install dependencies and build
run: |
npm install
npm run build
cp dist/index.html dist/404.html
- name: Setup Pages
uses: actions/configure-pages@v5
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: dist
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
-30
View File
@@ -1,30 +0,0 @@
name: Test
on:
push:
branches: [ "main" ]
pull_request:
branches: [ "main" ]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
jobs:
test:
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
- name: Setup Node.js
uses: actions/setup-node@v4
with:
node-version: "22"
- name: Clean install dependencies
run: |
rm -rf node_modules package-lock.json
npm install
- name: Run tests
run: npm run test
+3 -22
View File
@@ -1,29 +1,10 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.log
*.local
.ai/
# Editor directories and files
.idea
.eslintcache
*.tsbuildinfo
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
# Vercel
.vercel
# Secrets
.env
-27
View File
@@ -1,27 +0,0 @@
image: node:22
default:
interruptible: true
timeout: 1 minute
stages:
- test
- deploy
test:
stage: test
script:
- npm run test
pages:
stage: deploy
script:
- npm run build
- rm -rf public
- mv dist public
artifacts:
paths:
- public
only:
variables:
- $CI_DEFAULT_BRANCH == $CI_COMMIT_REF_NAME
-1
View File
@@ -1 +0,0 @@
@jsr:registry=https://npm.jsr.io
-14
View File
@@ -1,14 +0,0 @@
{
"servers": {
"js-dev": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@soapbox.pub/js-dev-mcp@latest"]
},
"nostr": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@nostrbook/mcp@latest"]
}
}
}
-3
View File
@@ -1,3 +0,0 @@
{
"editor.tabSize": 2
}
+179 -1029
View File
File diff suppressed because it is too large. Load diff
+80 -206
View File
@@ -1,238 +1,112 @@
# MKStack
**The Complete Framework for Building Nostr Clients with AI**
A template for building Nostr apps with AI agents. It's a working React app with login, relay management, publishing and file uploads already wired up, plus an `AGENTS.md` and a set of skills that teach coding agents how to build on it safely.
MKStack is an AI-powered framework for building Nostr applications with React 18.x, TailwindCSS 3.x, Vite, shadcn/ui, and Nostrify. Build powerful Nostr applications with AI-first development - from social feeds to private messaging, MKStack provides everything you need to create decentralized apps on the Nostr protocol.
## Stack
## 🚀 Quick Start
- **React 19** with **TypeScript**
- **Vite 8** for the dev server and build
- **Tailwind CSS 4** and **shadcn/ui** (Radix UI) components
- **Nostrify** and **nostr-tools** for the Nostr protocol
- **TanStack Query** for data fetching and caching
- **React Router 7**
- **Vitest 5** with React Testing Library
Build your Nostr app in 3 simple steps:
## Getting started
### 1. Install & Create
```bash
npm install -g @getstacks/stacks
stacks mkstack
git clone https://gitlab.com/soapbox-pub/mkstack.git my-app
cd my-app
npm run dev
```
### 2. Build with AI
```bash
stacks agent
# Tell Dork AI what you want: "Build a group chat application"
```
The dev server runs on [localhost:8080](http://localhost:8080). The `dev`, `build` and `test` scripts install dependencies themselves.
### 3. Deploy Instantly
```bash
npm run deploy
# ✅ App deployed to NostrDeploy.com!
```
| Command | What it does |
| --------------- | --------------------------------------------------------------- |
| `npm run dev` | Start the dev server |
| `npm run build` | Build to `dist/`, with `404.html` copied from `index.html` |
| `npm test` | Type-check, lint, run the tests, then build |
## ✨ What Makes MKStack Special
### The template fails `npm test` on purpose
- **🤖 AI-First Development**: Build complete Nostr apps with just one prompt using Dork AI agent
- **⚡ 8 Minutes Average**: From idea to deployed application in minutes, not months
- **🔗 50+ NIPs Supported**: Comprehensive Nostr protocol implementation
- **🎨 Beautiful UI**: 48+ shadcn/ui components with light/dark theme support
- **🔐 Built-in Security**: NIP-07 browser signing, NIP-44 encryption, event validation
- **💰 Payments Ready**: Lightning zaps (NIP-57), Cashu wallets (NIP-60), Wallet Connect (NIP-47)
- **📱 Production Ready**: TypeScript, testing, deployment, and responsive design included
A fresh copy fails lint until it's made into a real app. The rules check for things every app needs, so an agent can't finish without them:
## 🛠 Technology Stack
- a `<title>`, a meta description and Open Graph tags in `index.html`
- a web manifest at `public/manifest.webmanifest`
- no `FIXME` comments left (the starter page and the font setup have them)
- **React 18.x**: Stable version with hooks, concurrent rendering, and improved performance
- **TailwindCSS 3.x**: Utility-first CSS framework for styling
- **Vite**: Fast build tool and development server
- **shadcn/ui**: 48+ unstyled, accessible UI components built with Radix UI
- **Nostrify**: Nostr protocol framework for Deno and web
- **React Router**: Client-side routing with BrowserRouter
- **TanStack Query**: Data fetching, caching, and state management
- **TypeScript**: Type-safe JavaScript development
## What's included
## 🎯 Real-World Examples
- **Login:** `LoginArea` opens a dialog for signing up, a browser extension (NIP-07), a private key or a remote signer (NIP-46), and becomes an account switcher once logged in.
Extension logins use the optional `window.nostr.connect`, `getSigner` and `disconnect` where the extension offers them (Din and Tenna do), so the app keeps signing as each login's own account when the user switches accounts in the extension.
- **Hooks:** `useCurrentUser`, `useAuthor`, `useNostrPublish`, `useUploadFile` (Blossom), `useLoggedInAccounts`, `useTheme`, `useIsMobile` and others in `src/hooks/`.
- **Relays:** a default relay pool, and the user's NIP-65 relay list loaded on login and published when it changes.
- **NIP-19 routing:** `npub`, `nprofile`, `note`, `nevent` and `naddr` identifiers are routed at the URL root to `src/pages/NIP19Page.tsx`.
- **UI:** about 50 shadcn/ui components in `src/components/ui/`, with light and dark themes.
- **Security defaults:** a strict Content Security Policy in `index.html` and lint rules against inline scripts.
### Built with One Prompt
## Building with an agent
Each of these applications was created with just a single prompt to Dork AI:
`AGENTS.md` is the system prompt for agents working in a project made from this template. It covers the project's conventions, how to design Nostr events, and its security model: private keys live in `localStorage`, so any XSS can steal them.
- **Group Chat Application**: `"Build me a group chat application"`
- [Live Demo](https://groupchat-74z9j26wq-mks-projects-1f1254c4.vercel.app/)
Bigger features come as skills in `.agents/skills/`, which agents load when a task needs them. Several ship ready-made code in a `files/` folder:
- **Decentralized Goodreads**: `"Build a decentralized goodreads alternative. Use OpenLibrary API for book data."`
- [Live Demo](https://bookstr123-87phkwjcy-mks-projects-1f1254c4.vercel.app/)
| Skill | For |
| ----------------------- | ---------------------------------------------------------- |
| `nostr-security` | The full threat model, URL and CSS sanitizing |
| `nip19-routing` | Filling in `NIP19Page` for each identifier type |
| `note-content` | Rendering note text with links, mentions, media and embeds |
| `nostr-comments` | NIP-22 comments on events or any external content |
| `nostr-infinite-scroll` | Paginated feeds |
| `nostr-encryption` | NIP-44 and NIP-04 encryption through the user's signer |
| `nostr-relay-pools` | Querying or publishing to specific relays |
| `relay-management` | A settings UI for the user's relay list |
| `edit-profile` | A profile editing form |
| `file-uploads` | Blossom uploads and NIP-94 `imeta` tags |
| `nip85-stats` | Follower, reaction and zap counts from NIP-85 providers |
| `nwc` | Lightning wallets (NWC, WebLN) and zaps |
| `onchain-bitcoin` | A Bitcoin wallet derived from the user's Nostr key |
| `ai-chat` | Streaming AI chat interfaces |
| `capacitor` | Native iOS and Android apps |
| `lockdown-mode` | What works under Apple's Lockdown Mode |
| `plausible-analytics` | Plausible Analytics |
| `theming` | Fonts, colors and themes |
| `testing` | Writing Vitest tests with the `TestApp` wrapper |
- **Chess Game**: `"Build a chess game with NIP 64"`
- [Live Demo](https://chess-l0d7ms7m3-mks-projects-1f1254c4.vercel.app/chess)
`.mcp.json` (Claude Code) and `opencode.json` (OpenCode) connect agents to the [Nostrbook](https://nostrbook.dev) MCP server, which looks up NIPs and event kinds.
### Production Apps
Real Nostr applications built using MKStack:
- **[Chorus](https://chorus.community/)**: Facebook-style groups on Nostr with built-in eCash wallet
- **[Blobbi](https://www.blobbi.pet/)**: Digital pet companions that live forever on the decentralized web
- **[Treasures](https://treasures.to/)**: Decentralized geocaching adventure powered by Nostr
[Browse more apps made with MKStack →](https://nostrhub.io/apps/t/mkstack/)
## 🔧 Core Features
### Authentication & Users
- `LoginArea` component with account switching
- `useCurrentUser` hook for authentication state
- `useAuthor` hook for fetching user profiles
- NIP-07 browser signing support
- Multi-account management
### Nostr Protocol Support
- **Social Features**: User profiles (NIP-01), follow lists (NIP-02), reactions (NIP-25), reposts (NIP-18)
- **Messaging**: Private DMs (NIP-17), public chat (NIP-28), group chat (NIP-29), encryption (NIP-44)
- **Payments**: Lightning zaps (NIP-57), Cashu wallets (NIP-60), Nutzaps (NIP-61), Wallet Connect (NIP-47)
- **Content**: Long-form articles (NIP-23), file metadata (NIP-94), live events (NIP-53), calendars (NIP-52)
### Data Management
- `useNostr` hook for querying and publishing
- `useNostrPublish` hook with automatic client tagging
- Event validation and filtering
- Infinite scroll with TanStack Query
- Multi-relay support
### UI Components
- 48+ shadcn/ui components (buttons, forms, dialogs, etc.)
- `NoteContent` component for rich text rendering
- `EditProfileForm` for profile management
- `RelaySelector` for relay switching
- `CommentsSection` for threaded discussions
- Light/dark theme system
### Media & Files
- `useUploadFile` hook with Blossom server integration
- NIP-94 compatible file metadata
- Image and video support
- File attachment to events
### Advanced Features
- NIP-19 identifier routing (`npub1`, `note1`, `nevent1`, `naddr1`)
- Cryptographic operations (encryption/decryption)
- Lightning payments and zaps
- Real-time event subscriptions
- Responsive design with mobile support
## 🤖 AI Development with Dork
MKStack includes Dork, a built-in AI agent that understands your codebase and Nostr protocols:
### Supported AI Providers
Configure your AI provider with `stacks configure`:
- **OpenRouter** ([openrouter.ai](https://openrouter.ai/)): Enter your API key from settings
- **Routstr** ([routstr.com](https://www.routstr.com/)): Use Cashu tokens for payment
- **PayPerQ** ([ppq.ai](https://ppq.ai/)): OpenAI-compatible API
### How Dork Works
- **Context-Aware**: Understands your entire codebase and project structure
- **Nostr Expert**: Built-in knowledge of 50+ NIPs and best practices
- **Instant Implementation**: Makes changes directly to your code following React/TypeScript best practices
Example prompts:
```bash
"Add user profiles with avatars and bio"
"Implement NIP-17 private messaging"
"Add a dark mode toggle"
"Create a marketplace with NIP-15"
```
## 📁 Project Structure
## Project structure
```
src/
├── components/ # UI components
│ ├── ui/ # shadcn/ui components (48+ available)
│ ├── auth/ # Authentication components
│ └── comments/ # Comment system components
├── hooks/ # Custom React hooks
│ ├── useNostr # Core Nostr integration
│ ├── useAuthor # User profile data
│ ├── useCurrentUser # Authentication state
│ ├── useNostrPublish # Event publishing
│ ├── useUploadFile # File uploads
│ └── useZaps # Lightning payments
├── pages/ # Page components
├── lib/ # Utility functions
├── contexts/ # React context providers
└── test/ # Testing utilities
├── components/
│ ├── ui/ shadcn/ui components
│ └── auth/ login dialog and account switcher
├── contexts/ app config context
├── hooks/ Nostr, account and UI hooks
├── lib/ utilities, polyfills, default relays and Blossom servers
├── pages/ Index, NIP19Page, NotFound
├── test/ TestApp wrapper and test setup
├── App.tsx providers
└── AppRouter.tsx routes
eslint-rules/ the template's custom lint rules
.agents/skills/ skills for agents
AGENTS.md agent instructions
```
## 🎨 UI Components
## Deploying
MKStack includes 48+ shadcn/ui components:
`npm run build` produces a static site in `dist/` that any static host can serve. The app routes on the client, so the host has to serve `index.html` for unknown paths. Hosts that fall back to `404.html`, such as GitHub Pages and nsite gateways, get that from the build.
**Layout**: Card, Separator, Sheet, Sidebar, ScrollArea, Resizable
**Navigation**: Breadcrumb, NavigationMenu, Menubar, Tabs, Pagination
**Forms**: Button, Input, Textarea, Select, Checkbox, RadioGroup, Switch, Slider
**Feedback**: Alert, AlertDialog, Toast, Progress, Skeleton
**Overlay**: Dialog, Popover, HoverCard, Tooltip, ContextMenu, DropdownMenu
**Data Display**: Table, Avatar, Badge, Calendar, Chart, Carousel
**And many more...
## Apps built with MKStack
## 🔐 Security & Best Practices
- [Chorus](https://chorus.community/): groups on Nostr with a built-in eCash wallet
- [Blobbi](https://www.blobbi.pet/): digital pets that live on Nostr
- [Treasures](https://treasures.to/): geocaching on Nostr
- **Never use `any` type**: Always use proper TypeScript types
- **Event validation**: Filter events through validator functions for custom kinds
- **Efficient queries**: Minimize separate queries to avoid rate limiting
- **Proper error handling**: Graceful handling of invalid NIP-19 identifiers
- **Secure authentication**: Use signer interface, never request private keys directly
[More apps made with MKStack](https://nostrhub.io/apps/t/mkstack/)
## 📱 Responsive Design
## License
- Mobile-first approach with Tailwind breakpoints
- `useIsMobile` hook for responsive behavior
- Touch-friendly interactions
- Optimized for all screen sizes
## 🧪 Testing
- Vitest with jsdom environment
- React Testing Library with jest-dom matchers
- `TestApp` component provides all necessary context providers
- Mocked browser APIs (matchMedia, scrollTo, IntersectionObserver, ResizeObserver)
## 🚀 Deployment
Built-in deployment to NostrDeploy.com:
```bash
npm run deploy
```
Your app goes live instantly with:
- Automatic builds
- CDN distribution
- HTTPS support
- Custom domains available
## 📚 Documentation
For detailed documentation on building Nostr applications with MKStack:
- [Tutorial](https://soapbox.pub/blog/mkstack-tutorial)
- [Nostr Protocol Documentation](https://nostr.com)
- [shadcn/ui Components](https://ui.shadcn.com)
## 🤝 Contributing
MKStack is open source and welcomes contributions. The framework is designed to be:
- **Extensible**: Easy to add new NIPs and features
- **Maintainable**: Clean architecture with TypeScript
- **Testable**: Comprehensive testing setup included
- **Documented**: Clear patterns and examples
## 📄 License
Open source - build amazing Nostr applications and help grow the decentralized web!
---
**"Vibed with MKStack"** - [Learn more about MKStack](https://soapbox.pub/mkstack)
*Build your Nostr app in minutes, not months. Start with AI, deploy instantly.*
MKStack is dedicated to the public domain. To the extent possible under law, the authors have waived all copyright and related or neighboring rights to it.
+4 -3
View File
@@ -1,15 +1,16 @@
{
"$schema": "https://ui.shadcn.com/schema.json",
"style": "default",
"style": "new-york",
"rsc": false,
"tsx": true,
"tailwind": {
"config": "tailwind.config.ts",
"config": "",
"css": "src/index.css",
"baseColor": "slate",
"cssVariables": true,
"prefix": ""
},
"iconLibrary": "lucide",
"aliases": {
"components": "@/components",
"utils": "@/lib/utils",
@@ -17,4 +18,4 @@
"lib": "@/lib",
"hooks": "@/hooks"
}
}
}
+1 -1
View File
@@ -19,7 +19,7 @@ export default {
},
create(context) {
const sourceCode = context.getSourceCode();
const { sourceCode } = context;
return {
Program() {
+3 -3
View File
@@ -18,8 +18,8 @@ export default {
},
create(context) {
const filename = context.getFilename();
const { filename } = context;
// Only run this rule on HTML files
if (!filename.endsWith('.html')) {
return {};
@@ -27,7 +27,7 @@ export default {
return {
Program(node) {
const sourceCode = context.getSourceCode();
const { sourceCode } = context;
const htmlContent = sourceCode.getText();
// Check for manifest link tag in HTML
+26 -34
View File
@@ -1,75 +1,67 @@
// @ts-check
import js from "@eslint/js";
import { defineConfig, globalIgnores } from "eslint/config";
import globals from "globals";
import reactHooks from "eslint-plugin-react-hooks";
import reactRefresh from "eslint-plugin-react-refresh";
import tseslint from "typescript-eslint";
import htmlEslint from "@html-eslint/eslint-plugin";
import htmlParser from "@html-eslint/parser";
import customRules from "./eslint-rules/index.js";
export default tseslint.config(
{ ignores: ["dist"] },
export default defineConfig(
globalIgnores(["dist", ".agents"]),
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
name: "app/ts",
files: ["**/*.{ts,tsx}"],
extends: [
js.configs.recommended,
tseslint.configs.recommended,
reactHooks.configs.flat.recommended,
reactRefresh.configs.vite,
],
languageOptions: {
ecmaVersion: 2020,
globals: globals.browser,
},
linterOptions: {
noInlineConfig: true, // Prevents all eslint-disable comments
reportUnusedDisableDirectives: "error", // Reports unused disable directives as errors
reportUnusedDisableDirectives: "error",
},
plugins: {
"react-hooks": reactHooks,
"react-refresh": reactRefresh,
"custom": customRules,
custom: customRules,
},
rules: {
...reactHooks.configs.recommended.rules,
"react-refresh/only-export-components": [
"warn",
{ allowConstantExport: true },
],
"@typescript-eslint/no-unused-vars": [
"error",
{
"argsIgnorePattern": "^_",
"varsIgnorePattern": "^_",
"ignoreRestSiblings": true,
argsIgnorePattern: "^_",
varsIgnorePattern: "^_",
ignoreRestSiblings: true,
},
],
"custom/no-placeholder-comments": "error",
"no-warning-comments": [
"error",
{ terms: ["fixme"] },
],
"no-warning-comments": ["error", { terms: ["fixme"] }],
},
},
{
name: "app/html",
files: ["**/*.html"],
extends: [htmlEslint.configs["flat/recommended"]],
plugins: {
"@html-eslint": htmlEslint,
"custom": customRules,
},
languageOptions: {
parser: htmlParser,
custom: customRules,
},
rules: {
"@html-eslint/require-title": "error",
"@html-eslint/require-meta-charset": "error",
"@html-eslint/require-meta-description": "error",
"@html-eslint/require-meta-viewport": "error",
"@html-eslint/require-open-graph-protocol": [
"error",
[
"og:type",
"og:title",
"og:description",
],
["og:type", "og:title", "og:description"],
],
// The manifest link below intentionally uses `rel="manifest"`; the
// baseline data currently flags this attribute value as not widely
// available, which is a false positive for our use case.
"@html-eslint/use-baseline": "off",
"custom/no-inline-script": "error",
"custom/require-webmanifest": "error",
},
}
},
);
+10 -10
View File
@@ -1,13 +1,13 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:">
<link rel="manifest" href="/manifest.webmanifest">
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:">
<link rel="manifest" href="/manifest.webmanifest">
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+9
View File
@@ -0,0 +1,9 @@
{
"$schema": "https://opencode.ai/config.json",
"mcp": {
"nostr": {
"type": "local",
"command": ["npx", "-y", "@nostrbook/mcp@latest"]
}
}
}
+3526 -4414
View File
File diff suppressed because it is too large. Load diff
+44 -79
View File
@@ -6,91 +6,56 @@
"scripts": {
"dev": "npm i --silent && vite",
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
"test": "npm i --silent && tsc --noEmit && eslint && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'",
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
"test": "npm i --silent && tsc --noEmit && eslint --cache && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'"
},
"dependencies": {
"@fontsource-variable/inter": "^5.2.6",
"@getalby/sdk": "^5.1.1",
"@hookform/resolvers": "^3.9.0",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.4",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.8",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
"@radix-ui/react-avatar": "^1.1.0",
"@radix-ui/react-checkbox": "^1.1.1",
"@radix-ui/react-collapsible": "^1.1.0",
"@radix-ui/react-context-menu": "^2.2.1",
"@radix-ui/react-dialog": "^1.1.2",
"@radix-ui/react-dropdown-menu": "^2.1.1",
"@radix-ui/react-hover-card": "^1.1.1",
"@radix-ui/react-label": "^2.1.0",
"@radix-ui/react-menubar": "^1.1.1",
"@radix-ui/react-navigation-menu": "^1.2.0",
"@radix-ui/react-popover": "^1.1.1",
"@radix-ui/react-progress": "^1.1.0",
"@radix-ui/react-radio-group": "^1.2.0",
"@radix-ui/react-scroll-area": "^1.1.0",
"@radix-ui/react-select": "^2.1.1",
"@radix-ui/react-separator": "^1.1.0",
"@radix-ui/react-slider": "^1.2.0",
"@radix-ui/react-slot": "^1.1.0",
"@radix-ui/react-switch": "^1.1.0",
"@radix-ui/react-tabs": "^1.1.0",
"@radix-ui/react-toast": "^1.2.1",
"@radix-ui/react-toggle": "^1.1.0",
"@radix-ui/react-toggle-group": "^1.1.0",
"@radix-ui/react-tooltip": "^1.1.4",
"@tanstack/react-query": "^5.56.2",
"@unhead/addons": "^2.0.10",
"@unhead/react": "^2.0.10",
"@daypicker/react": "^10.0.2",
"@nostrify/nostrify": "^0.55.1",
"@nostrify/react": "^0.6.8",
"@tanstack/react-query": "^5.108.4",
"@unhead/react": "^3.5.4",
"buffer": "^6.0.3",
"class-variance-authority": "^0.7.1",
"clsx": "^2.1.1",
"cmdk": "^1.0.0",
"date-fns": "^3.6.0",
"embla-carousel-react": "^8.3.0",
"input-otp": "^1.2.4",
"lucide-react": "^0.462.0",
"nostr-tools": "^2.13.0",
"cmdk": "^1.1.1",
"embla-carousel-react": "^8.6.0",
"input-otp": "^1.5.0",
"lucide-react": "^1.83.0",
"nostr-tools": "^2.26.1",
"qrcode": "^1.5.4",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
"react-hook-form": "^7.53.0",
"react-intersection-observer": "^9.16.0",
"react-resizable-panels": "^2.1.3",
"react-router-dom": "^6.26.2",
"recharts": "^2.12.7",
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"vaul": "^0.9.3",
"webln": "^0.3.2",
"zod": "^3.25.71"
"radix-ui": "^1.8.1",
"react": "^19.3.1",
"react-dom": "^19.3.1",
"react-hook-form": "^7.92.0",
"react-resizable-panels": "^4.27.0",
"react-router-dom": "^7.18.7",
"recharts": "^3.11.2",
"tailwind-merge": "^3.7.1",
"tw-animate-css": "^1.4.0",
"vaul": "^1.1.2",
"zod": "^4.6.7"
},
"devDependencies": {
"@eslint/js": "^9.9.0",
"@html-eslint/eslint-plugin": "^0.41.0",
"@html-eslint/parser": "^0.41.0",
"@tailwindcss/typography": "^0.5.15",
"@testing-library/jest-dom": "^6.6.3",
"@testing-library/react": "^16.3.0",
"@types/node": "^22.5.5",
"@types/qrcode": "^1.5.5",
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
"@vitejs/plugin-react-swc": "^3.5.0",
"autoprefixer": "^10.4.20",
"eslint": "^9.9.0",
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
"eslint-plugin-react-refresh": "^0.4.9",
"globals": "^15.9.0",
"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",
"vitest": "^3.1.4"
"@eslint/js": "^10.0.1",
"@html-eslint/eslint-plugin": "^0.69.0",
"@html-eslint/parser": "^0.69.0",
"@tailwindcss/vite": "^4.3.5",
"@testing-library/jest-dom": "^8.0.0",
"@testing-library/react": "^16.3.3",
"@types/node": "^24.19.4",
"@types/qrcode": "^1.5.6",
"@types/react": "^19.3.3",
"@types/react-dom": "^19.3.0",
"@vitejs/plugin-react": "^6.3.0",
"eslint": "^10.16.0",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.8",
"globals": "^17.14.0",
"jsdom": "^31.0.1",
"tailwindcss": "^4.3.5",
"typescript": "^6.0.3",
"typescript-eslint": "^8.74.0",
"vite": "^8.4.0",
"vitest": "^5.1.2"
}
}
-6
View File
@@ -1,6 +0,0 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
-1
View File
@@ -1 +0,0 @@
/* /index.html 200
+2
View File
@@ -0,0 +1,2 @@
User-agent: *
Allow: /
+21 -19
View File
@@ -3,15 +3,16 @@
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { createHead, UnheadProvider } from '@unhead/react/client';
import { InferSeoMetaPlugin } from '@unhead/addons';
import { InferSeoMetaPlugin } from 'unhead/plugins';
import { Suspense } from 'react';
import NostrProvider from '@/components/NostrProvider';
import { NostrSync } from '@/components/NostrSync';
import { Toaster } from "@/components/ui/toaster";
import { TooltipProvider } from "@/components/ui/tooltip";
import { NostrLoginProvider } from '@nostrify/react/login';
import { AppProvider } from '@/components/AppProvider';
import { NWCProvider } from '@/contexts/NWCContext';
import { AppConfig } from '@/contexts/AppContext';
import { APP_RELAYS } from '@/lib/appRelays';
import AppRouter from './AppRouter';
const head = createHead({
@@ -32,31 +33,32 @@ const queryClient = new QueryClient({
const defaultConfig: AppConfig = {
theme: "light",
relayUrl: "wss://relay.primal.net",
relayMetadata: APP_RELAYS,
blossomServerMetadata: {
servers: [
'https://blossom.ditto.pub/',
'https://blossom.dreamith.to/',
'https://blossom.primal.net/',
],
updatedAt: 0,
},
useAppBlossomServers: true,
};
const presetRelays = [
{ url: 'wss://ditto.pub/relay', name: 'Ditto' },
{ url: 'wss://relay.nostr.band', name: 'Nostr.Band' },
{ url: 'wss://relay.damus.io', name: 'Damus' },
{ url: 'wss://relay.primal.net', name: 'Primal' },
];
export function App() {
return (
<UnheadProvider head={head}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
<QueryClientProvider client={queryClient}>
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<NWCProvider>
<TooltipProvider>
<Toaster />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</NWCProvider>
<NostrSync />
<TooltipProvider>
<Toaster />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</NostrProvider>
</NostrLoginProvider>
</QueryClientProvider>
Loaded 100 of 194 files, more files were not shown because too many files have changed in this diff. Show more