mirror of
https://gitlab.com/soapbox-pub/mkstack.git
synced 2026-12-03 08:07:21 +00:00
Compare commits
11
Commits
97d116ff7b
...
9d43fdbcc3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d43fdbcc3 | ||
|
|
67eb5f2a1c | ||
|
|
4cea0394d8 | ||
|
|
cd80e588cc | ||
|
|
a09d1aba1b | ||
|
|
51222e00d1 | ||
|
|
e9bec18edf | ||
|
|
75944a4711 | ||
|
|
033ec637c0 | ||
|
|
b33271df67 | ||
|
|
94d21d68de |
No files matched your search
@@ -133,7 +133,7 @@ export function useCurrentUser() {
|
||||
);
|
||||
}
|
||||
case 'extension':
|
||||
return new NUser(login.type, login.pubkey, new NBrowserSignerBtc());
|
||||
return new NUser(login.type, login.pubkey, new NBrowserSignerBtc({ pubkey: login.pubkey }));
|
||||
default:
|
||||
throw new Error(`Unsupported login type: ${login.type}`);
|
||||
}
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import type { NostrSigner } from '@nostrify/types';
|
||||
import { NSecSigner, NBrowserSigner, NConnectSigner } from '@nostrify/nostrify';
|
||||
import { NSecSigner, NConnectSigner } from '@nostrify/nostrify';
|
||||
import type { NConnectSignerOpts } from '@nostrify/nostrify';
|
||||
|
||||
import { signPsbtLocal } from '@/lib/bitcoin';
|
||||
import { Nip07Signer } from '@/lib/Nip07Signer';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// BtcSigner interface
|
||||
@@ -56,28 +57,28 @@ export class NSecSignerBtc extends NSecSigner implements BtcSigner {
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Extends `NBrowserSigner` with NIP-07 `window.nostr.signPsbt()` support.
|
||||
* 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 NBrowserSigner implements BtcSigner {
|
||||
constructor(opts?: { timeout?: number }) {
|
||||
export class NBrowserSignerBtc extends Nip07Signer implements BtcSigner {
|
||||
constructor(opts?: { pubkey?: string; timeout?: number }) {
|
||||
super(opts);
|
||||
}
|
||||
|
||||
async signPsbt(psbtHex: string): Promise<string> {
|
||||
// `awaitNostr` is TypeScript-private but JavaScript-public at runtime.
|
||||
const nostr = await (this as unknown as { awaitNostr(): Promise<Record<string, unknown>> }).awaitNostr();
|
||||
const signer = await this.signer();
|
||||
|
||||
if (typeof nostr.signPsbt !== 'function') {
|
||||
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.",
|
||||
);
|
||||
}
|
||||
|
||||
const signPsbt = nostr.signPsbt as (hex: string) => Promise<string>;
|
||||
return signPsbt(psbtHex);
|
||||
return signer.signPsbt(psbtHex);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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
|
||||
+2
-25
@@ -1,33 +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
|
||||
.eslintcache
|
||||
.tsbuildinfo
|
||||
.ai/
|
||||
yarn.lock
|
||||
|
||||
# Editor directories and files
|
||||
.idea
|
||||
*.tsbuildinfo
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
|
||||
# Vercel
|
||||
.vercel
|
||||
|
||||
# Secrets
|
||||
.env
|
||||
|
||||
@@ -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
|
||||
Vendored
-14
@@ -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"]
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
-3
@@ -1,3 +0,0 @@
|
||||
{
|
||||
"editor.tabSize": 2
|
||||
}
|
||||
@@ -1,242 +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
|
||||
|
||||
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 MKStack. You are free to copy, modify, distribute, and use this software for any purpose, commercial or non-commercial, without asking permission and without attribution.
|
||||
|
||||
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.
|
||||
Generated
+1939
-3043
File diff suppressed because it is too large.
Load diff
+34
-36
@@ -9,55 +9,53 @@
|
||||
"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": {
|
||||
"@daypicker/react": "^10.0.2",
|
||||
"@nostrify/nostrify": "^0.55.1",
|
||||
"@nostrify/react": "^0.6.8",
|
||||
"@radix-ui/react-toast": "^1.2.1",
|
||||
"@tanstack/react-query": "^5.100.5",
|
||||
"@unhead/react": "^3.1.0",
|
||||
"@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.1.1",
|
||||
"embla-carousel-react": "^8.6.0",
|
||||
"input-otp": "^1.4.2",
|
||||
"lucide-react": "^1.11.0",
|
||||
"nostr-tools": "^2.23.3",
|
||||
"input-otp": "^1.5.0",
|
||||
"lucide-react": "^1.83.0",
|
||||
"nostr-tools": "^2.26.1",
|
||||
"qrcode": "^1.5.4",
|
||||
"radix-ui": "^1.4.3",
|
||||
"react": "^19.2.5",
|
||||
"react-day-picker": "^9.14.0",
|
||||
"react-dom": "^19.2.5",
|
||||
"react-hook-form": "^7.74.0",
|
||||
"react-resizable-panels": "^4.10.0",
|
||||
"react-router-dom": "^7.14.2",
|
||||
"recharts": "^3.8.1",
|
||||
"tailwind-merge": "^3.5.0",
|
||||
"tw-animate-css": "^1.2.0",
|
||||
"unhead": "^3.1.0",
|
||||
"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.3.6"
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@html-eslint/eslint-plugin": "^0.59.0",
|
||||
"@html-eslint/parser": "^0.59.0",
|
||||
"@tailwindcss/vite": "^4.2.4",
|
||||
"@testing-library/jest-dom": "^6.9.1",
|
||||
"@testing-library/react": "^16.3.2",
|
||||
"@types/node": "^24.12.2",
|
||||
"@types/qrcode": "^1.5.5",
|
||||
"@types/react": "^19.2.14",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.1",
|
||||
"eslint": "^10.2.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.2",
|
||||
"globals": "^17.5.0",
|
||||
"jsdom": "^29.1.0",
|
||||
"tailwindcss": "^4.2.4",
|
||||
"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.59.0",
|
||||
"vite": "^8.0.10",
|
||||
"vitest": "^4.1.5"
|
||||
"typescript-eslint": "^8.74.0",
|
||||
"vite": "^8.4.0",
|
||||
"vitest": "^5.1.2"
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
/assets/* /assets/:splat 200
|
||||
/* /index.html 200
|
||||
@@ -5,6 +5,7 @@ import { NostrContext } from '@nostrify/react';
|
||||
import { NUser, useNostrLogin } from '@nostrify/react/login';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { Nip07Signer } from '@/lib/Nip07Signer';
|
||||
|
||||
interface NostrProviderProps {
|
||||
children: React.ReactNode;
|
||||
@@ -106,7 +107,8 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
|
||||
case 'bunker':
|
||||
return NUser.fromBunkerLogin(currentLogin, pool).signer;
|
||||
case 'extension':
|
||||
return NUser.fromExtensionLogin(currentLogin).signer;
|
||||
// Pinned to the login's account where the extension offers getSigner.
|
||||
return new Nip07Signer({ pubkey: currentLogin.pubkey });
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import { useEffect } from 'react';
|
||||
import { useEffect, useRef } from 'react';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useNostrLogin } from '@nostrify/react/login';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { parseBlossomServerList } from '@/lib/appBlossom';
|
||||
import { getNip07Provider, hasDisconnect } from '@/lib/nip07';
|
||||
|
||||
/**
|
||||
* NostrSync - Syncs user's Nostr data
|
||||
@@ -11,11 +13,31 @@ import { parseBlossomServerList } from '@/lib/appBlossom';
|
||||
* Currently syncs:
|
||||
* - NIP-65 relay list (kind 10002)
|
||||
* - BUD-03 Blossom server list (kind 10063)
|
||||
*
|
||||
* It also gives an extension login's account back to the extension when it
|
||||
* logs out, where the extension can take it (`window.nostr.disconnect`, as
|
||||
* Din and Tenna offer), so the site no longer holds it there either.
|
||||
*/
|
||||
export function NostrSync() {
|
||||
const { nostr } = useNostr();
|
||||
const { user } = useCurrentUser();
|
||||
const { config, updateConfig } = useAppContext();
|
||||
const { logins } = useNostrLogin();
|
||||
const extensionLogins = useRef<Set<string>>(new Set());
|
||||
|
||||
useEffect(() => {
|
||||
const current = new Set(
|
||||
logins.filter((login) => login.type === 'extension').map((login) => login.pubkey),
|
||||
);
|
||||
const provider = getNip07Provider();
|
||||
for (const pubkey of extensionLogins.current) {
|
||||
if (current.has(pubkey) || !hasDisconnect(provider)) continue;
|
||||
provider.disconnect(pubkey).catch((error: unknown) => {
|
||||
console.warn("The extension didn't take the account back:", error);
|
||||
});
|
||||
}
|
||||
extensionLogins.current = current;
|
||||
}, [logins]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!user) return;
|
||||
|
||||
@@ -3,26 +3,11 @@ import { Button } from '@/components/ui/button.tsx';
|
||||
import AuthDialog from './AuthDialog';
|
||||
import { QuickLoginDialog } from './QuickLoginDialog';
|
||||
import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts';
|
||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||
import { getNip07Provider, hasConnect } from '@/lib/nip07';
|
||||
import { AccountSwitcher } from './AccountSwitcher';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
/** Minimal shape of the NIP-07 provider injected at `window.nostr`. */
|
||||
interface Nip07Provider {
|
||||
getPublicKey(): Promise<string>;
|
||||
}
|
||||
|
||||
function getNip07Provider(): Nip07Provider | undefined {
|
||||
if (typeof window === 'undefined' || !('nostr' in window)) return undefined;
|
||||
const provider = (window as { nostr?: unknown }).nostr;
|
||||
if (
|
||||
provider &&
|
||||
typeof (provider as Nip07Provider).getPublicKey === 'function'
|
||||
) {
|
||||
return provider as Nip07Provider;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export interface LoginAreaProps {
|
||||
className?: string;
|
||||
}
|
||||
@@ -31,10 +16,22 @@ export function LoginArea({ className }: LoginAreaProps) {
|
||||
const { currentUser } = useLoggedInAccounts();
|
||||
const [authDialogOpen, setAuthDialogOpen] = useState(false);
|
||||
const [quickLoginPubkey, setQuickLoginPubkey] = useState<string | null>(null);
|
||||
const login = useLoginActions();
|
||||
|
||||
// An extension that can give the site an account (connect) is asked for one
|
||||
// straight away, since it shows the account itself. Otherwise one that
|
||||
// exposes a pubkey gets the one-tap "Welcome back" dialog. Either way a
|
||||
// refusal falls through to the full dialog.
|
||||
const handleJoin = async () => {
|
||||
const provider = getNip07Provider();
|
||||
if (provider) {
|
||||
if (hasConnect(provider)) {
|
||||
try {
|
||||
await login.extension();
|
||||
return;
|
||||
} catch {
|
||||
// Declined or errored — fall through to the full dialog.
|
||||
}
|
||||
} else if (provider) {
|
||||
try {
|
||||
const pubkey = await provider.getPublicKey();
|
||||
if (pubkey) {
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { AlertDialog as AlertDialogPrimitive } from "radix-ui"
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"use client"
|
||||
|
||||
import { AspectRatio as AspectRatioPrimitive } from "radix-ui"
|
||||
|
||||
function AspectRatio({
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import {
|
||||
ChevronDownIcon,
|
||||
@@ -10,7 +8,7 @@ import {
|
||||
DayPicker,
|
||||
getDefaultClassNames,
|
||||
type DayButton,
|
||||
} from "react-day-picker"
|
||||
} from "@daypicker/react"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/components/ui/button"
|
||||
@@ -53,17 +51,17 @@ function Calendar({
|
||||
),
|
||||
month: cn("flex w-full flex-col gap-4", defaultClassNames.month),
|
||||
nav: cn(
|
||||
"absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",
|
||||
"pointer-events-none absolute inset-x-0 top-0 flex w-full items-center justify-between gap-1",
|
||||
defaultClassNames.nav
|
||||
),
|
||||
button_previous: cn(
|
||||
buttonVariants({ variant: buttonVariant }),
|
||||
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
|
||||
"pointer-events-auto size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
|
||||
defaultClassNames.button_previous
|
||||
),
|
||||
button_next: cn(
|
||||
buttonVariants({ variant: buttonVariant }),
|
||||
"size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
|
||||
"pointer-events-auto size-(--cell-size) p-0 select-none aria-disabled:opacity-50",
|
||||
defaultClassNames.button_next
|
||||
),
|
||||
month_caption: cn(
|
||||
@@ -89,7 +87,7 @@ function Calendar({
|
||||
: "flex h-8 items-center gap-1 rounded-md pr-1 pl-2 text-sm [&>svg]:size-3.5 [&>svg]:text-muted-foreground",
|
||||
defaultClassNames.caption_label
|
||||
),
|
||||
table: "w-full border-collapse",
|
||||
month_grid: cn("w-full border-collapse", defaultClassNames.month_grid),
|
||||
weekdays: cn("flex", defaultClassNames.weekdays),
|
||||
weekday: cn(
|
||||
"flex-1 rounded-md text-[0.8rem] font-normal text-muted-foreground select-none",
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import * as RechartsPrimitive from "recharts"
|
||||
import type { TooltipValueType } from "recharts"
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"use client"
|
||||
|
||||
import { Collapsible as CollapsiblePrimitive } from "radix-ui"
|
||||
|
||||
function Collapsible({
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { XIcon } from "lucide-react"
|
||||
import { Dialog as DialogPrimitive } from "radix-ui"
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||
import { DropdownMenu as DropdownMenuPrimitive } from "radix-ui"
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { OTPInput, OTPInputContext } from "input-otp"
|
||||
import { MinusIcon } from "lucide-react"
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { CheckIcon, ChevronRightIcon, CircleIcon } from "lucide-react"
|
||||
import { Menubar as MenubarPrimitive } from "radix-ui"
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Progress as ProgressPrimitive } from "radix-ui"
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"use client"
|
||||
|
||||
import { GripVerticalIcon } from "lucide-react"
|
||||
import * as ResizablePrimitive from "react-resizable-panels"
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { CheckIcon, ChevronDownIcon, ChevronUpIcon } from "lucide-react"
|
||||
import { Select as SelectPrimitive } from "radix-ui"
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { XIcon } from "lucide-react"
|
||||
import { Dialog as SheetPrimitive } from "radix-ui"
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { type VariantProps } from "class-variance-authority"
|
||||
import { PanelLeftIcon } from "lucide-react"
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { Switch as SwitchPrimitive } from "radix-ui"
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { type VariantProps } from "class-variance-authority"
|
||||
import { Tabs as TabsPrimitive } from "radix-ui"
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import * as React from "react"
|
||||
import * as ToastPrimitives from "@radix-ui/react-toast"
|
||||
import { Toast as ToastPrimitives } from "radix-ui"
|
||||
import { type VariantProps } from "class-variance-authority"
|
||||
import { X } from "lucide-react"
|
||||
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { type VariantProps } from "class-variance-authority"
|
||||
import { ToggleGroup as ToggleGroupPrimitive } from "radix-ui"
|
||||
|
||||
@@ -3,6 +3,7 @@ import { useNostr } from '@nostrify/react';
|
||||
import { useCallback, useMemo } from 'react';
|
||||
|
||||
import { useAuthor } from './useAuthor.ts';
|
||||
import { Nip07Signer } from '@/lib/Nip07Signer';
|
||||
|
||||
export function useCurrentUser() {
|
||||
const { nostr } = useNostr();
|
||||
@@ -14,8 +15,8 @@ export function useCurrentUser() {
|
||||
return NUser.fromNsecLogin(login);
|
||||
case 'bunker': // Nostr login with NIP-46 "bunker://" URI
|
||||
return NUser.fromBunkerLogin(login, nostr);
|
||||
case 'extension': // Nostr login with NIP-07 browser extension
|
||||
return NUser.fromExtensionLogin(login);
|
||||
case 'extension': // NIP-07 browser extension, pinned to this account where the extension can (getSigner)
|
||||
return new NUser(login.type, login.pubkey, new Nip07Signer({ pubkey: login.pubkey }));
|
||||
// Other login types can be defined here
|
||||
default:
|
||||
throw new Error(`Unsupported login type: ${login.type}`);
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
} from '@nostrify/react/login';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { APP_RELAYS } from '@/lib/appRelays';
|
||||
import { getNip07Provider, hasConnect } from '@/lib/nip07';
|
||||
|
||||
// NOTE: This file should not be edited except for adding new login methods.
|
||||
|
||||
@@ -40,8 +41,21 @@ export function useLoginActions() {
|
||||
const login = await NLogin.fromBunker(uri, nostr);
|
||||
addAndActivate(login);
|
||||
},
|
||||
// Login with a NIP-07 browser extension
|
||||
// Login with a NIP-07 browser extension. One that can give the site an
|
||||
// account of the user's choosing (connect) is asked for one; the
|
||||
// extension shows the account itself.
|
||||
async extension(): Promise<void> {
|
||||
const provider = getNip07Provider();
|
||||
if (hasConnect(provider)) {
|
||||
const signer = await provider.connect();
|
||||
const answer: unknown = await signer.getPublicKey();
|
||||
const pubkey = typeof answer === 'string' ? answer.toLowerCase() : '';
|
||||
if (!/^[0-9a-f]{64}$/.test(pubkey)) {
|
||||
throw new Error('The extension returned an invalid public key');
|
||||
}
|
||||
addAndActivate(new NLogin('extension', pubkey, null));
|
||||
return;
|
||||
}
|
||||
const login = await NLogin.fromExtension();
|
||||
addAndActivate(login);
|
||||
},
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
import type { NostrEvent, NostrSigner } from '@nostrify/types';
|
||||
import { verifyEvent } from 'nostr-tools';
|
||||
|
||||
import { awaitNip07Provider, getNip07Provider, hasGetSigner, type Nip07Provider } from '@/lib/nip07';
|
||||
|
||||
/**
|
||||
* A NIP-07 browser-extension signer, normalizing behavior across extensions
|
||||
* as Nostrify's `NBrowserSigner` does.
|
||||
*
|
||||
* Given the login's `pubkey`, it acts as that account through the
|
||||
* extension's `getSigner(pubkey)` where the extension offers it (Din and
|
||||
* Tenna do), so switching accounts in the extension doesn't change who the
|
||||
* app signs as. A `NotFoundError` from `getSigner` (the extension no longer
|
||||
* gives this site that account) is passed on, never answered by acting as
|
||||
* another account. Extensions without `getSigner` are called directly.
|
||||
*/
|
||||
export class Nip07Signer implements NostrSigner {
|
||||
readonly #pubkey: string | undefined;
|
||||
readonly #timeout: number;
|
||||
#pinned: Promise<NostrSigner> | undefined;
|
||||
|
||||
constructor(opts?: { pubkey?: string; timeout?: number }) {
|
||||
this.#pubkey = opts?.pubkey;
|
||||
this.#timeout = opts?.timeout ?? 3000;
|
||||
}
|
||||
|
||||
/** The signer to call: pinned to the login's account when the extension can, else `window.nostr`. */
|
||||
protected async signer(): Promise<Nip07Provider> {
|
||||
const nostr = await awaitNip07Provider(this.#timeout);
|
||||
if (!this.#pubkey || !hasGetSigner(nostr)) return nostr;
|
||||
if (!this.#pinned) {
|
||||
const pinned = nostr.getSigner(this.#pubkey);
|
||||
this.#pinned = pinned;
|
||||
// Ask again next time: the account may be given back to the site.
|
||||
pinned.catch(() => {
|
||||
if (this.#pinned === pinned) this.#pinned = undefined;
|
||||
});
|
||||
}
|
||||
return this.#pinned;
|
||||
}
|
||||
|
||||
async getPublicKey(): Promise<string> {
|
||||
const pubkey = await (await this.signer()).getPublicKey();
|
||||
if (typeof pubkey !== 'string') {
|
||||
throw new Error(`Nostr public key retrieval failed: expected string, got ${JSON.stringify(pubkey)}`);
|
||||
}
|
||||
return pubkey;
|
||||
}
|
||||
|
||||
async signEvent(event: Omit<NostrEvent, 'id' | 'pubkey' | 'sig'>): Promise<NostrEvent> {
|
||||
const signed = await (await this.signer()).signEvent(event);
|
||||
if (typeof signed !== 'object' || !signed || !signed.id || !signed.pubkey || !signed.sig) {
|
||||
throw new Error(
|
||||
`Nostr event signing failed: expected object with id, pubkey, and sig, got ${JSON.stringify(signed)}`,
|
||||
);
|
||||
}
|
||||
// Rebuilt from the NIP-01 fields alone, which also drops nostr-tools'
|
||||
// cached `verifiedSymbol`, so the signature is really checked.
|
||||
const normalized: NostrEvent = {
|
||||
id: signed.id,
|
||||
pubkey: signed.pubkey,
|
||||
kind: signed.kind,
|
||||
content: signed.content,
|
||||
tags: signed.tags,
|
||||
created_at: signed.created_at,
|
||||
sig: signed.sig,
|
||||
};
|
||||
if (!verifyEvent(normalized)) {
|
||||
throw new Error('Nostr event signing failed: the extension returned an invalid event');
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
async getRelays(): Promise<Record<string, { read: boolean; write: boolean }>> {
|
||||
const signer = await this.signer();
|
||||
if (!signer.getRelays) return {};
|
||||
const relays = await signer.getRelays();
|
||||
if (typeof relays !== 'object' || relays === null) {
|
||||
throw new Error(`Nostr getRelays failed: expected object, got ${JSON.stringify(relays)}`);
|
||||
}
|
||||
return relays;
|
||||
}
|
||||
|
||||
get nip04(): NostrSigner['nip04'] {
|
||||
return this.#cipher('nip04', 'NIP-04');
|
||||
}
|
||||
|
||||
get nip44(): NostrSigner['nip44'] {
|
||||
return this.#cipher('nip44', 'NIP-44');
|
||||
}
|
||||
|
||||
/**
|
||||
* Undefined when a loaded extension lacks the scheme; otherwise (including
|
||||
* before the extension has loaded) a wrapper that waits for it.
|
||||
*/
|
||||
#cipher(scheme: 'nip04' | 'nip44', label: string): NostrSigner['nip44'] {
|
||||
const loaded = getNip07Provider();
|
||||
if (loaded && !loaded[scheme]) return undefined;
|
||||
|
||||
const run = async (op: 'encrypt' | 'decrypt', pubkey: string, text: string): Promise<string> => {
|
||||
const what = `${label} ${op === 'encrypt' ? 'encryption' : 'decryption'}`;
|
||||
const cipher = (await this.signer())[scheme];
|
||||
if (!cipher) throw new Error(`${what} not supported by extension`);
|
||||
const result = await cipher[op](pubkey, text);
|
||||
if (typeof result !== 'string') {
|
||||
throw new Error(`${what} failed: expected string result, got ${JSON.stringify(result)}`);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
|
||||
return {
|
||||
encrypt: (pubkey, plaintext) => run('encrypt', pubkey, plaintext),
|
||||
decrypt: (pubkey, ciphertext) => run('decrypt', pubkey, ciphertext),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
import type { NostrSigner } from '@nostrify/types';
|
||||
|
||||
/**
|
||||
* The NIP-07 provider at `window.nostr`, with the optional multi-account
|
||||
* additions some providers (Din, Tenna) offer. Each may be missing, so check
|
||||
* for it before calling it:
|
||||
*
|
||||
* - `connect()` asks the user to give the site an account and resolves with
|
||||
* a signer for it. It always asks, so the provider shows the account.
|
||||
* - `getSigner(pubkey)` resolves, without asking, with a signer pinned to an
|
||||
* account the site holds, whatever account the provider itself is acting
|
||||
* as. It rejects with a `NotFoundError` DOMException if the site doesn't
|
||||
* hold that account.
|
||||
* - `disconnect(pubkey)` lets the site's account go, without asking.
|
||||
*
|
||||
* A signer from `connect` or `getSigner` keeps its account, and its
|
||||
* `getPublicKey()` answers without asking, even once the site no longer
|
||||
* holds the account. Its other methods then reject with `NotFoundError`.
|
||||
*/
|
||||
export interface Nip07Provider extends NostrSigner {
|
||||
connect?(): Promise<NostrSigner>;
|
||||
getSigner?(pubkey: string): Promise<NostrSigner>;
|
||||
disconnect?(pubkey: string): Promise<void>;
|
||||
signPsbt?(psbtHex: string): Promise<string>;
|
||||
}
|
||||
|
||||
/** The provider at `window.nostr`, if one has been injected. */
|
||||
export function getNip07Provider(): Nip07Provider | undefined {
|
||||
const provider = (globalThis as { nostr?: unknown }).nostr;
|
||||
if (provider && typeof (provider as Nip07Provider).getPublicKey === 'function') {
|
||||
return provider as Nip07Provider;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/** Whether the provider can ask the user for an account to give the site. */
|
||||
export function hasConnect(
|
||||
provider: Nip07Provider | undefined,
|
||||
): provider is Nip07Provider & Required<Pick<Nip07Provider, 'connect'>> {
|
||||
return typeof provider?.connect === 'function';
|
||||
}
|
||||
|
||||
/** Whether the provider can hand out signers pinned to an account. */
|
||||
export function hasGetSigner(
|
||||
provider: Nip07Provider | undefined,
|
||||
): provider is Nip07Provider & Required<Pick<Nip07Provider, 'getSigner'>> {
|
||||
return typeof provider?.getSigner === 'function';
|
||||
}
|
||||
|
||||
/** Whether the provider lets the site give an account back. */
|
||||
export function hasDisconnect(
|
||||
provider: Nip07Provider | undefined,
|
||||
): provider is Nip07Provider & Required<Pick<Nip07Provider, 'disconnect'>> {
|
||||
return typeof provider?.disconnect === 'function';
|
||||
}
|
||||
|
||||
/** Wait for `window.nostr`, polling every 100 ms up to `timeout`. */
|
||||
export function awaitNip07Provider(timeout = 3000): Promise<Nip07Provider> {
|
||||
const provider = getNip07Provider();
|
||||
if (provider) return Promise.resolve(provider);
|
||||
|
||||
const deadline = Date.now() + timeout;
|
||||
return new Promise((resolve, reject) => {
|
||||
const interval = setInterval(() => {
|
||||
const provider = getNip07Provider();
|
||||
if (provider) {
|
||||
clearInterval(interval);
|
||||
resolve(provider);
|
||||
} else if (Date.now() >= deadline) {
|
||||
clearInterval(interval);
|
||||
reject(new Error('Browser extension not available'));
|
||||
}
|
||||
}, 100);
|
||||
});
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
import '@testing-library/jest-dom';
|
||||
import '@testing-library/jest-dom/vitest';
|
||||
import { vi } from 'vitest';
|
||||
|
||||
// Mock window.matchMedia
|
||||
|
||||
@@ -24,9 +24,6 @@ export default defineConfig(() => ({
|
||||
'**/{vite,eslint}.config.*',
|
||||
'.agents/**',
|
||||
],
|
||||
onConsoleLog(log) {
|
||||
return !log.includes("React Router Future Flag Warning");
|
||||
},
|
||||
env: {
|
||||
DEBUG_PRINT_LIMIT: '0', // Suppress DOM output that exceeds AI context windows
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user