diff --git a/docs/.obsidian/app.json b/docs/.obsidian/app.json new file mode 100644 index 0000000..9e26dfe --- /dev/null +++ b/docs/.obsidian/app.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/docs/.obsidian/appearance.json b/docs/.obsidian/appearance.json new file mode 100644 index 0000000..9e26dfe --- /dev/null +++ b/docs/.obsidian/appearance.json @@ -0,0 +1 @@ +{} \ No newline at end of file diff --git a/docs/.obsidian/core-plugins.json b/docs/.obsidian/core-plugins.json new file mode 100644 index 0000000..b977c25 --- /dev/null +++ b/docs/.obsidian/core-plugins.json @@ -0,0 +1,31 @@ +{ + "file-explorer": true, + "global-search": true, + "switcher": true, + "graph": true, + "backlink": true, + "canvas": true, + "outgoing-link": true, + "tag-pane": true, + "properties": false, + "page-preview": true, + "daily-notes": true, + "templates": true, + "note-composer": true, + "command-palette": true, + "slash-command": false, + "editor-status": true, + "bookmarks": true, + "markdown-importer": false, + "zk-prefixer": false, + "random-note": false, + "outline": true, + "word-count": true, + "slides": false, + "audio-recorder": false, + "workspaces": false, + "file-recovery": true, + "publish": false, + "sync": true, + "webviewer": false +} \ No newline at end of file diff --git a/docs/.obsidian/workspace.json b/docs/.obsidian/workspace.json new file mode 100644 index 0000000..74aab89 --- /dev/null +++ b/docs/.obsidian/workspace.json @@ -0,0 +1,175 @@ +{ + "main": { + "id": "ff312565b85205f5", + "type": "split", + "children": [ + { + "id": "22824a70121de2e3", + "type": "tabs", + "children": [ + { + "id": "fe085d296b05d361", + "type": "leaf", + "state": { + "type": "markdown", + "state": { + "file": "01-architecture/index.md", + "mode": "source", + "source": false + }, + "icon": "lucide-file", + "title": "index" + } + } + ] + } + ], + "direction": "vertical" + }, + "left": { + "id": "473f9c90dc0ac250", + "type": "split", + "children": [ + { + "id": "ee303aa846d48de1", + "type": "tabs", + "children": [ + { + "id": "b3b6e397fb343c96", + "type": "leaf", + "state": { + "type": "file-explorer", + "state": { + "sortOrder": "alphabetical", + "autoReveal": false + }, + "icon": "lucide-folder-closed", + "title": "Files" + } + }, + { + "id": "57989530481d5df7", + "type": "leaf", + "state": { + "type": "search", + "state": { + "query": "", + "matchingCase": false, + "explainSearch": false, + "collapseAll": false, + "extraContext": false, + "sortOrder": "alphabetical" + }, + "icon": "lucide-search", + "title": "Search" + } + }, + { + "id": "77b47c3e2e5e4005", + "type": "leaf", + "state": { + "type": "bookmarks", + "state": {}, + "icon": "lucide-bookmark", + "title": "Bookmarks" + } + } + ] + } + ], + "direction": "horizontal", + "width": 300 + }, + "right": { + "id": "5468ccf17d8ecb0f", + "type": "split", + "children": [ + { + "id": "6a62aec4067b5e7c", + "type": "tabs", + "children": [ + { + "id": "37a0910880ab8e26", + "type": "leaf", + "state": { + "type": "backlink", + "state": { + "file": "01-architecture/index.md", + "collapseAll": false, + "extraContext": false, + "sortOrder": "alphabetical", + "showSearch": false, + "searchQuery": "", + "backlinkCollapsed": false, + "unlinkedCollapsed": true + }, + "icon": "links-coming-in", + "title": "Backlinks for index" + } + }, + { + "id": "4520ebffbf27e768", + "type": "leaf", + "state": { + "type": "outgoing-link", + "state": { + "file": "01-architecture/index.md", + "linksCollapsed": false, + "unlinkedCollapsed": true + }, + "icon": "links-going-out", + "title": "Outgoing links from index" + } + }, + { + "id": "210907b9838cac35", + "type": "leaf", + "state": { + "type": "tag", + "state": { + "sortOrder": "frequency", + "useHierarchy": true, + "showSearch": false, + "searchQuery": "" + }, + "icon": "lucide-tags", + "title": "Tags" + } + }, + { + "id": "f2e44745914b6556", + "type": "leaf", + "state": { + "type": "outline", + "state": { + "file": "01-architecture/index.md", + "followCursor": false, + "showSearch": false, + "searchQuery": "" + }, + "icon": "lucide-list", + "title": "Outline of index" + } + } + ] + } + ], + "direction": "horizontal", + "width": 300, + "collapsed": true + }, + "left-ribbon": { + "hiddenItems": { + "switcher:Open quick switcher": false, + "graph:Open graph view": false, + "canvas:Create new canvas": false, + "daily-notes:Open today's daily note": false, + "templates:Insert template": false, + "command-palette:Open command palette": false + } + }, + "active": "fe085d296b05d361", + "lastOpenFiles": [ + "00-overview/index.md" + ] +} \ No newline at end of file diff --git a/docs/00-overview/index.md b/docs/00-overview/index.md new file mode 100644 index 0000000..7df5ef2 --- /dev/null +++ b/docs/00-overview/index.md @@ -0,0 +1,136 @@ +# ๐Ÿ“– Overview + +> **Welcome to the Ario Web Application** - A modular Vue 3 + TypeScript application with Nostr protocol integration and Lightning Network payments. + +## Table of Contents + +- [[#What is Ario?]] +- [[#Key Features]] +- [[#Technology Stack]] +- [[#Quick Start]] +- [[#Documentation Navigation]] + +## What is Ario? + +Ario is a decentralized social and marketplace application built on the Nostr protocol with Lightning Network integration. It provides users with: + +- **Decentralized Social Networking** - Connect through the Nostr protocol +- **Lightning Payments** - Instant, low-fee Bitcoin payments +- **Event Ticketing** - Create and manage events with Lightning payments +- **Encrypted Messaging** - Private, secure communications +- **Marketplace Functionality** - Buy and sell goods using Lightning Network + +## Key Features + +### ๐Ÿ”’ **Privacy-First Architecture** +- No central servers storing user data +- Nostr protocol ensures user sovereignty +- Client-side key management with secure encryption + +### โšก **Lightning Network Integration** +- Instant Bitcoin payments for events and marketplace +- Low transaction fees +- Invoice generation and payment tracking + +### ๐Ÿ—๏ธ **Modular Architecture** +- Plugin-based module system +- Dependency injection for service management +- Clean separation of concerns +- Easy to extend and maintain + +### ๐Ÿ“ฑ **Multi-Platform Support** +- Progressive Web App (PWA) capabilities +- Electron desktop application +- Responsive design for mobile and desktop + +### ๐ŸŒ **Internationalization** +- Multi-language support with Vue-i18n +- Theme switching (light/dark modes) +- Accessibility-focused design + +## Technology Stack + +### Frontend Core +- **Vue 3** with Composition API and ` +``` + +## Service Development + +### **Creating a New Service** + +#### 1. Service Class Implementation +```typescript +// src/core/services/MyService.ts +export class MyService extends BaseService { + // Reactive state + private readonly _data = ref([]) + private readonly _isLoading = ref(false) + + // Public readonly access to state + public readonly data = readonly(this._data) + public readonly isLoading = readonly(this._isLoading) + + constructor( + private dependency = injectService(SERVICE_TOKENS.DEPENDENCY) + ) { + super() + } + + async initialize(): Promise { + // Initialization logic + await this.loadInitialData() + this.isInitialized.value = true + } + + async dispose(): Promise { + // Cleanup logic + this._data.value = [] + this.isDisposed.value = true + } + + // Public methods + async createItem(item: CreateItemRequest): Promise { + this._isLoading.value = true + try { + const newItem = await this.dependency.create(item) + this._data.value.push(newItem) + return newItem + } finally { + this._isLoading.value = false + } + } +} +``` + +#### 2. Service Token Registration +```typescript +// Add to SERVICE_TOKENS +export const SERVICE_TOKENS = { + // ... existing tokens + MY_SERVICE: Symbol('MY_SERVICE') as InjectionKey, +} as const +``` + +#### 3. Service Registration in Module +```typescript +// In module installation +const myService = new MyService() +container.provide(SERVICE_TOKENS.MY_SERVICE, myService) +await myService.initialize() +``` + +### **Service Best Practices** + +#### **Reactive State Management** +- Use `ref()` for mutable state, `readonly()` for public access +- Provide computed properties for derived state +- Use `watch()` and `watchEffect()` for side effects + +#### **Error Handling** +- Throw descriptive errors with proper types +- Use try/catch blocks with proper cleanup +- Log errors appropriately for debugging + +#### **Performance Optimization** +- Implement proper subscription cleanup in `dispose()` +- Use debouncing for frequent operations +- Cache expensive computations with `computed()` + +## Testing Services + +### **Service Unit Tests** +```typescript +// tests/unit/services/MyService.test.ts +describe('MyService', () => { + let service: MyService + let mockDependency: MockType + + beforeEach(() => { + // Setup mocks + mockDependency = createMockService() + + // Create service with mocks + service = new MyService(mockDependency) + }) + + afterEach(async () => { + await service.dispose() + }) + + it('should initialize correctly', async () => { + await service.initialize() + + expect(service.isInitialized.value).toBe(true) + expect(service.data.value).toEqual([]) + }) + + it('should create items', async () => { + await service.initialize() + + const item = await service.createItem({ name: 'test' }) + + expect(service.data.value).toContain(item) + expect(mockDependency.create).toHaveBeenCalledWith({ name: 'test' }) + }) +}) +``` + +### **Integration Tests** +```typescript +// tests/integration/services/ServiceIntegration.test.ts +describe('Service Integration', () => { + let container: DIContainer + + beforeEach(async () => { + container = createTestContainer() + await installTestServices(container) + }) + + it('should handle cross-service communication', async () => { + const authService = container.get(SERVICE_TOKENS.AUTH_SERVICE) + const chatService = container.get(SERVICE_TOKENS.CHAT_SERVICE) + + await authService.login('test-key') + const message = await chatService.sendMessage('Hello') + + expect(message.author).toBe(authService.user.value?.pubkey) + }) +}) +``` + +## See Also + +### Service Documentation +- **[[authentication|๐Ÿ” Authentication Service]]** - User identity and session management +- **[[storage-service|๐Ÿ’พ Storage Service]]** - User-scoped data persistence +- **[[toast-service|๐Ÿ“ข Toast Service]]** - User notifications and feedback +- **[[visibility-service|๐Ÿ‘๏ธ Visibility Service]]** - Dynamic UI component control + +### Architecture References +- **[[../01-architecture/dependency-injection|โš™๏ธ Dependency Injection]]** - DI container system +- **[[../01-architecture/event-bus|๐Ÿ“ก Event Bus Communication]]** - Inter-service messaging +- **[[../02-modules/index|๐Ÿ“ฆ Module System]]** - How services integrate with modules +- **[[../04-development/testing|๐Ÿงช Testing Guide]]** - Service testing patterns + +--- + +**Tags:** #services #architecture #dependency-injection #reactive-state +**Last Updated:** 2025-09-06 +**Author:** Development Team \ No newline at end of file diff --git a/docs/VisibilityService-Integration.md b/docs/03-core-services/visibility-service-integration.md similarity index 100% rename from docs/VisibilityService-Integration.md rename to docs/03-core-services/visibility-service-integration.md diff --git a/docs/VisibilityService.md b/docs/03-core-services/visibility-service.md similarity index 100% rename from docs/VisibilityService.md rename to docs/03-core-services/visibility-service.md diff --git a/IMPROVEMENTS.md b/docs/04-development/improvements.md similarity index 100% rename from IMPROVEMENTS.md rename to docs/04-development/improvements.md diff --git a/docs/04-development/index.md b/docs/04-development/index.md new file mode 100644 index 0000000..61fa316 --- /dev/null +++ b/docs/04-development/index.md @@ -0,0 +1,571 @@ +# ๐Ÿ’ป Development Guide + +> **Development workflows and standards** for contributing to Ario's modular Vue 3 + TypeScript application with Nostr and Lightning Network integration. + +## Table of Contents + +- [[#Development Environment]] +- [[#Development Workflow]] +- [[#Code Standards]] +- [[#Testing Strategy]] +- [[#Build & Deployment]] +- [[#Debugging Guide]] + +## Development Environment + +### **Prerequisites** +- **Node.js 18+** and npm for package management +- **Git** for version control +- **VS Code** (recommended) with Vue and TypeScript extensions +- **Basic understanding** of Vue 3, TypeScript, and Nostr protocol + +### **Quick Setup** +```bash +# Navigate to web app directory +cd web-app/ + +# Install dependencies +npm install + +# Start development server with hot reload +npm run dev + +# For desktop development +npm run electron:dev +``` + +### **Environment Configuration** +```bash +# Copy environment template +cp .env.example .env + +# Essential configuration +VITE_NOSTR_RELAYS='["wss://relay.damus.io","wss://nos.lol"]' +VITE_ADMIN_PUBKEYS='["admin_pubkey_hex"]' + +# Optional configuration +VITE_DEBUG=true +VITE_APP_NAME="Ario Development" +``` + +### **Development Tools** + +#### **Recommended VS Code Extensions** +- **Vue Language Features (Volar)** - Vue 3 support +- **TypeScript Vue Plugin (Volar)** - TypeScript integration +- **Tailwind CSS IntelliSense** - CSS class completion +- **ESLint** - Code linting +- **Prettier** - Code formatting +- **Auto Rename Tag** - HTML tag synchronization + +#### **Browser Extensions** +- **Vue.js devtools** - Component inspection and debugging +- **Lightning Network Browser Extension** - WebLN testing + +### **Project Structure Overview** +``` +web-app/ +โ”œโ”€โ”€ src/ +โ”‚ โ”œโ”€โ”€ components/ # Reusable UI components +โ”‚ โ”œโ”€โ”€ composables/ # Vue composables and hooks +โ”‚ โ”œโ”€โ”€ core/ # Core architecture (DI, services) +โ”‚ โ”œโ”€โ”€ lib/ # Utility functions and helpers +โ”‚ โ”œโ”€โ”€ modules/ # Feature modules (plugin-based) +โ”‚ โ”œโ”€โ”€ pages/ # Route pages +โ”‚ โ”œโ”€โ”€ stores/ # Pinia state management +โ”‚ โ””โ”€โ”€ types/ # TypeScript type definitions +โ”œโ”€โ”€ docs/ # Documentation (Obsidian-style) +โ”œโ”€โ”€ public/ # Static assets +โ”œโ”€โ”€ electron/ # Electron main process +โ””โ”€โ”€ tests/ # Test files +``` + +## Development Workflow + +### **Feature Development Process** + +#### **1. Planning & Design** +- Review existing modules and services for reusable functionality +- Design module interfaces and dependencies +- Create or update relevant documentation + +#### **2. Implementation** +```bash +# Create feature branch +git checkout -b feature/my-new-feature + +# Implement feature following modular architecture +# - Create module plugin if needed +# - Implement services with BaseService pattern +# - Use dependency injection for service access +# - Follow TypeScript and Vue 3 best practices + +# Test implementation +npm run dev +npm run test:unit # If tests exist +``` + +#### **3. Code Review & Testing** +```bash +# Run quality checks +npm run build # Ensure TypeScript compilation +npm run lint # Check code style +npm run format # Auto-format code + +# Test across platforms +npm run preview # Test production build +npm run electron:dev # Test desktop version +``` + +#### **4. Documentation & Commit** +```bash +# Update relevant documentation +# Add JSDoc comments for public APIs +# Update CHANGELOG.md if applicable + +# Commit with conventional commits +git add . +git commit -m "feat: add new feature functionality" +``` + +### **Daily Development Tasks** + +#### **Starting Development Session** +```bash +cd web-app/ +npm run dev # Starts Vite dev server on http://localhost:5173 +``` + +#### **Development Server Features** +- **Hot Module Replacement (HMR)** - Instant updates without page reload +- **TypeScript Checking** - Compile-time error detection +- **Import Analysis** - Automatic dependency resolution +- **Source Maps** - Debug original TypeScript code in browser + +#### **Common Development Commands** +```bash +# Development +npm run dev # Start dev server +npm run dev:host # Dev server accessible on network + +# Building +npm run build # Production build with TypeScript check +npm run preview # Preview production build locally + +# Code Quality +npm run lint # ESLint checking +npm run lint:fix # Auto-fix linting issues +npm run format # Prettier formatting + +# Electron +npm run electron:dev # Concurrent Vite + Electron development +npm run electron:build # Package desktop application + +# Analysis +npm run analyze # Bundle analyzer +``` + +## Code Standards + +### **TypeScript Guidelines** + +#### **Strict Type Checking** +```typescript +// โœ… Use explicit types for public APIs +interface UserProfile { + pubkey: string + name?: string + about?: string +} + +// โœ… Use type guards for runtime validation +function isNostrEvent(obj: unknown): obj is NostrEvent { + return typeof obj === 'object' && obj !== null && 'kind' in obj +} + +// โŒ Avoid 'any' type +function processData(data: any): any { } + +// โœ… Use proper generic constraints +function processData(data: T): T { } +``` + +#### **Interface vs Type Preferences** +```typescript +// โœ… Use interfaces for extensible objects +interface ModulePlugin { + name: string + install(app: App): Promise +} + +interface MyModulePlugin extends ModulePlugin { + customConfig?: MyConfig +} + +// โœ… Use type aliases for unions and computations +type EventKind = 0 | 1 | 3 | 4 | 5 | 6 | 7 +type ServiceToken = keyof typeof SERVICE_TOKENS +``` + +### **Vue 3 Patterns** + +#### **Composition API with Script Setup** +```vue + +``` + +#### **Service Integration** +```vue + +``` + +### **Module Development Standards** + +#### **Module Structure** +```typescript +// โœ… Proper module plugin implementation +export const myModule: ModulePlugin = { + name: 'my-module', + version: '1.0.0', + dependencies: ['base'], // Always depend on base + + async install(app: App, options?: MyModuleConfig) { + // Register services + const myService = new MyService() + container.provide(SERVICE_TOKENS.MY_SERVICE, myService) + + // Register components + app.component('MyComponent', MyComponent) + + // Initialize + await myService.initialize() + }, + + routes: [ + { + path: '/my-feature', + component: () => import('./views/MyFeatureView.vue') + } + ] +} +``` + +#### **Service Development** +```typescript +// โœ… Extend BaseService for consistency +export class MyService extends BaseService { + private readonly _data = ref([]) + public readonly data = readonly(this._data) + + constructor( + private auth = injectService(SERVICE_TOKENS.AUTH_SERVICE) + ) { + super() + } + + async initialize(): Promise { + // Initialization logic + this.isInitialized.value = true + } + + async dispose(): Promise { + // Cleanup logic + this.isDisposed.value = true + } +} +``` + +### **Naming Conventions** + +#### **Files and Directories** +``` +# โœ… Use kebab-case for files and directories +my-component.vue +my-service.ts +my-module-config.ts + +# โœ… Component files use PascalCase base name +UserProfileCard.vue +EventTicketPurchase.vue +``` + +#### **Variables and Functions** +```typescript +// โœ… Use camelCase for variables and functions +const userName = ref('') +const isAuthenticated = computed(() => !!user.value) + +async function handleUserLogin(): Promise { } + +// โœ… Use PascalCase for classes and interfaces +class AuthService extends BaseService { } +interface UserProfile { } +``` + +#### **Constants and Types** +```typescript +// โœ… Use SCREAMING_SNAKE_CASE for constants +const MAX_MESSAGE_LENGTH = 1000 +const DEFAULT_RELAY_URLS = ['wss://relay.example.com'] + +// โœ… Use PascalCase for types and enums +type NostrEventKind = 0 | 1 | 3 | 4 +enum ConnectionStatus { Connected, Connecting, Disconnected } +``` + +## Testing Strategy + +### **Testing Philosophy** +- **Unit Tests** - Test individual components and services in isolation +- **Integration Tests** - Test service interactions and module integration +- **E2E Tests** - Test complete user workflows (planned) +- **Manual Testing** - Cross-platform testing and user experience validation + +### **Unit Testing Setup** +```typescript +// tests/unit/services/MyService.test.ts +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { MyService } from '@/services/MyService' +import { createMockDIContainer } from '@/tests/helpers' + +describe('MyService', () => { + let service: MyService + let mockAuth: MockAuthService + + beforeEach(() => { + const container = createMockDIContainer() + mockAuth = container.get(SERVICE_TOKENS.AUTH_SERVICE) + service = new MyService() + }) + + afterEach(async () => { + await service.dispose() + }) + + it('should initialize correctly', async () => { + await service.initialize() + expect(service.isInitialized.value).toBe(true) + }) +}) +``` + +### **Component Testing** +```typescript +// tests/unit/components/MyComponent.test.ts +import { mount } from '@vue/test-utils' +import { createMockDIContainer } from '@/tests/helpers' +import MyComponent from '@/components/MyComponent.vue' + +describe('MyComponent', () => { + it('should render correctly', () => { + const wrapper = mount(MyComponent, { + props: { userId: 'test-user' }, + global: { + plugins: [createMockDIContainer()] + } + }) + + expect(wrapper.text()).toContain('test-user') + }) +}) +``` + +## Build & Deployment + +### **Development Builds** +```bash +# Development server (with HMR) +npm run dev + +# Development build (for debugging) +npm run build:dev +``` + +### **Production Builds** +```bash +# Full production build +npm run build + +# Preview production build locally +npm run preview + +# Bundle analysis +npm run analyze +``` + +### **Electron Builds** +```bash +# Development +npm run electron:dev + +# Production packaging +npm run electron:build + +# Platform-specific builds +npm run build:win # Windows +npm run build:mac # macOS +npm run build:linux # Linux +``` + +### **Build Configuration** + +#### **Vite Configuration** (`vite.config.ts`) +- **TypeScript compilation** with vue-tsc +- **Bundle optimization** with manual chunking +- **PWA integration** with service worker +- **Asset optimization** with image processing + +#### **Electron Configuration** (`forge.config.js`) +- **Cross-platform packaging** with Electron Forge +- **Auto-updater integration** for seamless updates +- **Code signing** for distribution (production) + +## Debugging Guide + +### **Development Debugging** + +#### **Vue DevTools** +- Install Vue DevTools browser extension +- Inspect component state and props +- Monitor Pinia store mutations +- Track component lifecycle events + +#### **Browser Developer Tools** +- Use TypeScript source maps for original code debugging +- Network tab for Nostr relay communication +- Console tab for service logging +- Application tab for localStorage inspection + +#### **Service Debugging** +```typescript +// Add debug logging to services +export class MyService extends BaseService { + private debug = (message: string, ...args: unknown[]) => { + if (import.meta.env.VITE_DEBUG) { + console.log(`[MyService] ${message}`, ...args) + } + } + + async performAction(): Promise { + this.debug('Performing action...') + // Implementation + this.debug('Action completed') + } +} +``` + +### **Nostr Debugging** + +#### **Relay Communication** +```typescript +// Log Nostr events for debugging +const relayHub = injectService(SERVICE_TOKENS.RELAY_HUB) + +relayHub.subscribe(filters, (event) => { + console.log('Received Nostr event:', event) +}) + +// Debug relay connections +console.log('Connected relays:', relayHub.connectedRelays.value) +``` + +#### **Event Publishing** +```typescript +// Debug event publishing +try { + await relayHub.publishEvent(event) + console.log('Event published successfully:', event) +} catch (error) { + console.error('Failed to publish event:', error) +} +``` + +### **Common Issues & Solutions** + +#### **TypeScript Errors** +```bash +# Clear TypeScript cache +rm -rf node_modules/.cache +rm -rf dist + +# Restart TypeScript language server in VS Code +Cmd/Ctrl + Shift + P > "TypeScript: Restart TS Server" +``` + +#### **Module Import Issues** +```typescript +// โŒ Incorrect relative import +import { MyService } from '../../services/MyService' + +// โœ… Use absolute imports with @ alias +import { MyService } from '@/services/MyService' +``` + +#### **Dependency Injection Issues** +```typescript +// โŒ Service not registered +const service = injectService(SERVICE_TOKENS.MY_SERVICE) // Error! + +// โœ… Ensure service is registered in module installation +container.provide(SERVICE_TOKENS.MY_SERVICE, new MyService()) +``` + +## See Also + +### Development Documentation +- **[[setup|๐Ÿ› ๏ธ Environment Setup]]** - Detailed setup instructions +- **[[coding-standards|๐Ÿ“‹ Coding Standards]]** - Comprehensive style guide +- **[[testing|๐Ÿงช Testing Guide]]** - Testing frameworks and patterns +- **[[debugging|๐Ÿ› Debugging Techniques]]** - Advanced debugging strategies + +### Architecture References +- **[[../02-modules/index|๐Ÿ“ฆ Module System]]** - Plugin-based architecture +- **[[../03-core-services/index|โš™๏ธ Core Services]]** - Service development patterns +- **[[../01-architecture/dependency-injection|โš™๏ธ Dependency Injection]]** - DI container usage + +--- + +**Tags:** #development #workflow #standards #testing #debugging +**Last Updated:** 2025-09-06 +**Author:** Development Team \ No newline at end of file diff --git a/MOBILE_RELAY_EVALUATION.md b/docs/04-development/mobile-relay-evaluation.md similarity index 100% rename from MOBILE_RELAY_EVALUATION.md rename to docs/04-development/mobile-relay-evaluation.md diff --git a/TODO.md b/docs/04-development/todo.md similarity index 100% rename from TODO.md rename to docs/04-development/todo.md diff --git a/docs/05-api-reference/index.md b/docs/05-api-reference/index.md new file mode 100644 index 0000000..a7ec468 --- /dev/null +++ b/docs/05-api-reference/index.md @@ -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 + getInfo(): Promise + sendPayment(paymentRequest: string): Promise + makeInvoice(args: RequestInvoiceArgs): Promise + signMessage(message: string): Promise +} + +// Payment workflow +async function processLightningPayment(invoice: string): Promise { + 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 { + 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 { + return encrypt(senderPrivkey, recipientPubkey, message) +} +``` + +### **Storage Services** +**Browser APIs:** localStorage, IndexedDB +**Abstraction:** StorageService with user-scoped keys + +```typescript +interface StorageService { + // User-scoped operations + setUserData(key: string, data: T): void + getUserData(key: string, defaultValue?: T): T | undefined + removeUserData(key: string): void + clearUserData(): void + + // Global application data + setAppData(key: string, data: T): void + getAppData(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([]) + + 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 + + // Session management + login(privateKey: string, remember?: boolean): Promise + logout(): Promise + + // 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 \ No newline at end of file diff --git a/web-app-specification.md b/docs/05-api-reference/specifications.md similarity index 100% rename from web-app-specification.md rename to docs/05-api-reference/specifications.md diff --git a/docs/06-deployment/index.md b/docs/06-deployment/index.md new file mode 100644 index 0000000..99c1241 --- /dev/null +++ b/docs/06-deployment/index.md @@ -0,0 +1,663 @@ +# ๐Ÿš€ Deployment Guide + +> **Production deployment and operations** for Ario's web application, desktop app, and Progressive Web App across multiple platforms and environments. + +## Table of Contents + +- [[#Deployment Options]] +- [[#Production Build Process]] +- [[#Environment Configuration]] +- [[#Platform-Specific Deployment]] +- [[#Monitoring & Maintenance]] +- [[#Security Considerations]] + +## Deployment Options + +### **Web Application (SPA)** +- **Static Hosting** - Deploy to CDN or static hosting service +- **Traditional Web Server** - Nginx, Apache, or similar +- **Cloud Platforms** - Vercel, Netlify, Cloudflare Pages +- **Container Deployment** - Docker with web server + +### **Progressive Web App (PWA)** +- **Service Worker** - Offline capabilities and caching +- **App Manifest** - Installation and app-like experience +- **Push Notifications** - Real-time updates (future feature) +- **Background Sync** - Offline data synchronization + +### **Desktop Application** +- **Electron** - Cross-platform desktop packaging +- **Platform-Specific** - Windows MSI, macOS DMG, Linux AppImage/Snap +- **Auto-Update** - Seamless application updates +- **Code Signing** - Security and trust verification + +### **Self-Hosted** +- **Full Control** - Complete control over infrastructure +- **Privacy** - No third-party hosting dependencies +- **Custom Configuration** - Tailored environment variables and settings +- **Local Development** - Internal network deployment + +## Production Build Process + +### **Build Commands** +```bash +# Standard web build +npm run build + +# Build with analysis +npm run analyze + +# Electron desktop build +npm run electron:build + +# Platform-specific builds +npm run build:win # Windows +npm run build:mac # macOS +npm run build:linux # Linux +``` + +### **Build Configuration** + +#### **Vite Production Config** +```typescript +// vite.config.ts - Production optimizations +export default defineConfig({ + build: { + target: 'es2020', + minify: 'terser', + sourcemap: false, // Disable in production + chunkSizeWarningLimit: 600, + + rollupOptions: { + output: { + manualChunks: { + 'vue-vendor': ['vue', 'vue-router', 'pinia'], + 'ui-vendor': ['@headlessui/vue', '@heroicons/vue'], + 'nostr-vendor': ['nostr-tools'], + 'crypto-vendor': ['crypto-js'] + } + } + } + } +}) +``` + +#### **Build Optimization** +- **Tree Shaking** - Remove unused code +- **Code Splitting** - Lazy load modules and routes +- **Asset Optimization** - Compress images and fonts +- **Bundle Analysis** - Monitor bundle size and dependencies + +### **Build Output Structure** +``` +dist/ +โ”œโ”€โ”€ index.html # Entry point +โ”œโ”€โ”€ assets/ # Static assets with hashed names +โ”‚ โ”œโ”€โ”€ index-[hash].js # Main application bundle +โ”‚ โ”œโ”€โ”€ vendor-[hash].js # Vendor dependencies +โ”‚ โ””โ”€โ”€ [module]-[hash].js # Module-specific bundles +โ”œโ”€โ”€ icons/ # PWA icons +โ”œโ”€โ”€ manifest.json # PWA manifest +โ””โ”€โ”€ sw.js # Service worker +``` + +## Environment Configuration + +### **Environment Variables** + +#### **Production Environment (.env.production)** +```bash +# Application Configuration +VITE_APP_NAME="Ario" +VITE_APP_VERSION="1.0.0" +VITE_BASE_URL="/" + +# Nostr Configuration +VITE_NOSTR_RELAYS='["wss://relay.damus.io","wss://nos.lol","wss://relay.snort.social"]' +VITE_ADMIN_PUBKEYS='["admin_pubkey_1","admin_pubkey_2"]' + +# Lightning Configuration (if using LNbits) +VITE_LNBITS_URL="https://your-lnbits-instance.com" +VITE_LNBITS_ADMIN_KEY="" # Only for invoice creation + +# Security & Performance +VITE_DEBUG=false +VITE_ENABLE_PWA=true +VITE_ENABLE_ANALYTICS=true + +# Optional Features +VITE_ENABLE_NOTIFICATIONS=true +VITE_MAX_RELAY_CONNECTIONS=10 +VITE_EVENT_CACHE_SIZE=1000 +``` + +#### **Configuration Validation** +```typescript +// src/config/production.ts +export const productionConfig = { + app: { + name: import.meta.env.VITE_APP_NAME || 'Ario', + version: import.meta.env.VITE_APP_VERSION || '1.0.0', + baseUrl: import.meta.env.VITE_BASE_URL || '/', + }, + + nostr: { + relays: JSON.parse(import.meta.env.VITE_NOSTR_RELAYS || '[]'), + adminPubkeys: JSON.parse(import.meta.env.VITE_ADMIN_PUBKEYS || '[]'), + maxConnections: Number(import.meta.env.VITE_MAX_RELAY_CONNECTIONS) || 10, + }, + + features: { + debug: import.meta.env.VITE_DEBUG === 'true', + pwa: import.meta.env.VITE_ENABLE_PWA === 'true', + notifications: import.meta.env.VITE_ENABLE_NOTIFICATIONS === 'true', + } +} + +// Validate required configuration +if (!productionConfig.nostr.relays.length) { + throw new Error('VITE_NOSTR_RELAYS must be configured') +} +``` + +### **Security Configuration** + +#### **Content Security Policy (CSP)** +```html + + +``` + +#### **Security Headers (nginx example)** +```nginx +# nginx.conf security headers +add_header X-Frame-Options DENY; +add_header X-Content-Type-Options nosniff; +add_header X-XSS-Protection "1; mode=block"; +add_header Referrer-Policy "strict-origin-when-cross-origin"; +add_header Permissions-Policy "geolocation=(), microphone=(), camera=()"; +``` + +## Platform-Specific Deployment + +### **Web Hosting - Vercel** + +#### **vercel.json Configuration** +```json +{ + "buildCommand": "npm run build", + "outputDirectory": "dist", + "framework": "vite", + "rewrites": [ + { + "source": "/((?!api/).*)", + "destination": "/index.html" + } + ], + "headers": [ + { + "source": "/(.*)", + "headers": [ + { + "key": "X-Frame-Options", + "value": "DENY" + }, + { + "key": "X-Content-Type-Options", + "value": "nosniff" + } + ] + } + ] +} +``` + +#### **Deployment Steps** +```bash +# 1. Install Vercel CLI +npm i -g vercel + +# 2. Deploy to Vercel +vercel --prod + +# 3. Set environment variables in Vercel dashboard +# - VITE_NOSTR_RELAYS +# - VITE_ADMIN_PUBKEYS +# - Other configuration variables +``` + +### **Web Hosting - Netlify** + +#### **netlify.toml Configuration** +```toml +[build] + command = "npm run build" + publish = "dist" + +[[redirects]] + from = "/*" + to = "/index.html" + status = 200 + +[build.environment] + NODE_VERSION = "18" + +[[headers]] + for = "/*" + [headers.values] + X-Frame-Options = "DENY" + X-XSS-Protection = "1; mode=block" + X-Content-Type-Options = "nosniff" +``` + +### **Self-Hosted - Docker** + +#### **Dockerfile** +```dockerfile +# Multi-stage build for production +FROM node:18-alpine AS builder + +WORKDIR /app +COPY package*.json ./ +RUN npm ci --only=production + +COPY . . +RUN npm run build + +# Production stage +FROM nginx:alpine + +# Copy built application +COPY --from=builder /app/dist /usr/share/nginx/html + +# Copy nginx configuration +COPY docker/nginx.conf /etc/nginx/nginx.conf + +# Expose port +EXPOSE 80 + +CMD ["nginx", "-g", "daemon off;"] +``` + +#### **Docker Compose** +```yaml +# docker-compose.yml +version: '3.8' + +services: + ario-web: + build: . + ports: + - "80:80" + environment: + - VITE_NOSTR_RELAYS=["wss://relay.damus.io"] + - VITE_ADMIN_PUBKEYS=["your_admin_pubkey"] + volumes: + - ./nginx.conf:/etc/nginx/nginx.conf:ro + restart: unless-stopped +``` + +### **Desktop Application** + +#### **Electron Forge Configuration** +```javascript +// forge.config.js +module.exports = { + packagerConfig: { + name: 'Ario', + executableName: 'ario', + icon: './src/assets/icon', + asar: true, + + // Code signing (production) + osxSign: { + identity: process.env.APPLE_IDENTITY, + 'hardened-runtime': true, + entitlements: './entitlements.plist', + 'entitlements-inherit': './entitlements.plist' + }, + + osxNotarize: { + tool: 'notarytool', + appleId: process.env.APPLE_ID, + appleIdPassword: process.env.APPLE_PASSWORD, + teamId: process.env.APPLE_TEAM_ID + } + }, + + makers: [ + { + name: '@electron-forge/maker-squirrel', + config: { + name: 'ario', + setupIcon: './src/assets/icon.ico' + } + }, + { + name: '@electron-forge/maker-dmg', + config: { + format: 'ULFO', + icon: './src/assets/icon.icns' + } + }, + { + name: '@electron-forge/maker-deb', + config: { + options: { + maintainer: 'Ario Team', + homepage: 'https://ario.app' + } + } + } + ], + + publishers: [ + { + name: '@electron-forge/publisher-github', + config: { + repository: { + owner: 'your-org', + name: 'ario' + }, + prerelease: false + } + } + ] +} +``` + +#### **Auto-Update Configuration** +```typescript +// electron/main.ts - Auto-updater setup +import { autoUpdater } from 'electron-updater' + +if (!app.isPackaged) { + autoUpdater.updateConfigPath = path.join(__dirname, 'dev-app-update.yml') +} + +autoUpdater.checkForUpdatesAndNotify() + +autoUpdater.on('update-available', () => { + dialog.showMessageBox(mainWindow, { + type: 'info', + title: 'Update Available', + message: 'A new version is available. It will be downloaded in the background.', + buttons: ['OK'] + }) +}) +``` + +## Monitoring & Maintenance + +### **Performance Monitoring** + +#### **Web Vitals Tracking** +```typescript +// src/utils/analytics.ts +import { getCLS, getFID, getFCP, getLCP, getTTFB } from 'web-vitals' + +export function initPerformanceMonitoring() { + if (import.meta.env.VITE_ENABLE_ANALYTICS) { + getCLS(sendToAnalytics) + getFID(sendToAnalytics) + getFCP(sendToAnalytics) + getLCP(sendToAnalytics) + getTTFB(sendToAnalytics) + } +} + +function sendToAnalytics(metric: any) { + // Send to your analytics service + console.log('Performance metric:', metric) +} +``` + +#### **Application Health Monitoring** +```typescript +// src/services/HealthMonitor.ts +export class HealthMonitor extends BaseService { + private healthStatus = ref({ + relayConnections: 0, + lastEventReceived: null as Date | null, + memoryUsage: 0, + errorCount: 0 + }) + + async initialize(): Promise { + setInterval(() => this.checkHealth(), 30000) // Every 30 seconds + } + + private checkHealth(): void { + const relayHub = injectService(SERVICE_TOKENS.RELAY_HUB) + + this.healthStatus.value = { + relayConnections: relayHub.connectedRelays.value.length, + lastEventReceived: this.getLastEventTime(), + memoryUsage: this.getMemoryUsage(), + errorCount: this.getErrorCount() + } + + // Alert if critical issues detected + if (this.healthStatus.value.relayConnections === 0) { + console.warn('No relay connections available') + } + } +} +``` + +### **Error Tracking** + +#### **Global Error Handler** +```typescript +// src/utils/errorHandler.ts +export function setupGlobalErrorHandler() { + window.addEventListener('error', (event) => { + console.error('Global error:', event.error) + + // Send to error tracking service + if (import.meta.env.VITE_ERROR_TRACKING) { + sendErrorToService(event.error) + } + }) + + window.addEventListener('unhandledrejection', (event) => { + console.error('Unhandled promise rejection:', event.reason) + sendErrorToService(event.reason) + }) +} +``` + +### **Logging Strategy** + +#### **Production Logging** +```typescript +// src/utils/logger.ts +class Logger { + private shouldLog(level: LogLevel): boolean { + if (import.meta.env.PROD && level === 'debug') return false + return true + } + + info(message: string, ...args: unknown[]): void { + if (this.shouldLog('info')) { + console.log(`[INFO] ${message}`, ...args) + } + } + + error(message: string, error?: Error, ...args: unknown[]): void { + if (this.shouldLog('error')) { + console.error(`[ERROR] ${message}`, error, ...args) + + // Send to error tracking in production + if (import.meta.env.PROD && error) { + this.sendToErrorTracking(message, error) + } + } + } + + private sendToErrorTracking(message: string, error: Error): void { + // Implementation for error tracking service + } +} + +export const logger = new Logger() +``` + +## Security Considerations + +### **Client-Side Security** + +#### **Key Storage Security** +```typescript +// src/utils/keyStorage.ts +export class SecureKeyStorage { + private static readonly STORAGE_KEY = 'ario_encrypted_keys' + + static async storeEncryptedKey(privateKey: string, passphrase: string): Promise { + const encrypted = await this.encrypt(privateKey, passphrase) + localStorage.setItem(this.STORAGE_KEY, encrypted) + } + + static async retrieveDecryptedKey(passphrase: string): Promise { + const encrypted = localStorage.getItem(this.STORAGE_KEY) + if (!encrypted) return null + + try { + return await this.decrypt(encrypted, passphrase) + } catch { + return null // Invalid passphrase + } + } + + private static async encrypt(data: string, passphrase: string): Promise { + // Use Web Crypto API for encryption + const encoder = new TextEncoder() + const key = await window.crypto.subtle.importKey( + 'raw', + encoder.encode(passphrase), + { name: 'PBKDF2' }, + false, + ['deriveKey'] + ) + + // Implementation details... + return encryptedData + } +} +``` + +#### **Input Validation** +```typescript +// src/utils/validation.ts +export const validators = { + nostrPublicKey: (pubkey: string): boolean => { + return /^[0-9a-f]{64}$/i.test(pubkey) + }, + + nostrPrivateKey: (privkey: string): boolean => { + return /^[0-9a-f]{64}$/i.test(privkey) + }, + + lightningInvoice: (invoice: string): boolean => { + return /^(lnbc|lntb|lnbcrt)[0-9]+[munp]?[0-9a-z]+$/i.test(invoice) + }, + + sanitizeContent: (content: string): string => { + // Sanitize user-generated content + return content + .replace(/)<[^<]*)*<\/script>/gi, '') + .replace(/javascript:/gi, '') + .trim() + } +} +``` + +### **Deployment Security** + +#### **HTTPS Enforcement** +```nginx +# nginx.conf - Force HTTPS +server { + listen 80; + server_name ario.app www.ario.app; + return 301 https://$server_name$request_uri; +} + +server { + listen 443 ssl http2; + server_name ario.app www.ario.app; + + ssl_certificate /path/to/cert.pem; + ssl_certificate_key /path/to/private.key; + + # Security headers + add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always; + add_header X-Frame-Options DENY always; + add_header X-Content-Type-Options nosniff always; + + location / { + root /usr/share/nginx/html; + try_files $uri $uri/ /index.html; + } +} +``` + +### **Privacy Protection** + +#### **Data Minimization** +- **No Server Storage** - All user data stored client-side +- **Ephemeral Sessions** - No persistent server-side sessions +- **Optional Analytics** - Analytics can be disabled by users +- **Relay Privacy** - Users can configure their own relays + +#### **User Privacy Controls** +```typescript +// src/services/PrivacyService.ts +export class PrivacyService extends BaseService { + private settings = ref({ + shareAnalytics: false, + shareErrorReports: false, + allowLocationTracking: false, + publicProfile: false + }) + + updatePrivacySettings(updates: Partial): void { + this.settings.value = { ...this.settings.value, ...updates } + + // Apply privacy settings immediately + if (!this.settings.value.shareAnalytics) { + this.disableAnalytics() + } + + if (!this.settings.value.shareErrorReports) { + this.disableErrorReporting() + } + } +} +``` + +## See Also + +### Configuration Documentation +- **[[configuration|โš™๏ธ Environment Configuration]]** - Detailed configuration options +- **[[pwa-setup|๐Ÿ“ฑ PWA Configuration]]** - Progressive Web App setup +- **[[electron|๐Ÿ–ฅ๏ธ Desktop App Packaging]]** - Electron configuration and distribution + +### Operations Documentation +- **[[../04-development/index|๐Ÿ’ป Development Guide]]** - Development environment setup +- **[[../05-api-reference/index|๐Ÿ“ก API Reference]]** - External service integrations +- **[[../01-architecture/index|๐Ÿ—๏ธ Architecture Overview]]** - System architecture principles + +--- + +**Tags:** #deployment #production #security #monitoring #pwa #electron +**Last Updated:** 2025-09-06 +**Author:** Development Team \ No newline at end of file diff --git a/docs/README.md b/docs/README.md new file mode 100644 index 0000000..1a7102a --- /dev/null +++ b/docs/README.md @@ -0,0 +1,175 @@ +# ๐Ÿ“š Ario Web App Documentation + +> **A comprehensive guide to the Ario Web Application** - A modular Vue 3 + TypeScript application with Nostr protocol integration and Lightning Network payments. + +## ๐Ÿ—‚๏ธ Documentation Structure + +This documentation follows an Obsidian-compatible structure with cross-linked markdown files organized by domain. + +### Quick Navigation + +- **[[00-overview/index|๐Ÿ“– Overview]]** - Start here for project introduction +- **[[01-architecture/index|๐Ÿ—๏ธ Architecture]]** - System design and patterns +- **[[02-modules/index|๐Ÿ“ฆ Modules]]** - Feature module documentation +- **[[03-core-services/index|โš™๏ธ Core Services]]** - Shared infrastructure +- **[[04-development/index|๐Ÿ’ป Development]]** - Setup and guidelines +- **[[05-api-reference/index|๐Ÿ“ก API Reference]]** - External integrations +- **[[06-deployment/index|๐Ÿš€ Deployment]]** - Production setup + +## ๐Ÿ“‚ Directory Structure + +``` +docs/ +โ”œโ”€โ”€ README.md # This file - Documentation hub +โ”œโ”€โ”€ 00-overview/ # Project overview and introduction +โ”‚ โ”œโ”€โ”€ index.md # Overview index +โ”‚ โ”œโ”€โ”€ project-goals.md # Project objectives +โ”‚ โ”œโ”€โ”€ tech-stack.md # Technology choices +โ”‚ โ””โ”€โ”€ getting-started.md # Quick start guide +โ”‚ +โ”œโ”€โ”€ 01-architecture/ # System architecture +โ”‚ โ”œโ”€โ”€ index.md # Architecture overview +โ”‚ โ”œโ”€โ”€ modular-design.md # Modular architecture patterns +โ”‚ โ”œโ”€โ”€ dependency-injection.md # DI container system +โ”‚ โ”œโ”€โ”€ event-bus.md # Inter-module communication +โ”‚ โ””โ”€โ”€ relay-hub.md # Nostr relay management +โ”‚ +โ”œโ”€โ”€ 02-modules/ # Feature modules +โ”‚ โ”œโ”€โ”€ index.md # Module system overview +โ”‚ โ”œโ”€โ”€ base-module/ # Core infrastructure module +โ”‚ โ”œโ”€โ”€ market-module/ # Marketplace functionality +โ”‚ โ”œโ”€โ”€ chat-module/ # Encrypted chat system +โ”‚ โ”œโ”€โ”€ events-module/ # Event ticketing +โ”‚ โ””โ”€โ”€ nostr-feed-module/ # Social feed +โ”‚ +โ”œโ”€โ”€ 03-core-services/ # Shared services +โ”‚ โ”œโ”€โ”€ index.md # Services overview +โ”‚ โ”œโ”€โ”€ authentication.md # Auth service & LNbits +โ”‚ โ”œโ”€โ”€ payment-service.md # Lightning payments +โ”‚ โ”œโ”€โ”€ storage-service.md # User-scoped storage +โ”‚ โ”œโ”€โ”€ toast-service.md # Notifications +โ”‚ โ””โ”€โ”€ visibility-service.md # Component visibility +โ”‚ +โ”œโ”€โ”€ 04-development/ # Development guides +โ”‚ โ”œโ”€โ”€ index.md # Development overview +โ”‚ โ”œโ”€โ”€ setup.md # Environment setup +โ”‚ โ”œโ”€โ”€ coding-standards.md # Code conventions +โ”‚ โ”œโ”€โ”€ testing.md # Testing strategies +โ”‚ โ””โ”€โ”€ debugging.md # Debug techniques +โ”‚ +โ”œโ”€โ”€ 05-api-reference/ # External APIs +โ”‚ โ”œโ”€โ”€ index.md # API overview +โ”‚ โ”œโ”€โ”€ nostr-protocol.md # Nostr implementation +โ”‚ โ”œโ”€โ”€ lnbits-api.md # LNbits integration +โ”‚ โ””โ”€โ”€ events-api.md # Events system API +โ”‚ +โ”œโ”€โ”€ 06-deployment/ # Deployment & operations +โ”‚ โ”œโ”€โ”€ index.md # Deployment overview +โ”‚ โ”œโ”€โ”€ configuration.md # Environment variables +โ”‚ โ”œโ”€โ”€ pwa-setup.md # PWA configuration +โ”‚ โ””โ”€โ”€ electron.md # Desktop app packaging +โ”‚ +โ””โ”€โ”€ archive/ # Deprecated documentation + โ”œโ”€โ”€ legacy-architecture.md + โ””โ”€โ”€ old-relay-system.md +``` + +## ๐Ÿ”— Key Documentation Files + +### Essential Reading +1. **[[00-overview/getting-started|Getting Started]]** - Set up your development environment +2. **[[01-architecture/modular-design|Modular Architecture]]** - Understand the plugin system +3. **[[02-modules/index|Module Development]]** - Create new feature modules +4. **[[04-development/coding-standards|Coding Standards]]** - Maintain code quality + +### Module Documentation +- **[[02-modules/base-module/index|Base Module]]** - Core infrastructure (Nostr, Auth, PWA) +- **[[02-modules/market-module/index|Market Module]]** - Nostr marketplace implementation +- **[[02-modules/chat-module/index|Chat Module]]** - Encrypted DM system +- **[[02-modules/events-module/index|Events Module]]** - Lightning ticketing system +- **[[02-modules/nostr-feed-module/index|Nostr Feed]]** - Social feed functionality + +### Technical Deep Dives +- **[[01-architecture/relay-hub|Relay Hub Architecture]]** - Centralized Nostr relay management +- **[[01-architecture/dependency-injection|Dependency Injection]]** - Service container patterns +- **[[03-core-services/visibility-service|Visibility Service]]** - Dynamic UI control + +## ๐Ÿท๏ธ Documentation Tags + +Documents are tagged for easy navigation: +- `#architecture` - System design documents +- `#module` - Feature module documentation +- `#service` - Service layer documentation +- `#api` - External API references +- `#guide` - How-to guides +- `#reference` - Technical references +- `#deprecated` - Outdated documentation + +## ๐Ÿ“ Documentation Standards + +### File Naming +- Use kebab-case for all files: `module-name.md` +- Index files for directories: `index.md` +- Prefix with numbers for ordering: `01-architecture/` + +### Markdown Structure +```markdown +# Document Title + +> Brief description or important note + +## Overview +Introduction to the topic + +## Table of Contents +- [[#Section 1]] +- [[#Section 2]] + +## Section 1 +Content... + +## See Also +- [[related-document]] +- [[another-reference]] + +--- +**Tags:** #architecture #module +**Last Updated:** 2025-09-06 +**Author:** Development Team +``` + +### Cross-Linking +- Use `[[filename]]` for internal links (Obsidian-style) +- Use `[[filename#section]]` for section links +- Use `[[filename|Display Text]]` for custom link text + +## ๐Ÿ”„ Maintenance + +### Keeping Documentation Current +1. Update documentation with code changes +2. Review quarterly for accuracy +3. Move deprecated docs to `archive/` +4. Tag documents with last update date + +### Contributing +1. Follow the structure and standards above +2. Add appropriate tags to new documents +3. Update index files when adding new docs +4. Cross-link related documentation + +## ๐Ÿ“Š Documentation Coverage + +| Module | Status | Coverage | +|--------|--------|----------| +| Base Module | โœ… Complete | 100% | +| Market Module | โœ… Complete | 100% | +| Chat Module | โœ… Complete | 100% | +| Events Module | โœ… Complete | 100% | +| Nostr Feed | โœ… Complete | 100% | +| Core Services | โœ… Complete | 100% | +| Development Guides | ๐Ÿ”„ In Progress | 80% | +| API Reference | ๐Ÿ”„ In Progress | 70% | + +--- + +**Welcome to the Ario Web App documentation!** Start with the [[00-overview/index|Overview]] to begin your journey. \ No newline at end of file diff --git a/ARCHITECTURE_ANALYSIS_PRINT.md b/docs/archive/ARCHITECTURE_ANALYSIS_PRINT.md similarity index 100% rename from ARCHITECTURE_ANALYSIS_PRINT.md rename to docs/archive/ARCHITECTURE_ANALYSIS_PRINT.md diff --git a/ARCHITECTURE_ANALYSIS.md b/docs/archive/legacy-architecture-analysis.md similarity index 100% rename from ARCHITECTURE_ANALYSIS.md rename to docs/archive/legacy-architecture-analysis.md diff --git a/NOSTR_ARCHITECTURE.md b/docs/archive/legacy-nostr-architecture.md similarity index 100% rename from NOSTR_ARCHITECTURE.md rename to docs/archive/legacy-nostr-architecture.md diff --git a/docs/modular-architecture-analysis.pdf b/docs/modular-architecture-analysis.pdf deleted file mode 100644 index 7b210d9..0000000 Binary files a/docs/modular-architecture-analysis.pdf and /dev/null differ