Create comprehensive Obsidian-style documentation structure

- Reorganize all markdown documentation into structured docs/ folder
- Create 7 main documentation categories (00-overview through 06-deployment)
- Add comprehensive index files for each category with cross-linking
- Implement Obsidian-compatible [[link]] syntax throughout
- Move legacy/deprecated documentation to archive folder
- Establish documentation standards and maintenance guidelines
- Provide complete coverage of modular architecture, services, and deployment
- Enable better navigation and discoverability for developers and contributors

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
padreug 2025-09-06 14:31:27 +02:00
parent 46856134ef
commit cdf099e45f
29 changed files with 3733 additions and 0 deletions

View file

@ -0,0 +1,479 @@
# 📡 API Reference
> **External integrations and protocol implementations** powering Ario's decentralized architecture with Nostr protocol, Lightning Network, and third-party service APIs.
## Table of Contents
- [[#Protocol Implementations]]
- [[#External APIs]]
- [[#Service Integrations]]
- [[#SDK References]]
- [[#Authentication & Security]]
- [[#Rate Limits & Best Practices]]
## Protocol Implementations
### **Nostr Protocol**
**Specification:** [NIPs (Nostr Implementation Possibilities)](https://github.com/nostr-protocol/nips)
**Client Library:** `nostr-tools` v2.x
**Implementation:** Custom RelayHub service with connection pooling
**Supported NIPs:**
- **NIP-01** - Basic protocol flow and event structure
- **NIP-02** - Contact list and petnames
- **NIP-04** - Encrypted direct messages
- **NIP-05** - Mapping Nostr keys to DNS-based internet identifiers
- **NIP-09** - Event deletion
- **NIP-10** - Conventions for clients' use of `e` and `p` tags
- **NIP-19** - bech32-encoded entities
- **NIP-25** - Reactions
**Core Event Types:**
```typescript
interface NostrEvent {
id: string // Event ID (32-bytes hex)
pubkey: string // Author public key (32-bytes hex)
created_at: number // Unix timestamp in seconds
kind: number // Event kind (0=metadata, 1=text, 3=contacts, etc.)
tags: string[][] // Tags array
content: string // Event content
sig: string // Event signature (64-bytes hex)
}
// Common event kinds
enum EventKind {
Metadata = 0, // User profile information
TextNote = 1, // Short text note
RecommendRelay = 2, // Recommend relay
Contacts = 3, // Contact list
EncryptedDM = 4, // Encrypted direct message
EventDeletion = 5, // Event deletion
Repost = 6, // Repost/boost
Reaction = 7, // Like/reaction
BadgeAward = 8, // Badge award
GroupChatMessage = 9, // Group chat message
}
```
**See:** [[nostr-protocol|📖 Nostr Protocol Implementation]]
### **Lightning Network**
**Protocol:** BOLT specifications for Lightning Network
**Browser Integration:** WebLN API for wallet communication
**Backend Integration:** LNbits for invoice generation and payment processing
**WebLN API Integration:**
```typescript
interface WebLN {
enable(): Promise<void>
getInfo(): Promise<GetInfoResponse>
sendPayment(paymentRequest: string): Promise<SendPaymentResponse>
makeInvoice(args: RequestInvoiceArgs): Promise<RequestInvoiceResponse>
signMessage(message: string): Promise<SignMessageResponse>
}
// Payment workflow
async function processLightningPayment(invoice: string): Promise<PaymentResult> {
if (!window.webln) {
throw new Error('WebLN not available')
}
await window.webln.enable()
const result = await window.webln.sendPayment(invoice)
return {
preimage: result.preimage,
paymentHash: result.paymentHash,
paid: true
}
}
```
**Invoice Generation:**
```typescript
interface LightningInvoice {
payment_request: string // BOLT11 invoice string
payment_hash: string // Payment hash (32-bytes hex)
amount: number // Amount in millisats
description: string // Invoice description
expires_at: number // Expiration timestamp
created_at: number // Creation timestamp
}
```
**See:** [[lightning-integration|📖 Lightning Network Integration]]
## External APIs
### **LNbits API**
**Purpose:** Lightning wallet backend and invoice management
**Documentation:** [LNbits API Docs](https://legend.lnbits.com/docs)
**Base URL:** Configurable via environment variables
**Key Endpoints:**
#### **Wallet Management**
```typescript
// Get wallet information
GET /api/v1/wallet
Authorization: X-Api-Key: {admin_key}
interface WalletInfo {
id: string
name: string
balance: number // Balance in millisats
}
```
#### **Invoice Operations**
```typescript
// Create invoice
POST /api/v1/payments
Content-Type: application/json
Authorization: X-Api-Key: {invoice_key}
interface CreateInvoiceRequest {
out: false // Incoming payment
amount: number // Amount in sats
memo: string // Invoice description
expiry?: number // Expiry in seconds
}
interface CreateInvoiceResponse {
payment_hash: string
payment_request: string // BOLT11 invoice
checking_id: string
}
```
#### **Payment Verification**
```typescript
// Check payment status
GET /api/v1/payments/{checking_id}
Authorization: X-Api-Key: {invoice_key}
interface PaymentStatus {
paid: boolean
checking_id: string
amount: number
fee: number
memo: string
time: number
}
```
**See:** [[lnbits-api|📖 LNbits API Integration]]
### **Nostr Relay APIs**
**Protocol:** WebSocket-based communication following Nostr specification
**Connection Management:** Custom RelayHub with connection pooling and failover
**Relay Communication Protocol:**
```typescript
// Client to relay messages
type ClientMessage =
| ['EVENT', NostrEvent] // Publish event
| ['REQ', string, ...Filter[]] // Request events
| ['CLOSE', string] // Close subscription
// Relay to client messages
type RelayMessage =
| ['EVENT', string, NostrEvent] // Event received
| ['OK', string, boolean, string] // Event acceptance
| ['EOSE', string] // End of stored events
| ['NOTICE', string] // Relay notice
```
**Event Filters:**
```typescript
interface Filter {
ids?: string[] // Event IDs
authors?: string[] // Author pubkeys
kinds?: number[] // Event kinds
since?: number // Events after timestamp
until?: number // Events before timestamp
limit?: number // Maximum number of events
search?: string // Text search (if supported)
[key: string]: any // Tag filters (#e, #p, etc.)
}
```
**Relay Information (NIP-11):**
```typescript
// GET https://relay.example.com (Accept: application/nostr+json)
interface RelayInformation {
name: string
description: string
pubkey?: string
contact?: string
supported_nips?: number[]
software?: string
version?: string
limitation?: {
max_message_length?: number
max_subscriptions?: number
max_filters?: number
max_subid_length?: number
min_pow_difficulty?: number
auth_required?: boolean
payment_required?: boolean
}
}
```
**See:** [[relay-communication|📖 Relay Communication Protocol]]
## Service Integrations
### **QR Code Generation**
**Library:** `qrcode` for QR code generation
**Use Cases:** Lightning invoices, contact sharing, event tickets
```typescript
interface QRCodeOptions {
width?: number
margin?: number
color?: {
dark?: string
light?: string
}
errorCorrectionLevel?: 'L' | 'M' | 'Q' | 'H'
}
async function generateQRCode(data: string, options?: QRCodeOptions): Promise<string> {
return QRCode.toDataURL(data, {
width: options?.width || 256,
margin: options?.margin || 2,
color: {
dark: options?.color?.dark || '#000000',
light: options?.color?.light || '#FFFFFF'
},
errorCorrectionLevel: options?.errorCorrectionLevel || 'M'
})
}
```
### **Cryptography Services**
**Library:** `nostr-tools` cryptographic functions
**Use Cases:** Key generation, event signing, message encryption
```typescript
// Key generation
function generateKeyPair(): { privateKey: string; publicKey: string } {
const privateKey = generatePrivateKey()
const publicKey = getPublicKey(privateKey)
return { privateKey, publicKey }
}
// Event signing
function signEvent(event: UnsignedEvent, privateKey: string): NostrEvent {
const id = getEventHash(event)
const sig = getSignature(id, privateKey)
return { ...event, id, sig }
}
// Message encryption (NIP-04)
async function encryptMessage(
message: string,
recipientPubkey: string,
senderPrivkey: string
): Promise<string> {
return encrypt(senderPrivkey, recipientPubkey, message)
}
```
### **Storage Services**
**Browser APIs:** localStorage, IndexedDB
**Abstraction:** StorageService with user-scoped keys
```typescript
interface StorageService {
// User-scoped operations
setUserData<T>(key: string, data: T): void
getUserData<T>(key: string, defaultValue?: T): T | undefined
removeUserData(key: string): void
clearUserData(): void
// Global application data
setAppData<T>(key: string, data: T): void
getAppData<T>(key: string, defaultValue?: T): T | undefined
}
```
## SDK References
### **Nostr-tools Reference**
**Documentation:** [nostr-tools GitHub](https://github.com/nbd-wtf/nostr-tools)
**Version:** 2.x
**Key Functions:**
```typescript
import {
generatePrivateKey,
getPublicKey,
getEventHash,
getSignature,
validateEvent,
verifySignature,
SimplePool,
Filter,
Event as NostrEvent,
nip04,
nip19
} from 'nostr-tools'
// Pool management
const pool = new SimplePool()
const events = await pool.list(relays, [filter])
const sub = pool.sub(relays, [filter])
```
### **Vue 3 Integration**
**Framework:** Vue 3 Composition API
**State Management:** Pinia stores
**Reactivity:** Vue reactive primitives
```typescript
// Reactive Nostr client integration
export function useNostrClient() {
const isConnected = ref(false)
const connectedRelays = ref<string[]>([])
const connect = async (relays: string[]) => {
// Connection logic
isConnected.value = true
connectedRelays.value = relays
}
return {
isConnected: readonly(isConnected),
connectedRelays: readonly(connectedRelays),
connect
}
}
```
## Authentication & Security
### **Key Management**
**Security Model:** Client-side key generation and storage
**Storage:** Encrypted localStorage with user passphrase
**No Server Storage:** Private keys never leave the client
```typescript
interface AuthenticationFlow {
// Key generation
generateNewUser(): Promise<{ privateKey: string; publicKey: string }>
// Import existing key
importUser(privateKey: string): Promise<UserProfile>
// Session management
login(privateKey: string, remember?: boolean): Promise<void>
logout(): Promise<void>
// Key security
encryptPrivateKey(privateKey: string, passphrase: string): string
decryptPrivateKey(encrypted: string, passphrase: string): string
}
```
### **Event Validation**
**Signature Verification:** All received events are cryptographically verified
**Content Filtering:** Optional content moderation and filtering
**Spam Prevention:** Rate limiting and reputation-based filtering
```typescript
function validateNostrEvent(event: NostrEvent): ValidationResult {
// 1. Check event structure
if (!event.id || !event.pubkey || !event.sig) {
return { valid: false, error: 'Missing required fields' }
}
// 2. Verify event ID
const expectedId = getEventHash(event)
if (event.id !== expectedId) {
return { valid: false, error: 'Invalid event ID' }
}
// 3. Verify signature
const signatureValid = verifySignature(event)
if (!signatureValid) {
return { valid: false, error: 'Invalid signature' }
}
return { valid: true }
}
```
## Rate Limits & Best Practices
### **Relay Communication**
- **Connection Limits** - Maximum 10 concurrent relay connections
- **Subscription Limits** - Maximum 20 active subscriptions per relay
- **Event Publishing** - Rate limited to prevent spam (1 event/second per kind)
- **Reconnection Strategy** - Exponential backoff with maximum 30-second intervals
### **Lightning Payments**
- **Invoice Expiry** - Default 1 hour expiry for generated invoices
- **Payment Verification** - Poll payment status every 5 seconds for 5 minutes
- **Amount Limits** - Configurable minimum/maximum payment amounts
- **Error Handling** - Graceful handling of payment failures and timeouts
### **API Usage Guidelines**
#### **LNbits Integration**
```typescript
const API_CONFIG = {
baseUrl: process.env.VITE_LNBITS_URL,
timeout: 30000, // 30 second timeout
retryAttempts: 3, // Retry failed requests
retryDelay: 1000, // 1 second between retries
rateLimits: {
invoiceCreation: 10, // Max 10 invoices per minute
paymentCheck: 60, // Max 60 payment checks per minute
}
}
```
#### **Nostr Relay Usage**
```typescript
const RELAY_CONFIG = {
maxConnections: 10, // Maximum concurrent connections
maxSubscriptions: 20, // Maximum active subscriptions
connectionTimeout: 10000, // 10 second connection timeout
publishLimits: {
textNote: 5, // Max 5 text notes per minute
reaction: 30, // Max 30 reactions per minute
directMessage: 10, // Max 10 DMs per minute
},
reconnection: {
attempts: 5, // Maximum reconnection attempts
delay: 1000, // Initial delay (1 second)
backoffMultiplier: 2, // Exponential backoff
maxDelay: 30000, // Maximum delay (30 seconds)
}
}
```
## See Also
### Protocol Documentation
- **[[nostr-protocol|📡 Nostr Protocol Implementation]]** - Detailed NIP implementation
- **[[lightning-integration|⚡ Lightning Network Integration]]** - WebLN and payment processing
- **[[lnbits-api|🔗 LNbits API Reference]]** - Lightning backend integration
- **[[events-api|📅 Events System API]]** - Event ticketing API reference
### Implementation Guides
- **[[../03-core-services/index|⚙️ Core Services]]** - Service implementations using these APIs
- **[[../02-modules/index|📦 Module System]]** - How modules integrate with external APIs
- **[[../04-development/index|💻 Development Guide]]** - Testing and debugging API integrations
---
**Tags:** #api #integration #nostr #lightning #protocols
**Last Updated:** 2025-09-06
**Author:** Development Team

View file

@ -0,0 +1,268 @@
# Protocols
## Finance
Layer 1: Bitcoin on-chain
Layer 2: Bitcoin Lightning
Layer 2+: LNBits
## Communication
NOSTR
### Resources
https://nostr.how
https://github.com/nostr-protocol/nips
## Notes on integration
NOSTR and Bitcoin lightning are closely integrated. Each NOSTR profile will have a lightning "zap" address that is likely to be `<username>@<domain>.<ext>`. We want users to be easily able to "zap" each other
### resources
[What are Zaps](https://nostr.how/en/zaps)
# Objective
The objective of this project is to make an app for a social network that serve people in a close physical community. This core tenets of this app are that it be made with FOSS so that it may easily be reproduced.
This app will be able to function on a LAN that is not connected to WAN.
We want this app to foster a strong social network that allows for easy exchange of value. On the server that hosts the application will be a NOSTR Relay which will be the database that stores any content.
## Components
- LNBits Server
- LNBits User Web app
- Front end app designed for enhanced UX/UI
The vast majority of the backend will be handled by the LNBits stack. LNBits includes both a server that facilitates the exchange of value compatible with the lightning network. Technically, this would be described as layer 2+ in the context of Bitcoin. While it is fully compatible with the lightning network, it can also have internal payments that occur mostly at the database level.
LNBits has a collection of extensions that we will leverage in order to super-charge the user experience. When we make a user for a person, we will be creating an lnbits user. A user has access to their lnbits settings through the lnbits front end that is run in tandem with the lnbits server.
We will also create a UI that provides a streamlined experience for less technical users who do not need the level of control that the lnbits quasar web app provides. For this, we will be using Vue3, shadcn-vue (implying tailwind v4), vite, etc. This UI will focus on displaying the content in a visually pleasing way that also provides the ability to interact through their nostr profile. E.g., they can send messages to friends, purchase items from the nostr marketplace, exchange money with friends, etc
### LNBits Server + Extensions
- NOSTR Relay
- NOSTR Client
- NOSTR Marketplace
# Features
- Newsfeed page with filters. E.g., Important Announcements, GenPop, Event notifications, etc
- Communal calendar page
- Communal Marketplace
- Events Page (already present)
# User Experience Details
## Authentication & User Management
- User registration creates both LNBits user and NOSTR key-pair via LNBits API
- Keys stored securely, minimal technical exposure to users
- Simplified onboarding for non-technical users
## User Profiles
- **Displayed Info**: Avatar, username, display name, bio
- **Zap Address**: `<username>@<hostname>` format
- **Wallet Integration**: Show LNBits wallet balance
- **Future Features**: Badges and gamification elements
## Content & Interactions
- **Primary Content**: Moderator posts and automated system posts (e.g., event creation notifications)
- **User Actions**: Reply and react to existing content (limited user-generated content initially)
- **Real-time Updates**: WebSocket-based NOSTR client for live feed updates
- **Data Persistence**: Local storage for offline capability and improved UX
## Technical Architecture
- **PWA Deployment**: Mobile-optimized progressive web app
- **Network**: Functions on LAN without WAN dependency
- **API Integration**: All transactions through LNBits API
- **User Roles**: Admin/moderator/user permissions handled via LNBits
## Development Phases
**Phase 1 (Current Focus)**: Newsfeed and Events
**Phase 2 (Future)**: Marketplace integration
**Phase 3 (Future)**: Location-aware features and maps
# Technical Integration Specifications
## Environment Variables
```
VITE_LNBITS_BASE_URL=http://localhost:5000 # LNBits server URL
VITE_NOSTR_RELAY_URL=ws://localhost:5000/nostrrelay/<relay-id> # NOSTR relay WebSocket
VITE_HOSTNAME=localhost # For zap addresses (username@hostname)
```
## LNBits API Integration Points
### User Management
- **Create User**: `POST /api/v1/user` - Creates LNBits user with NOSTR key-pair
- **Get User**: `GET /api/v1/user/{user_id}` - Retrieve user profile data
- **Update User**: `PUT /api/v1/user/{user_id}` - Update profile (avatar, username, display name, bio)
### Wallet Operations
- **Get Wallet Balance**: `GET /api/v1/wallet` - Retrieve current wallet balance
- **Create Payment**: `POST /api/v1/payments` - Handle zap transactions
- **Payment Status**: `GET /api/v1/payments/{payment_hash}` - Check payment status
### NOSTR Integration
- **NOSTR Client Extension**: `/extensions/nostrclient` - Manages NOSTR connections and messaging
- **NOSTR Relay Extension**: `/extensions/nostrrelay` - Local relay for community content
- **WebSocket Connection**: Real-time event streaming via relay WebSocket
## UI/UX Component Architecture
### Main Navigation
- **Newsfeed** (tabs: All, Important, Events, General)
- **Events** (existing page, integrate with newsfeed notifications)
- **Profile** (modal: user info, wallet balance, settings)
### Newsfeed Features
- Real-time WebSocket updates from NOSTR relay
- Visual priority system for Important Announcements
- Reply and reaction capabilities (zap, like, comment)
- Local storage for offline content persistence
### Zapping Interface
- Quick zap buttons (preset amounts: 10, 50, 100 sats)
- Custom amount modal for larger transactions
- Visual feedback for successful zaps
- Integration with LNBits payment API
### Profile Management
- Editable: avatar, username, display name, bio
- Read-only: zap address (username@hostname), wallet balance
- Future: badges and gamification elements
## Data Flow
1. **User Registration**: Vue app → LNBits API → NOSTR key-pair generation
2. **Content Publishing**: Moderator/System → NOSTR relay → WebSocket → Vue app
3. **User Interactions**: Vue app → LNBits API (payments) + NOSTR relay (social)
4. **Real-time Updates**: NOSTR relay WebSocket → Vue app state management
# NOSTR Event Types for Implementation
Based on NOSTR Improvement Proposals (NIPs), the following event types are relevant for our community app:
## Core Event Types
### User Profile (Kind 0 - NIP-01)
```json
{
"kind": 0,
"content": "{\"name\":\"username\", \"about\":\"bio text\", \"picture\":\"avatar_url\"}"
}
```
- **Usage**: User profile management
- **UI Components**: Profile modal, user avatar/name display
### Text Notes (Kind 1 - NIP-10)
```json
{
"kind": 1,
"content": "Post content text",
"tags": [
["p", "pubkey", "relay_url"], // mentions
["e", "event_id", "relay_url", "marker"] // replies/threads
]
}
```
- **Usage**: Main newsfeed content, moderator announcements
- **UI Components**: Post display, reply threads
### Reactions (Kind 7 - NIP-25)
```json
{
"kind": 7,
"content": "+", // or "-", or emoji
"tags": [
["e", "target_event_id", "relay_url", "target_pubkey"],
["p", "target_pubkey", "relay_url"],
["k", "target_event_kind"]
]
}
```
- **Usage**: Like/dislike posts, emoji reactions
- **UI Components**: Reaction buttons, reaction counts
### Calendar Events (Kind 31922/31923 - NIP-52)
```json
{
"kind": 31922, // date-based events
"content": "Event description",
"tags": [
["d", "unique_identifier"],
["title", "Event Title"],
["start", "YYYY-MM-DD"],
["end", "YYYY-MM-DD"],
["location", "Event location"],
["p", "participant_pubkey", "relay_url", "role"]
]
}
```
- **Usage**: Community calendar, event announcements
- **UI Components**: Event cards, calendar integration, automatic newsfeed posts
## Lightning/Payment Events
### Zap Requests (Kind 9734 - NIP-57)
```json
{
"kind": 9734,
"content": "Zap message",
"tags": [
["relays", "relay1", "relay2"],
["amount", "21000"], // millisats
["p", "recipient_pubkey"],
["e", "target_event_id"] // if zapping a post
]
}
```
- **Usage**: Lightning zap payments
- **UI Components**: Zap buttons, amount selection, payment confirmation
### Zap Receipts (Kind 9735 - NIP-57)
```json
{
"kind": 9735,
"content": "",
"tags": [
["bolt11", "lightning_invoice"],
["description", "zap_request_json"],
["p", "recipient_pubkey"],
["e", "target_event_id"]
]
}
```
- **Usage**: Payment confirmation display
- **UI Components**: Zap success indicators, payment history
## Content Types for Future Implementation
### Long-form Content (Kind 30023 - NIP-23)
- **Usage**: Community announcements, detailed posts
- **Tags**: `title`, `summary`, `image`, `published_at`
### Marketplace Events (NIP-15)
- **Usage**: Community marketplace integration (Phase 2)
## Implementation Notes
### Event Filtering for Newsfeed Tabs
- **All**: Subscribe to kinds [0, 1, 7, 31922, 31923, 9735]
- **Important**: Filter by specific pubkeys (moderators) or tags
- **Events**: Filter specifically for kinds [31922, 31923]
- **General**: Filter for kind 1 excluding moderator pubkeys
### WebSocket Subscription Filters
```json
{
"kinds": [1, 7, 31922, 31923, 9735],
"since": <timestamp>,
"limit": 50
}
```
### Local Storage Schema
- Events by kind and timestamp
- User profiles by pubkey
- Reaction counts by event_id
- Zap totals by event_id and recipient