41 Commits

Author SHA1 Message Date
0aa9921941 Release v0.17.0: Phase 1 & 2 improvements, documentation restructuring 2025-12-13 13:18:43 +01:00
5fc20f1be9 Remove Node.js Host Guide references
Remove all references to NODE_HOST_GUIDE.md and test-connect.js:
- README.md: Removed Node.js Host Guide section and links
- ADVANCED.md: Simplified Node.js example, removed guide references

Keep inline Node.js example code for reference.

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-12 23:24:56 +01:00
54c371f451 Fix broken relative links to demo repository
Change relative paths to absolute GitHub URLs:
- ../demo/NODE_HOST_GUIDE.md → github.com/xtr-dev/rondevu-demo/blob/main/NODE_HOST_GUIDE.md
- ../demo/test-connect.js → github.com/xtr-dev/rondevu-demo/blob/main/test-connect.js

Affected files:
- README.md (2 links fixed)
- ADVANCED.md (2 links fixed)

Why: Client and demo are separate repositories, so relative paths
don't work when viewing on GitHub. Now links work from anywhere.

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-12 23:18:50 +01:00
5f4743e086 Make README more concise with ADVANCED.md
Restructure documentation for better discoverability:

Changes:
- README.md: 551 → 181 lines (67% reduction)
- ADVANCED.md: New comprehensive guide (500+ lines)

README.md now contains:
 Features overview
 Installation
 Quick start examples (offerer & answerer)
 Core API summary
 Links to advanced docs

ADVANCED.md contains:
📚 Complete API reference (all methods)
📚 Type definitions
📚 Platform support details (Browser & Node.js)
📚 Advanced usage patterns
📚 Username rules and FQN format
📚 Migration guides
📚 Examples

Benefits:
- Faster onboarding for new users
- Essential info in README
- Detailed reference still accessible
- Better documentation structure

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-12 23:14:54 +01:00
2ce3e98df0 Improve type safety: Replace any with proper types
Replace `candidate: any` with `candidate: RTCIceCandidateInit | null`:

Changes:
- api.ts poll() return type (line 366)
- rondevu.ts pollOffers() return type (line 827)
- IceCandidate interface (line 41)

Benefits:
- Better type safety and IntelliSense support
- Matches WebRTC spec (candidates can be null)
- Catches potential type errors at compile time
- Clearer API contracts for consumers

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-12 23:10:57 +01:00
800f6eaa94 Refactor connectToService() method for better maintainability
Break down 129-line method into focused helper methods:

New private methods:
- resolveServiceFqn(): Determines full FQN from various input options
  Handles direct FQN, service+username, or discovery mode

- startIcePolling(): Manages remote ICE candidate polling
  Encapsulates polling logic and interval management

Benefits:
- connectToService() reduced from 129 to ~98 lines
- Each method has single responsibility
- Easier to test and maintain
- Better code readability with clear method names
- Reusable components for future features

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-12 23:07:49 +01:00
d6a9876440 Extract duplicate ICE candidate handling code
Refactor ICE candidate handler setup:
- Create setupIceCandidateHandler() private method
- Remove duplicate code from createOffer() and connectToService()
- Both methods now call the shared handler setup

Benefits:
- DRY principle: 13 lines of duplicate code eliminated
- Easier to maintain: changes to ICE handling logic only needed in one place
- Consistent error handling across both code paths

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-12 23:06:22 +01:00
9262043e97 Add debug mode and wrap all console.log statements
Implements opt-in debug logging system:
- Add debug?: boolean option to RondevuOptions
- Add private debug() method that only logs when debug mode is enabled
- Replace all 25+ console.log statements with this.debug() calls
- Static connect() method checks options.debug before logging

Benefits:
- Clean production console output by default
- Users can enable debug logging when needed: debug: true
- All debug messages prefixed with [Rondevu]
- Error logging (console.error) preserved for important failures

Usage:
```typescript
const rondevu = await Rondevu.connect({
  apiUrl: 'https://api.ronde.vu',
  username: 'alice',
  debug: true  // Enable debug logging
})
```

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-12 23:05:13 +01:00
bd16798a2f Replace magic numbers with named constants in client
Refactoring: Extract magic numbers to static constants
- DEFAULT_TTL_MS = 300000 (5 minutes)
- POLLING_INTERVAL_MS = 1000 (1 second)

Replaced in:
- ttl property initialization (line 173)
- publishService() default (line 335)
- startFilling() polling interval (line 500)
- connectToService() ICE polling (line 636)

Impact: Improves code clarity and maintainability
2025-12-12 22:55:24 +01:00
c662161cd9 Add input validation to connectToService()
Validation: Add checks for empty strings in connectToService()
- Validates serviceFqn is not empty string
- Validates service is not empty string
- Validates username is not empty string
- Prevents silent failures from whitespace-only inputs

Impact: Better error messages for invalid inputs
2025-12-12 22:51:58 +01:00
a9a0127ccf Remove unused imports: Service and ServiceRequest
Cleanup: Remove Service and ServiceRequest types from imports
- Not used anywhere in rondevu.ts
- Reduces unnecessary dependencies
- Verified: Build passes with no TypeScript errors
2025-12-12 22:51:20 +01:00
4345709e9c Remove RondevuSignaler documentation and outdated files
- Remove entire RondevuSignaler class documentation section
- Remove PollingConfig interface from Types section
- Delete obsolete USAGE.md file (completely outdated)
- Update all examples to use new automatic API
- Fix migration examples to show current publishService() format
2025-12-12 22:43:48 +01:00
43dfd72c3d Remove all legacy and backward compatibility support
- Remove serviceFqn, offers array from PublishServiceOptions
- Make service and maxOffers required fields
- Simplify publishService() to only support automatic mode
- Remove RondevuSignaler class completely
- Update exports to include new types (ConnectionContext, ConnectToServiceOptions)
- Update test-connect.js to use connectToService()
- Remove all "manual mode" and "legacy" references from documentation

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-12 22:33:29 +01:00
ec19ce50db Add connectToService() for automatic answering side setup
- Add ConnectToServiceOptions and ConnectionContext interfaces
- Implement connectToService() method that handles entire answering flow
- Automatically discovers/gets service, creates RTCPeerConnection, exchanges answer and ICE candidates
- Supports both direct lookup (serviceFqn) and discovery (service)
- Returns connection context with pc, dc, serviceFqn, offerId, and peerUsername
- Update README with automatic mode examples

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-12 22:26:44 +01:00
e5c82b75b1 Add ICE server preset support and update to Rondevu.connect()
- Add 4 ICE server presets: ipv4-turn, hostname-turns, google-stun, relay-only
- Update Rondevu.connect() to accept preset string or custom RTCIceServer array
- Support both automatic (maxOffers) and manual (offers array) modes in publishService()
- Rename internal poll() to pollInternal() to avoid conflict with public API
- Update README examples to use presets and proper offer factory pattern

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-12 22:13:03 +01:00
a2c01d530f Simplify API: Remove explicit claiming, add Rondevu.connect(), simplify publishService
Breaking changes:
- Remove claimUsername() method - username claiming now fully implicit
- Remove initialize() method - replaced with static Rondevu.connect()
- Change publishService() parameter from serviceFqn to service (username auto-appended)
- Make constructor private - must use Rondevu.connect()
- Remove nullable types from keypair/api - always initialized after connect()

New pattern:
const rondevu = await Rondevu.connect({ apiUrl, username })
await rondevu.publishService({ service: 'chat:2.0.0', offers })

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-12 21:56:37 +01:00
7223e45b98 Implement RPC request batching and throttling
Adds automatic request batching to reduce HTTP overhead by combining
multiple RPC calls into a single request.

Features:
- RpcBatcher class for intelligent request batching
- Configurable batch size (default: 10 requests)
- Configurable wait time (default: 50ms)
- Throttling to prevent overwhelming the server (default: 10ms)
- Automatic flushing when batch is full
- Enabled by default, can be disabled via options

Changes:
- Created rpc-batcher.ts with RpcBatcher class
- Updated RondevuAPI to use batcher by default
- Added batching option to RondevuOptions
- Updated README with batching documentation
- Bumped version to 0.16.0

Example usage:
  // Default (batching enabled with defaults)
  const rondevu = new Rondevu({ apiUrl: 'https://api.ronde.vu' })

  // Custom batching settings
  const rondevu = new Rondevu({
    apiUrl: 'https://api.ronde.vu',
    batching: { maxBatchSize: 20, maxWaitTime: 100 }
  })

  // Disable batching
  const rondevu = new Rondevu({
    apiUrl: 'https://api.ronde.vu',
    batching: false
  })

This can reduce HTTP requests by up to 90% during intensive operations
like ICE candidate exchange.

🤖 Generated with Claude Code
https://claude.com/claude-code

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-12 20:42:02 +01:00
d55abf2b63 Implement crypto adapter pattern for platform independence
Adds CryptoAdapter interface with WebCryptoAdapter (browser) and
NodeCryptoAdapter (Node.js 19+) implementations.

Changes:
- Created crypto-adapter.ts interface
- Created web-crypto-adapter.ts for browser environments
- Created node-crypto-adapter.ts for Node.js environments
- Updated RondevuAPI to accept optional CryptoAdapter
- Updated Rondevu class to pass crypto adapter through
- Exported adapters and types in index.ts
- Updated README with platform support documentation
- Bumped version to 0.15.0

This allows the client library to work in both browser and Node.js
environments by providing platform-specific crypto implementations.

Example usage in Node.js:
  import { Rondevu, NodeCryptoAdapter } from '@xtr-dev/rondevu-client'

  const rondevu = new Rondevu({
    apiUrl: 'https://api.ronde.vu',
    cryptoAdapter: new NodeCryptoAdapter()
  })

🤖 Generated with Claude Code
https://claude.com/claude-code

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-12 20:34:27 +01:00
4ce5217135 Fix: Remove redundant signature generation in publishService
The rondevu.ts wrapper was generating its own message and signature
which were being ignored by the API layer (which generates its own).
This caused the old signature to be passed but not used.

Simplified by removing the redundant code and letting the API layer
handle all authentication.

🤖 Generated with Claude Code
https://claude.com/claude-code

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-12 20:26:48 +01:00
238cc08bf5 Send publicKey in RPC requests for implicit username claiming
Updated client to send publicKey in all authenticated RPC requests,
enabling server-side implicit username claiming.

Changes:
- Added publicKey field to RpcRequest interface
- Added publicKey to all authenticated RPC method calls
- Removed username claiming requirement from publishService()
- Auto-mark username as claimed after successful publish

Users no longer need to call claimUsername() before publishing
services. The server will automatically claim the username on
the first authenticated request.

🤖 Generated with Claude Code
https://claude.com/claude-code

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-12 20:22:28 +01:00
f4ae5dee30 chore: Bump version to 0.14.0 for RPC refactor
BREAKING CHANGE: RPC interface replaces REST API
2025-12-12 20:14:12 +01:00
a499062e52 refactor: Update client to use RPC interface
BREAKING CHANGES:
- All API calls now go to POST /rpc endpoint
- Request format: { method, message, signature, params }
- Response format: { success, result } or { success: false, error }
- Simplified API methods to match RPC methods
- Removed checkUsername, added isUsernameAvailable
- Renamed postOfferAnswer to answerOffer
- Removed discoverService/discoverServices (use getService)

Changes:
- Completely refactored api.ts for RPC interface
- Updated rondevu.ts wrapper methods
- Updated rondevu-signaler.ts to use new API
- Fixed exports in index.ts
2025-12-12 20:10:03 +01:00
b5f36d8f77 refactor: Rename pollOffers to poll and remove getAnsweredOffers
BREAKING CHANGES:
- Renamed pollOffers() to poll() (matches new /poll endpoint)
- Removed getAnsweredOffers() method (use poll() instead)
- Updated endpoint path from /offers/poll to /poll
- Updated auth message format from 'pollOffers' to 'poll'
2025-12-12 19:13:19 +01:00
214f611dc2 fix: Send signature and message in publishService body
The auth middleware expects username, signature, and message in the request
body for POST requests. The service object already contains signature and
message from rondevu.ts, so we just need to ensure they're sent by spreading
the service object and adding username.
2025-12-12 12:38:33 +01:00
1112eeefd4 feat: Remove automatic username claiming
- Removed auto-claim logic from initialize() method
- Users must now explicitly call claimUsername()
- Updated JSDoc to reflect manual claiming requirement
- Anonymous usernames are generated but not auto-claimed

BREAKING CHANGE: Anonymous users are no longer automatically claimed.
Applications must explicitly call claimUsername() before publishing services.
2025-12-12 12:01:56 +01:00
0fe8e82858 docs: Update README for unified Ed25519 authentication
- Add anonymous username documentation and examples
- Remove Credentials interface from types section
- Update Rondevu constructor to show optional username (auto-generates anonymous)
- Remove register() method references
- Update RondevuAPI constructor (no credentials, requires username + keypair)
- Add automatic signature generation notes
- Update all code examples to show new initialization flow
- Add persistent keypair example with username storage
2025-12-10 22:19:18 +01:00
c9a5e0eae6 Unified Ed25519 authentication - remove credentials system
BREAKING CHANGE: Remove credential-based authentication

- Remove Credentials interface and all credential-related code
- Remove register() method from RondevuAPI
- Remove setCredentials() and getAuthHeader() methods

RondevuAPI changes:
- Constructor now requires username and keypair (not credentials)
- Add generateAuthParams() helper for automatic signature generation
- All API methods now include {username, signature, message} auth
- POST requests: auth in body
- GET requests: auth in query params
- Remove Authorization header from all fetch calls

Rondevu class changes:
- Make username optional in RondevuOptions (auto-generates anon username)
- Make keypair optional (auto-generates if not provided)
- Add generateAnonymousUsername() method (anon-{timestamp}-{random})
- Update initialize() to create API with username+keypair (no register call)
- Auto-claim username for anonymous users during initialize()
- Add lazy getAPI() to ensure initialization

Message format for auth:
- Format: action:username:params:timestamp
- Examples: publishService:alice:chat:1.0.0@alice:1234567890
- Each request generates unique signature with timestamp

Index exports:
- Remove Credentials export (no longer exists)
2025-12-10 22:07:07 +01:00
239563ac5c Update README to document current v0.4 API
- Remove outdated ServiceHost/ServiceClient/RTCDurableConnection documentation
- Document actual Rondevu, RondevuSignaler, and RondevuAPI classes
- Add pollOffers() combined polling documentation
- Add complete usage examples for offerer and answerer sides
- Document role-based ICE candidate filtering
- Add migration guide from v0.3.x
2025-12-10 21:04:16 +01:00
3327c5b219 Replace separate polling with combined pollOffers() in RondevuSignaler
Breaking Change: Offerer now uses pollOffers() for efficient batch polling

Changes:
- Offerer: use pollOffers() for combined answer+ICE polling (1 request vs 2)
- Answerer: keep using getOfferIceCandidates() (separate endpoint still needed)
- Add isOfferer flag to track role
- Replace startAnswerPolling() with startPolling() using pollOffers()
- Filter ICE candidates by role (answerer candidates for offerer)
- Use single lastPollTimestamp for both answers and ICE
- Reduce HTTP requests by 50% for offerers
- More efficient signaling with timestamp-based filtering

No backwards compatibility maintained per user request.
2025-12-10 20:55:02 +01:00
b4be5e9060 Add role and peerId to pollOffers ICE candidate response types
- ICE candidates now include role ('offerer' | 'answerer')
- ICE candidates now include peerId for matching
- Enables clients to filter candidates by role
- Supports bidirectional ICE exchange
2025-12-10 19:51:43 +01:00
b60799a712 Add combined polling API method for answers and ICE candidates
- Add pollOffers() method to RondevuAPI class
- Expose pollOffers() in Rondevu class
- Returns both answered offers and ICE candidates in single call
- Supports timestamp-based filtering with optional 'since' parameter
- More efficient than separate getAnsweredOffers() and getOfferIceCandidates() calls
2025-12-10 19:33:11 +01:00
8fbb76a336 Add getAnsweredOffers API method for batch polling
Added RondevuAPI.getAnsweredOffers() and Rondevu.getAnsweredOffers()
methods to efficiently retrieve all answered offers with optional
timestamp filtering.

This enables offerers to poll for incoming connections in a single
request instead of polling each offer individually.
2025-12-10 19:19:39 +01:00
a3b4dfa15f 0.13.0 2025-12-09 22:28:15 +01:00
5c38f8f36c v0.13.0: Major refactoring with unified Rondevu class and service discovery
- Renamed RondevuService to Rondevu as single main entrypoint
- Integrated signaling methods directly into Rondevu class
- Updated service FQN format: service:version@username (colon instead of @)
- Added service discovery (direct, random, paginated)
- Removed high-level abstractions (ServiceHost, ServiceClient, RTCDurableConnection, EventBus, WebRTCContext, Bin)
- Updated RondevuAPI with new endpoint methods (offer-specific routes)
- Simplified types (moved Binnable to types.ts, removed connection types)
- Updated RondevuSignaler to use Rondevu class
- Breaking changes: Complete API overhaul for simplicity

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-09 22:22:15 +01:00
177ee2ec2d feat: update client to use service-based signaling endpoints
BREAKING CHANGE: Client API now uses service UUIDs for WebRTC signaling

- Replace answerOffer() with answerService()
- Replace getAnswer() with getServiceAnswer()
- Replace addIceCandidates() with addServiceIceCandidates()
- Replace getIceCandidates() with getServiceIceCandidates()
- Update RondevuSignaler to use service UUID instead of offer ID for signaling
- Automatically track offerId returned from service endpoints
- Bump version to 0.12.0

Matches server v0.4.0 service-based API refactor.
2025-12-07 22:17:36 +01:00
d06b2166c1 chore: Bump version to 0.11.0 2025-12-07 22:01:34 +01:00
cbb0cc3f83 docs: Update README with semver and privacy features 2025-12-07 21:58:20 +01:00
fbd3be57d4 Add RTCConfiguration support to ServiceHost and ServiceClient
- WebRTCContext now accepts optional RTCConfiguration
- ServiceHost and ServiceClient accept optional rtcConfiguration option
- Allows custom STUN/TURN server configuration
- Version bump to 0.10.1

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-07 19:43:34 +01:00
54355323d9 Add ServiceHost, ServiceClient, and RondevuService for high-level service management
- Add RondevuService: High-level API for username claiming and service publishing with Ed25519 signatures
- Add ServiceHost: Manages offer pool for hosting services with auto-replacement
- Add ServiceClient: Connects to hosted services with automatic reconnection
- Add NoOpSignaler: Placeholder signaler for connection setup
- Integrate Ed25519 signature functionality from @noble/ed25519
- Add ESLint and Prettier configuration with 4-space indentation
- Add demo with local signaling test
- Version bump to 0.10.0

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-07 19:37:43 +01:00
945d5a8792 Add comprehensive usage documentation 2025-12-07 17:41:16 +01:00
58cd610694 Implement RondevuAPI and RondevuSignaler classes
Added comprehensive API client and signaling implementation:

**RondevuAPI** - Single class for all Rondevu endpoints:
- Authentication: register()
- Offers: createOffers(), getOffer(), answerOffer(), getAnswer(), searchOffers()
- ICE Candidates: addIceCandidates(), getIceCandidates()
- Services: publishService(), getService(), searchServices()
- Usernames: checkUsername(), claimUsername()

**RondevuSignaler** - ICE candidate exchange:
- addIceCandidate() - Send local candidates to server
- addListener() - Poll for remote candidates (1 second intervals)
- Returns cleanup function (Binnable) to stop polling
- Handles offer expiration gracefully

**WebRTCRondevuConnection** - WebRTC connection wrapper:
- Handles offer/answer creation
- Manages ICE candidate exchange via Signaler
- Type-safe event bus for state changes and messages
- Queue and send message interfaces

**Utilities**:
- createBin() - Cleanup function collector
- Binnable type - Cleanup function signature

All classes use the shared RondevuAPI client for consistent
error handling and authentication.

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

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2025-12-07 17:40:17 +01:00
17 changed files with 5347 additions and 857 deletions

9
.prettierrc.json Normal file
View File

@@ -0,0 +1,9 @@
{
"semi": false,
"singleQuote": true,
"tabWidth": 4,
"useTabs": false,
"trailingComma": "es5",
"printWidth": 100,
"arrowParens": "avoid"
}

486
ADVANCED.md Normal file
View File

@@ -0,0 +1,486 @@
# Rondevu Client - Advanced Usage
Comprehensive guide for advanced features, platform support, and detailed API reference.
## Table of Contents
- [API Reference](#api-reference)
- [Types](#types)
- [Advanced Usage](#advanced-usage)
- [Platform Support](#platform-support)
- [Username Rules](#username-rules)
- [Service FQN Format](#service-fqn-format)
- [Examples](#examples)
- [Migration Guide](#migration-guide)
---
## API Reference
### Rondevu Class
Main class for all Rondevu operations.
```typescript
import { Rondevu } from '@xtr-dev/rondevu-client'
// Create and connect to Rondevu
const rondevu = await Rondevu.connect({
apiUrl: string, // Signaling server URL
username?: string, // Optional: your username (auto-generates anonymous if omitted)
keypair?: Keypair, // Optional: reuse existing keypair
cryptoAdapter?: CryptoAdapter // Optional: platform-specific crypto (defaults to WebCryptoAdapter)
batching?: BatcherOptions | false // Optional: RPC batching configuration
iceServers?: IceServerPreset | RTCIceServer[] // Optional: preset name or custom STUN/TURN servers
debug?: boolean // Optional: enable debug logging (default: false)
})
```
#### Platform Support (Browser & Node.js)
The client supports both browser and Node.js environments using crypto adapters:
**Browser (default):**
```typescript
import { Rondevu } from '@xtr-dev/rondevu-client'
// WebCryptoAdapter is used by default - no configuration needed
const rondevu = await Rondevu.connect({
apiUrl: 'https://api.ronde.vu',
username: 'alice'
})
```
**Node.js (19+ or 18 with --experimental-global-webcrypto):**
```typescript
import { Rondevu, NodeCryptoAdapter } from '@xtr-dev/rondevu-client'
const rondevu = await Rondevu.connect({
apiUrl: 'https://api.ronde.vu',
username: 'alice',
cryptoAdapter: new NodeCryptoAdapter()
})
```
**Note:** Node.js support requires:
- Node.js 19+ (crypto.subtle available globally), OR
- Node.js 18 with `--experimental-global-webcrypto` flag
- WebRTC implementation like `wrtc` or `node-webrtc` for RTCPeerConnection
**Custom Crypto Adapter:**
```typescript
import { CryptoAdapter, Keypair } from '@xtr-dev/rondevu-client'
class CustomCryptoAdapter implements CryptoAdapter {
async generateKeypair(): Promise<Keypair> { /* ... */ }
async signMessage(message: string, privateKey: string): Promise<string> { /* ... */ }
async verifySignature(message: string, signature: string, publicKey: string): Promise<boolean> { /* ... */ }
bytesToBase64(bytes: Uint8Array): string { /* ... */ }
base64ToBytes(base64: string): Uint8Array { /* ... */ }
randomBytes(length: number): Uint8Array { /* ... */ }
}
const rondevu = await Rondevu.connect({
apiUrl: 'https://api.ronde.vu',
cryptoAdapter: new CustomCryptoAdapter()
})
```
#### Username Management
Usernames are **automatically claimed** on the first authenticated request (like `publishService()`).
```typescript
// Check if username is claimed (checks server)
await rondevu.isUsernameClaimed(): Promise<boolean>
// Get username
rondevu.getUsername(): string
// Get public key
rondevu.getPublicKey(): string
// Get keypair (for backup/storage)
rondevu.getKeypair(): Keypair
```
#### Service Publishing
```typescript
// Publish service with offers
await rondevu.publishService({
service: string, // e.g., 'chat:1.0.0' (username auto-appended)
maxOffers: number, // Maximum number of concurrent offers to maintain
offerFactory?: OfferFactory, // Optional: custom offer creation (defaults to simple data channel)
ttl?: number // Optional: milliseconds (default: 300000)
}): Promise<void>
```
#### Service Discovery
```typescript
// Direct lookup by FQN (with username)
await rondevu.getService('chat:1.0.0@alice'): Promise<ServiceOffer>
// Random discovery (without username)
await rondevu.discoverService('chat:1.0.0'): Promise<ServiceOffer>
// Paginated discovery (returns multiple offers)
await rondevu.discoverServices(
'chat:1.0.0', // serviceVersion
10, // limit
0 // offset
): Promise<{ services: ServiceOffer[], count: number, limit: number, offset: number }>
```
#### WebRTC Signaling
```typescript
// Post answer SDP
await rondevu.postOfferAnswer(
serviceFqn: string,
offerId: string,
sdp: string
): Promise<{ success: boolean, offerId: string }>
// Get answer SDP (offerer polls this - deprecated, use pollOffers instead)
await rondevu.getOfferAnswer(
serviceFqn: string,
offerId: string
): Promise<{ sdp: string, offerId: string, answererId: string, answeredAt: number } | null>
// Combined polling for answers and ICE candidates (RECOMMENDED for offerers)
await rondevu.pollOffers(since?: number): Promise<{
answers: Array<{
offerId: string
serviceId?: string
answererId: string
sdp: string
answeredAt: number
}>
iceCandidates: Record<string, Array<{
candidate: RTCIceCandidateInit | null
role: 'offerer' | 'answerer'
peerId: string
createdAt: number
}>>
}>
// Add ICE candidates
await rondevu.addOfferIceCandidates(
serviceFqn: string,
offerId: string,
candidates: RTCIceCandidateInit[]
): Promise<{ count: number, offerId: string }>
// Get ICE candidates (with polling support)
await rondevu.getOfferIceCandidates(
serviceFqn: string,
offerId: string,
since: number = 0
): Promise<{ candidates: IceCandidate[], offerId: string }>
```
### RondevuAPI Class
Low-level HTTP API client (used internally by Rondevu class).
```typescript
import { RondevuAPI } from '@xtr-dev/rondevu-client'
const api = new RondevuAPI(
baseUrl: string,
username: string,
keypair: Keypair
)
// Check username
await api.checkUsername(username: string): Promise<{
available: boolean
publicKey?: string
claimedAt?: number
expiresAt?: number
}>
// Note: Username claiming is now implicit - usernames are auto-claimed
// on first authenticated request to the server
// ... (all other HTTP endpoints)
```
#### Cryptographic Helpers
```typescript
// Generate Ed25519 keypair
const keypair = await RondevuAPI.generateKeypair(): Promise<Keypair>
// Sign message
const signature = await RondevuAPI.signMessage(
message: string,
privateKey: string
): Promise<string>
// Verify signature
const valid = await RondevuAPI.verifySignature(
message: string,
signature: string,
publicKey: string
): Promise<boolean>
```
---
## Types
```typescript
interface Keypair {
publicKey: string // Base64-encoded Ed25519 public key
privateKey: string // Base64-encoded Ed25519 private key
}
interface Service {
serviceId: string
offers: ServiceOffer[]
username: string
serviceFqn: string
createdAt: number
expiresAt: number
}
interface ServiceOffer {
offerId: string
sdp: string
createdAt: number
expiresAt: number
}
interface IceCandidate {
candidate: RTCIceCandidateInit | null
createdAt: number
}
```
---
## Advanced Usage
### Anonymous Username
```typescript
// Auto-generate anonymous username (format: anon-{timestamp}-{random})
const rondevu = await Rondevu.connect({
apiUrl: 'https://api.ronde.vu'
// No username provided - will generate anonymous username
})
console.log(rondevu.getUsername()) // e.g., "anon-lx2w34-a3f501"
// Anonymous users behave exactly like regular users
await rondevu.publishService({
service: 'chat:1.0.0',
maxOffers: 5
})
await rondevu.startFilling()
```
### Persistent Keypair
```typescript
// Save keypair and username to localStorage
const rondevu = await Rondevu.connect({
apiUrl: 'https://api.ronde.vu',
username: 'alice'
})
// Save for later (username will be auto-claimed on first authenticated request)
localStorage.setItem('rondevu-username', rondevu.getUsername())
localStorage.setItem('rondevu-keypair', JSON.stringify(rondevu.getKeypair()))
// Load on next session
const savedUsername = localStorage.getItem('rondevu-username')
const savedKeypair = JSON.parse(localStorage.getItem('rondevu-keypair'))
const rondevu2 = await Rondevu.connect({
apiUrl: 'https://api.ronde.vu',
username: savedUsername,
keypair: savedKeypair
})
```
### Service Discovery
```typescript
// Get a random available service
const service = await rondevu.discoverService('chat:1.0.0')
console.log('Discovered:', service.username)
// Get multiple services (paginated)
const result = await rondevu.discoverServices('chat:1.0.0', 10, 0)
console.log(`Found ${result.count} services:`)
result.services.forEach(s => console.log(` - ${s.username}`))
```
### Multiple Concurrent Offers
```typescript
// Publish service with multiple offers for connection pooling
const offers = []
const connections = []
for (let i = 0; i < 5; i++) {
const pc = new RTCPeerConnection(rtcConfig)
const dc = pc.createDataChannel('chat')
const offer = await pc.createOffer()
await pc.setLocalDescription(offer)
offers.push({ sdp: offer.sdp })
connections.push({ pc, dc })
}
const service = await rondevu.publishService({
service: 'chat:1.0.0',
offers,
ttl: 300000
})
// Each offer can be answered independently
console.log(`Published ${service.offers.length} offers`)
```
### Debug Logging
```typescript
// Enable debug logging to see internal operations
const rondevu = await Rondevu.connect({
apiUrl: 'https://api.ronde.vu',
username: 'alice',
debug: true // All internal logs will be displayed with [Rondevu] prefix
})
// Debug logs include:
// - Connection establishment
// - Keypair generation
// - Service publishing
// - Offer creation
// - ICE candidate exchange
// - Connection state changes
```
---
## Platform Support
### Modern Browsers
Works out of the box - no additional setup needed.
### Node.js 18+
Native fetch is available, but WebRTC requires polyfills:
```bash
npm install wrtc
```
```typescript
import { RTCPeerConnection, RTCSessionDescription, RTCIceCandidate } from 'wrtc'
// Use wrtc implementations
const pc = new RTCPeerConnection()
```
---
## Username Rules
- **Format**: Lowercase alphanumeric + dash (`a-z`, `0-9`, `-`)
- **Length**: 3-32 characters
- **Pattern**: `^[a-z0-9][a-z0-9-]*[a-z0-9]$`
- **Validity**: 365 days from claim/last use
- **Ownership**: Secured by Ed25519 public key signature
---
## Service FQN Format
- **Format**: `service:version@username`
- **Service**: Lowercase alphanumeric + dash (e.g., `chat`, `video-call`)
- **Version**: Semantic versioning (e.g., `1.0.0`, `2.1.3`)
- **Username**: Claimed username
- **Example**: `chat:1.0.0@alice`
---
## Examples
### Node.js Service Host Example
You can host WebRTC services in Node.js that browser clients can connect to:
```typescript
import { Rondevu, NodeCryptoAdapter } from '@xtr-dev/rondevu-client'
import wrtc from 'wrtc'
const { RTCPeerConnection } = wrtc
// Initialize with Node crypto adapter
const rondevu = await Rondevu.connect({
apiUrl: 'https://api.ronde.vu',
username: 'mybot',
cryptoAdapter: new NodeCryptoAdapter()
})
// Create peer connection (offerer creates data channel)
const pc = new RTCPeerConnection(rtcConfig)
const dc = pc.createDataChannel('chat')
// Publish service (username auto-claimed on first publish)
await rondevu.publishService({
service: 'chat:1.0.0',
maxOffers: 5
})
await rondevu.startFilling()
// Browser clients can now discover and connect to chat:1.0.0@mybot
```
**See also:**
- [React Demo](https://github.com/xtr-dev/rondevu-demo) - Complete browser UI ([live](https://ronde.vu))
---
## Migration Guide
### Migration from v0.3.x
v0.4.0 removes high-level abstractions and uses manual WebRTC setup:
**Removed:**
- `ServiceHost` class (use manual WebRTC + `publishService()`)
- `ServiceClient` class (use manual WebRTC + `getService()`)
- `RTCDurableConnection` class (use native WebRTC APIs)
- `RondevuService` class (merged into `Rondevu`)
**Added:**
- `pollOffers()` - Combined polling for answers and ICE candidates
- `publishService()` - Automatic offer pool management
- `connectToService()` - Automatic answering side setup
**Migration Example:**
```typescript
// Before (v0.3.x) - ServiceHost
const host = new ServiceHost({
service: 'chat@1.0.0',
rondevuService: service
})
await host.start()
// After (v0.4.0+) - Automatic setup
await rondevu.publishService({
service: 'chat:1.0.0',
maxOffers: 5
})
await rondevu.startFilling()
```

View File

@@ -1,120 +0,0 @@
# EventBus Usage Examples
## Type-Safe Event Bus
The `EventBus` class provides fully type-safe event handling with TypeScript type inference.
### Basic Usage
```typescript
import { EventBus } from '@xtr-dev/rondevu-client';
// Define your event mapping
interface AppEvents {
'user:connected': { userId: string; timestamp: number };
'user:disconnected': { userId: string };
'message:received': string;
'connection:error': Error;
}
// Create the event bus
const events = new EventBus<AppEvents>();
// Subscribe to events - TypeScript knows the exact data type!
events.on('user:connected', (data) => {
// data is { userId: string; timestamp: number }
console.log(`User ${data.userId} connected at ${data.timestamp}`);
});
events.on('message:received', (data) => {
// data is string
console.log(data.toUpperCase());
});
// Emit events - TypeScript validates the data type
events.emit('user:connected', {
userId: '123',
timestamp: Date.now()
});
events.emit('message:received', 'Hello World');
// Type errors caught at compile time:
// events.emit('user:connected', 'wrong type'); // ❌ Error!
// events.emit('message:received', { wrong: 'type' }); // ❌ Error!
```
### One-Time Listeners
```typescript
// Subscribe once - handler auto-unsubscribes after first call
events.once('connection:error', (error) => {
console.error('Connection failed:', error.message);
});
```
### Unsubscribing
```typescript
const handler = (data: string) => {
console.log('Message:', data);
};
events.on('message:received', handler);
// Later, unsubscribe
events.off('message:received', handler);
```
### Utility Methods
```typescript
// Clear all handlers for a specific event
events.clear('message:received');
// Clear all handlers for all events
events.clear();
// Get listener count
const count = events.listenerCount('user:connected');
// Get all event names with handlers
const eventNames = events.eventNames();
```
## Connection Events Example
```typescript
interface ConnectionEvents {
'connection:state': { state: 'connected' | 'disconnected' | 'connecting' };
'connection:message': { from: string; data: string | ArrayBuffer };
'connection:error': { code: string; message: string };
}
class ConnectionManager {
private events = new EventBus<ConnectionEvents>();
on<K extends keyof ConnectionEvents>(
event: K,
handler: (data: ConnectionEvents[K]) => void
) {
this.events.on(event, handler);
}
private handleStateChange(state: 'connected' | 'disconnected' | 'connecting') {
this.events.emit('connection:state', { state });
}
private handleMessage(from: string, data: string | ArrayBuffer) {
this.events.emit('connection:message', { from, data });
}
}
```
## Benefits
-**Full type safety** - TypeScript validates event names and data types
-**IntelliSense support** - Auto-completion for event names and data properties
-**Compile-time errors** - Catch type mismatches before runtime
-**Self-documenting** - Event interface serves as documentation
-**Refactoring-friendly** - Rename events or change types with confidence

698
README.md
View File

@@ -2,9 +2,9 @@
[![npm version](https://img.shields.io/npm/v/@xtr-dev/rondevu-client)](https://www.npmjs.com/package/@xtr-dev/rondevu-client)
🌐 **WebRTC with durable connections and automatic reconnection**
🌐 **Simple WebRTC signaling client with username-based discovery**
TypeScript/JavaScript client for Rondevu, providing durable WebRTC connections that survive network interruptions with automatic reconnection and message queuing.
TypeScript/JavaScript client for Rondevu, providing WebRTC signaling with username claiming, service publishing/discovery, and efficient batch polling.
**Related repositories:**
- [@xtr-dev/rondevu-client](https://github.com/xtr-dev/rondevu-client) - TypeScript client library ([npm](https://www.npmjs.com/package/@xtr-dev/rondevu-client))
@@ -15,16 +15,17 @@ TypeScript/JavaScript client for Rondevu, providing durable WebRTC connections t
## Features
- **Durable Connections**: Automatic reconnection on network drops
- **Message Queuing**: Messages sent during disconnections are queued and flushed on reconnect
- **Durable Channels**: RTCDataChannel wrappers that survive connection drops
- **TTL Auto-Refresh**: Services automatically republish before expiration
- **Username Claiming**: Cryptographic ownership with Ed25519 signatures
- **Service Publishing**: Package-style naming (com.example.chat@1.0.0)
- **Username Claiming**: Secure ownership with Ed25519 signatures
- **Anonymous Users**: Auto-generated anonymous usernames for quick testing
- **Service Publishing**: Publish services with multiple offers for connection pooling
- **Service Discovery**: Direct lookup, random discovery, or paginated search
- **Efficient Batch Polling**: Single endpoint for answers and ICE candidates (50% fewer requests)
- **Semantic Version Matching**: Compatible version resolution (chat:1.0.0 matches any 1.x.x)
- **TypeScript**: Full type safety and autocomplete
- **Configurable**: All timeouts, retry limits, and queue sizes are configurable
- **Keypair Management**: Generate or reuse Ed25519 keypairs
- **Automatic Signatures**: All authenticated requests signed automatically
## Install
## Installation
```bash
npm install @xtr-dev/rondevu-client
@@ -32,627 +33,144 @@ npm install @xtr-dev/rondevu-client
## Quick Start
### Publishing a Service (Alice)
### Publishing a Service (Offerer)
```typescript
import { Rondevu } from '@xtr-dev/rondevu-client';
import { Rondevu } from '@xtr-dev/rondevu-client'
// Initialize client and register
const client = new Rondevu({ baseUrl: 'https://api.ronde.vu' });
await client.register();
// 1. Connect to Rondevu
const rondevu = await Rondevu.connect({
apiUrl: 'https://api.ronde.vu',
username: 'alice', // Or omit for anonymous username
iceServers: 'ipv4-turn' // Preset: 'ipv4-turn', 'hostname-turns', 'google-stun', 'relay-only'
})
// Step 1: Claim username (one-time)
const claim = await client.usernames.claimUsername('alice');
client.usernames.saveKeypairToStorage('alice', claim.publicKey, claim.privateKey);
// 2. Publish service with automatic offer management
await rondevu.publishService({
service: 'chat:1.0.0',
maxOffers: 5, // Maintain up to 5 concurrent offers
offerFactory: async (rtcConfig) => {
const pc = new RTCPeerConnection(rtcConfig)
const dc = pc.createDataChannel('chat')
// Step 2: Expose service with handler
const keypair = client.usernames.loadKeypairFromStorage('alice');
dc.addEventListener('open', () => {
console.log('Connection opened!')
dc.send('Hello from Alice!')
})
const service = await client.exposeService({
username: 'alice',
privateKey: keypair.privateKey,
serviceFqn: 'chat@1.0.0',
isPublic: true,
poolSize: 10, // Handle 10 concurrent connections
handler: (channel, connectionId) => {
console.log(`📡 New connection: ${connectionId}`);
dc.addEventListener('message', (e) => {
console.log('Received:', e.data)
})
channel.on('message', (data) => {
console.log('📥 Received:', data);
channel.send(`Echo: ${data}`);
});
channel.on('close', () => {
console.log(`👋 Connection ${connectionId} closed`);
});
const offer = await pc.createOffer()
await pc.setLocalDescription(offer)
return { pc, dc, offer }
}
});
})
// Start the service
const info = await service.start();
console.log(`Service published with UUID: ${info.uuid}`);
console.log('Waiting for connections...');
// Later: stop the service
await service.stop();
// 3. Start accepting connections
await rondevu.startFilling()
```
### Connecting to a Service (Bob)
### Connecting to a Service (Answerer)
```typescript
import { Rondevu } from '@xtr-dev/rondevu-client';
import { Rondevu } from '@xtr-dev/rondevu-client'
// Initialize client and register
const client = new Rondevu({ baseUrl: 'https://api.ronde.vu' });
await client.register();
// 1. Connect to Rondevu
const rondevu = await Rondevu.connect({
apiUrl: 'https://api.ronde.vu',
username: 'bob',
iceServers: 'ipv4-turn'
})
// Connect to Alice's service
const connection = await client.connect('alice', 'chat@1.0.0', {
maxReconnectAttempts: 5
});
// 2. Connect to service (automatic WebRTC setup)
const connection = await rondevu.connectToService({
serviceFqn: 'chat:1.0.0@alice',
onConnection: ({ dc, peerUsername }) => {
console.log('Connected to', peerUsername)
// Create a durable channel
const channel = connection.createChannel('main');
dc.addEventListener('message', (e) => {
console.log('Received:', e.data)
})
channel.on('message', (data) => {
console.log('📥 Received:', data);
});
channel.on('open', () => {
console.log('✅ Channel open');
channel.send('Hello Alice!');
});
// Listen for connection events
connection.on('connected', () => {
console.log('🎉 Connected to Alice');
});
connection.on('reconnecting', (attempt, max, delay) => {
console.log(`🔄 Reconnecting... (${attempt}/${max}, retry in ${delay}ms)`);
});
connection.on('disconnected', () => {
console.log('🔌 Disconnected');
});
connection.on('failed', (error) => {
console.error('❌ Connection failed permanently:', error);
});
// Establish the connection
await connection.connect();
// Messages sent during disconnection are automatically queued
channel.send('This will be queued if disconnected');
// Later: close the connection
await connection.close();
```
## Core Concepts
### DurableConnection
Manages WebRTC peer lifecycle with automatic reconnection:
- Automatically reconnects when connection drops
- Exponential backoff with jitter (1s → 2s → 4s → 8s → ... max 30s)
- Configurable max retry attempts (default: 10)
- Manages multiple DurableChannel instances
### DurableChannel
Wraps RTCDataChannel with message queuing:
- Queues messages during disconnection
- Flushes queue on reconnection
- Configurable queue size and message age limits
- RTCDataChannel-compatible API with event emitters
### DurableService
Server-side service with TTL auto-refresh:
- Automatically republishes service before TTL expires
- Creates DurableConnection for each incoming peer
- Manages connection pool for multiple simultaneous connections
## API Reference
### Main Client
```typescript
const client = new Rondevu({
baseUrl: 'https://api.ronde.vu', // optional, default shown
credentials?: { peerId, secret }, // optional, skip registration
fetch?: customFetch, // optional, for Node.js < 18
RTCPeerConnection?: RTCPeerConnection, // optional, for Node.js
RTCSessionDescription?: RTCSessionDescription,
RTCIceCandidate?: RTCIceCandidate
});
// Register and get credentials
const creds = await client.register();
// { peerId: '...', secret: '...' }
// Check if authenticated
client.isAuthenticated(); // boolean
// Get current credentials
client.getCredentials(); // { peerId, secret } | undefined
```
### Username API
```typescript
// Check username availability
const check = await client.usernames.checkUsername('alice');
// { available: true } or { available: false, expiresAt: number, publicKey: string }
// Claim username with new keypair
const claim = await client.usernames.claimUsername('alice');
// { username, publicKey, privateKey, claimedAt, expiresAt }
// Save keypair to localStorage
client.usernames.saveKeypairToStorage('alice', claim.publicKey, claim.privateKey);
// Load keypair from localStorage
const keypair = client.usernames.loadKeypairFromStorage('alice');
// { publicKey, privateKey } | null
```
**Username Rules:**
- Format: Lowercase alphanumeric + dash (`a-z`, `0-9`, `-`)
- Length: 3-32 characters
- Pattern: `^[a-z0-9][a-z0-9-]*[a-z0-9]$`
- Validity: 365 days from claim/last use
- Ownership: Secured by Ed25519 public key
### Durable Service API
```typescript
// Expose a durable service
const service = await client.exposeService({
username: 'alice',
privateKey: keypair.privateKey,
serviceFqn: 'chat@1.0.0',
// Service options
isPublic: true, // optional, default: false
metadata: { version: '1.0' }, // optional
ttl: 300000, // optional, default: 5 minutes
ttlRefreshMargin: 0.2, // optional, refresh at 80% of TTL
// Connection pooling
poolSize: 10, // optional, default: 1
pollingInterval: 2000, // optional, default: 2000ms
// Connection options (applied to incoming connections)
maxReconnectAttempts: 10, // optional, default: 10
reconnectBackoffBase: 1000, // optional, default: 1000ms
reconnectBackoffMax: 30000, // optional, default: 30000ms
reconnectJitter: 0.2, // optional, default: 0.2 (±20%)
connectionTimeout: 30000, // optional, default: 30000ms
// Message queuing
maxQueueSize: 1000, // optional, default: 1000
maxMessageAge: 60000, // optional, default: 60000ms (1 minute)
// WebRTC configuration
rtcConfig: {
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' }
]
},
// Connection handler
handler: (channel, connectionId) => {
// Handle incoming connection
channel.on('message', (data) => {
console.log('Received:', data);
channel.send(`Echo: ${data}`);
});
dc.addEventListener('open', () => {
dc.send('Hello from Bob!')
})
}
});
})
// Start the service
const info = await service.start();
// { serviceId: '...', uuid: '...', expiresAt: 1234567890 }
// Get active connections
const connections = service.getActiveConnections();
// ['conn-123', 'conn-456']
// Get service info
const serviceInfo = service.getServiceInfo();
// { serviceId: '...', uuid: '...', expiresAt: 1234567890 } | null
// Stop the service
await service.stop();
// Access connection
connection.dc.send('Another message')
connection.pc.close() // Close when done
```
**Service Events:**
```typescript
service.on('published', (serviceId, uuid) => {
console.log(`Service published: ${uuid}`);
});
## Core API
service.on('connection', (connectionId) => {
console.log(`New connection: ${connectionId}`);
});
service.on('disconnection', (connectionId) => {
console.log(`Connection closed: ${connectionId}`);
});
service.on('ttl-refreshed', (expiresAt) => {
console.log(`TTL refreshed, expires at: ${new Date(expiresAt)}`);
});
service.on('error', (error, context) => {
console.error(`Service error (${context}):`, error);
});
service.on('closed', () => {
console.log('Service stopped');
});
```
### Durable Connection API
### Rondevu.connect()
```typescript
// Connect by username and service FQN
const connection = await client.connect('alice', 'chat@1.0.0', {
// Connection options
maxReconnectAttempts: 10, // optional, default: 10
reconnectBackoffBase: 1000, // optional, default: 1000ms
reconnectBackoffMax: 30000, // optional, default: 30000ms
reconnectJitter: 0.2, // optional, default: 0.2 (±20%)
connectionTimeout: 30000, // optional, default: 30000ms
// Message queuing
maxQueueSize: 1000, // optional, default: 1000
maxMessageAge: 60000, // optional, default: 60000ms
// WebRTC configuration
rtcConfig: {
iceServers: [
{ urls: 'stun:stun.l.google.com:19302' }
]
}
});
// Connect by UUID
const connection2 = await client.connectByUuid('service-uuid-here', {
maxReconnectAttempts: 5
});
// Create channels before connecting
const channel = connection.createChannel('main');
const fileChannel = connection.createChannel('files', {
ordered: false,
maxRetransmits: 3
});
// Get existing channel
const existingChannel = connection.getChannel('main');
// Check connection state
const state = connection.getState();
// 'connecting' | 'connected' | 'reconnecting' | 'disconnected' | 'failed' | 'closed'
const isConnected = connection.isConnected();
// Connect
await connection.connect();
// Close connection
await connection.close();
const rondevu = await Rondevu.connect({
apiUrl: string, // Required: Signaling server URL
username?: string, // Optional: your username (auto-generates anonymous if omitted)
keypair?: Keypair, // Optional: reuse existing keypair
iceServers?: IceServerPreset | RTCIceServer[], // Optional: preset or custom config
debug?: boolean // Optional: enable debug logging (default: false)
})
```
**Connection Events:**
```typescript
connection.on('state', (newState, previousState) => {
console.log(`State: ${previousState}${newState}`);
});
connection.on('connected', () => {
console.log('Connected');
});
connection.on('reconnecting', (attempt, maxAttempts, delay) => {
console.log(`Reconnecting (${attempt}/${maxAttempts}) in ${delay}ms`);
});
connection.on('disconnected', () => {
console.log('Disconnected');
});
connection.on('failed', (error, permanent) => {
console.error('Connection failed:', error, 'Permanent:', permanent);
});
connection.on('closed', () => {
console.log('Connection closed');
});
```
### Durable Channel API
### Service Publishing
```typescript
const channel = connection.createChannel('chat', {
ordered: true, // optional, default: true
maxRetransmits: undefined // optional, for unordered channels
});
await rondevu.publishService({
service: string, // e.g., 'chat:1.0.0' (username auto-appended)
maxOffers: number, // Maximum concurrent offers to maintain
offerFactory?: OfferFactory, // Optional: custom offer creation
ttl?: number // Optional: offer lifetime in ms (default: 300000)
})
// Send data (queued if disconnected)
channel.send('Hello!');
channel.send(new ArrayBuffer(1024));
channel.send(new Blob(['data']));
// Check state
const state = channel.readyState;
// 'connecting' | 'open' | 'closing' | 'closed'
// Get buffered amount
const buffered = channel.bufferedAmount;
// Set buffered amount low threshold
channel.bufferedAmountLowThreshold = 16 * 1024; // 16KB
// Get queue size (for debugging)
const queueSize = channel.getQueueSize();
// Close channel
channel.close();
await rondevu.startFilling() // Start accepting connections
rondevu.stopFilling() // Stop and close all connections
```
**Channel Events:**
```typescript
channel.on('open', () => {
console.log('Channel open');
});
channel.on('message', (data) => {
console.log('Received:', data);
});
channel.on('error', (error) => {
console.error('Channel error:', error);
});
channel.on('close', () => {
console.log('Channel closed');
});
channel.on('bufferedAmountLow', () => {
console.log('Buffer drained, safe to send more');
});
channel.on('queueOverflow', (droppedCount) => {
console.warn(`Queue overflow: ${droppedCount} messages dropped`);
});
```
## Configuration Options
### Connection Configuration
### Service Discovery
```typescript
interface DurableConnectionConfig {
maxReconnectAttempts?: number; // default: 10
reconnectBackoffBase?: number; // default: 1000 (1 second)
reconnectBackoffMax?: number; // default: 30000 (30 seconds)
reconnectJitter?: number; // default: 0.2 (±20%)
connectionTimeout?: number; // default: 30000 (30 seconds)
maxQueueSize?: number; // default: 1000 messages
maxMessageAge?: number; // default: 60000 (1 minute)
rtcConfig?: RTCConfiguration;
}
// Direct lookup (with username)
await rondevu.getService('chat:1.0.0@alice')
// Random discovery (without username)
await rondevu.discoverService('chat:1.0.0')
// Paginated discovery
await rondevu.discoverServices('chat:1.0.0', limit, offset)
```
### Service Configuration
### Connecting to Services
```typescript
interface DurableServiceConfig extends DurableConnectionConfig {
username: string;
privateKey: string;
serviceFqn: string;
isPublic?: boolean; // default: false
metadata?: Record<string, any>;
ttl?: number; // default: 300000 (5 minutes)
ttlRefreshMargin?: number; // default: 0.2 (refresh at 80%)
poolSize?: number; // default: 1
pollingInterval?: number; // default: 2000 (2 seconds)
}
const connection = await rondevu.connectToService({
serviceFqn?: string, // Full FQN like 'chat:1.0.0@alice'
service?: string, // Service without username (for discovery)
username?: string, // Target username (combined with service)
onConnection?: (context) => void, // Called when data channel opens
rtcConfig?: RTCConfiguration // Optional: override ICE servers
})
```
## Documentation
📚 **[ADVANCED.md](./ADVANCED.md)** - Comprehensive guide including:
- Detailed API reference for all methods
- Type definitions and interfaces
- Platform support (Browser & Node.js)
- Advanced usage patterns
- Username rules and service FQN format
- Examples and migration guides
## Examples
### Chat Application
```typescript
// Server
const client = new Rondevu();
await client.register();
const claim = await client.usernames.claimUsername('alice');
client.usernames.saveKeypairToStorage('alice', claim.publicKey, claim.privateKey);
const keypair = client.usernames.loadKeypairFromStorage('alice');
const service = await client.exposeService({
username: 'alice',
privateKey: keypair.privateKey,
serviceFqn: 'chat@1.0.0',
isPublic: true,
poolSize: 50, // Handle 50 concurrent users
handler: (channel, connectionId) => {
console.log(`User ${connectionId} joined`);
channel.on('message', (data) => {
console.log(`[${connectionId}]: ${data}`);
// Broadcast to all users (implement your broadcast logic)
});
channel.on('close', () => {
console.log(`User ${connectionId} left`);
});
}
});
await service.start();
// Client
const client2 = new Rondevu();
await client2.register();
const connection = await client2.connect('alice', 'chat@1.0.0');
const channel = connection.createChannel('chat');
channel.on('message', (data) => {
console.log('Message:', data);
});
await connection.connect();
channel.send('Hello everyone!');
```
### File Transfer with Progress
```typescript
// Server
const service = await client.exposeService({
username: 'alice',
privateKey: keypair.privateKey,
serviceFqn: 'files@1.0.0',
handler: (channel, connectionId) => {
channel.on('message', async (data) => {
const request = JSON.parse(data);
if (request.action === 'download') {
const file = await fs.readFile(request.path);
const chunkSize = 16 * 1024; // 16KB chunks
for (let i = 0; i < file.byteLength; i += chunkSize) {
const chunk = file.slice(i, i + chunkSize);
channel.send(chunk);
// Wait for buffer to drain if needed
while (channel.bufferedAmount > 16 * 1024 * 1024) { // 16MB
await new Promise(resolve => setTimeout(resolve, 100));
}
}
channel.send(JSON.stringify({ done: true }));
}
});
}
});
await service.start();
// Client
const connection = await client.connect('alice', 'files@1.0.0');
const channel = connection.createChannel('files');
const chunks = [];
channel.on('message', (data) => {
if (typeof data === 'string') {
const msg = JSON.parse(data);
if (msg.done) {
const blob = new Blob(chunks);
console.log('Download complete:', blob.size, 'bytes');
}
} else {
chunks.push(data);
console.log('Progress:', chunks.length * 16 * 1024, 'bytes');
}
});
await connection.connect();
channel.send(JSON.stringify({ action: 'download', path: '/file.zip' }));
```
## Platform-Specific Setup
### Modern Browsers
Works out of the box - no additional setup needed.
### Node.js 18+
Native fetch is available, but you need WebRTC polyfills:
```bash
npm install wrtc
```
```typescript
import { Rondevu } from '@xtr-dev/rondevu-client';
import { RTCPeerConnection, RTCSessionDescription, RTCIceCandidate } from 'wrtc';
const client = new Rondevu({
baseUrl: 'https://api.ronde.vu',
RTCPeerConnection,
RTCSessionDescription,
RTCIceCandidate
});
```
### Node.js < 18
Install both fetch and WebRTC polyfills:
```bash
npm install node-fetch wrtc
```
```typescript
import { Rondevu } from '@xtr-dev/rondevu-client';
import fetch from 'node-fetch';
import { RTCPeerConnection, RTCSessionDescription, RTCIceCandidate } from 'wrtc';
const client = new Rondevu({
baseUrl: 'https://api.ronde.vu',
fetch: fetch as any,
RTCPeerConnection,
RTCSessionDescription,
RTCIceCandidate
});
```
## TypeScript
All types are exported:
```typescript
import type {
// Client types
Credentials,
RondevuOptions,
// Username types
UsernameCheckResult,
UsernameClaimResult,
// Durable connection types
DurableConnectionState,
DurableChannelState,
DurableConnectionConfig,
DurableChannelConfig,
DurableServiceConfig,
QueuedMessage,
DurableConnectionEvents,
DurableChannelEvents,
DurableServiceEvents,
ConnectionInfo,
ServiceInfo
} from '@xtr-dev/rondevu-client';
```
## Migration from v0.8.x
v0.9.0 is a **breaking change** that replaces the low-level APIs with high-level durable connections. See [MIGRATION.md](./MIGRATION.md) for detailed migration guide.
**Key Changes:**
- ❌ Removed: `client.services.*`, `client.discovery.*`, `client.createPeer()` (low-level APIs)
- ✅ Added: `client.exposeService()`, `client.connect()`, `client.connectByUuid()` (durable APIs)
- ✅ Changed: Focus on durable connections with automatic reconnection and message queuing
- [React Demo](https://github.com/xtr-dev/rondevu-demo) - Full browser UI ([live](https://ronde.vu))
## License

52
eslint.config.js Normal file
View File

@@ -0,0 +1,52 @@
import js from '@eslint/js'
import tsPlugin from '@typescript-eslint/eslint-plugin'
import tsParser from '@typescript-eslint/parser'
import prettierConfig from 'eslint-config-prettier'
import prettierPlugin from 'eslint-plugin-prettier'
import unicorn from 'eslint-plugin-unicorn'
import globals from 'globals'
export default [
js.configs.recommended,
{
files: ['**/*.ts', '**/*.tsx', '**/*.js'],
languageOptions: {
parser: tsParser,
parserOptions: {
ecmaVersion: 'latest',
sourceType: 'module',
},
globals: {
...globals.browser,
...globals.node,
RTCPeerConnection: 'readonly',
RTCIceCandidate: 'readonly',
RTCSessionDescriptionInit: 'readonly',
RTCIceCandidateInit: 'readonly',
BufferSource: 'readonly',
},
},
plugins: {
'@typescript-eslint': tsPlugin,
prettier: prettierPlugin,
unicorn: unicorn,
},
rules: {
...tsPlugin.configs.recommended.rules,
...prettierConfig.rules,
'prettier/prettier': 'error',
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-unused-vars': ['warn', { argsIgnorePattern: '^_' }],
'unicorn/filename-case': [
'error',
{
case: 'kebabCase',
ignore: ['^README\\.md$'],
},
],
},
},
{
ignores: ['dist/**', 'node_modules/**', '*.config.js'],
},
]

2951
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,6 +1,6 @@
{
"name": "@xtr-dev/rondevu-client",
"version": "0.9.2",
"version": "0.17.0",
"description": "TypeScript client for Rondevu with durable WebRTC connections, automatic reconnection, and message queuing",
"type": "module",
"main": "dist/index.js",
@@ -8,6 +8,10 @@
"scripts": {
"build": "tsc",
"typecheck": "tsc --noEmit",
"dev": "vite",
"lint": "eslint src demo --ext .ts,.tsx,.js",
"lint:fix": "eslint src demo --ext .ts,.tsx,.js --fix",
"format": "prettier --write \"src/**/*.{ts,tsx,js}\" \"demo/**/*.{ts,tsx,js,html}\"",
"prepublishOnly": "npm run build"
},
"keywords": [
@@ -20,14 +24,23 @@
"author": "",
"license": "MIT",
"devDependencies": {
"typescript": "^5.9.3"
"@eslint/js": "^9.39.1",
"@typescript-eslint/eslint-plugin": "^8.48.1",
"@typescript-eslint/parser": "^8.48.1",
"eslint": "^9.39.1",
"eslint-config-prettier": "^10.1.8",
"eslint-plugin-prettier": "^5.5.4",
"eslint-plugin-unicorn": "^62.0.0",
"globals": "^16.5.0",
"prettier": "^3.7.4",
"typescript": "^5.9.3",
"vite": "^7.2.6"
},
"files": [
"dist",
"README.md"
],
"dependencies": {
"@noble/ed25519": "^3.0.0",
"@xtr-dev/rondevu-client": "^0.9.2"
"@noble/ed25519": "^3.0.0"
}
}

423
src/api.ts Normal file
View File

@@ -0,0 +1,423 @@
/**
* Rondevu API Client - RPC interface
*/
import { CryptoAdapter, Keypair } from './crypto-adapter.js'
import { WebCryptoAdapter } from './web-crypto-adapter.js'
import { RpcBatcher, BatcherOptions } from './rpc-batcher.js'
export type { Keypair } from './crypto-adapter.js'
export type { BatcherOptions } from './rpc-batcher.js'
export interface OfferRequest {
sdp: string
}
export interface ServiceRequest {
serviceFqn: string // Must include username: service:version@username
offers: OfferRequest[]
ttl?: number
signature: string
message: string
}
export interface ServiceOffer {
offerId: string
sdp: string
createdAt: number
expiresAt: number
}
export interface Service {
serviceId: string
offers: ServiceOffer[]
username: string
serviceFqn: string
createdAt: number
expiresAt: number
}
export interface IceCandidate {
candidate: RTCIceCandidateInit | null
createdAt: number
}
/**
* RPC request format
*/
interface RpcRequest {
method: string
message: string
signature: string
publicKey?: string
params?: any
}
/**
* RPC response format
*/
interface RpcResponse {
success: boolean
result?: any
error?: string
}
/**
* RondevuAPI - RPC-based API client for Rondevu signaling server
*/
export class RondevuAPI {
private crypto: CryptoAdapter
private batcher: RpcBatcher | null = null
constructor(
private baseUrl: string,
private username: string,
private keypair: Keypair,
cryptoAdapter?: CryptoAdapter,
batcherOptions?: BatcherOptions | false
) {
// Use WebCryptoAdapter by default (browser environment)
this.crypto = cryptoAdapter || new WebCryptoAdapter()
// Create batcher if not explicitly disabled
if (batcherOptions !== false) {
this.batcher = new RpcBatcher(
(requests) => this.rpcBatchDirect(requests),
batcherOptions
)
}
}
/**
* Generate authentication parameters for RPC calls
*/
private async generateAuth(method: string, params: string = ''): Promise<{
message: string
signature: string
}> {
const timestamp = Date.now()
const message = params
? `${method}:${this.username}:${params}:${timestamp}`
: `${method}:${this.username}:${timestamp}`
const signature = await this.crypto.signMessage(message, this.keypair.privateKey)
return { message, signature }
}
/**
* Execute RPC call with optional batching
*/
private async rpc(request: RpcRequest): Promise<any> {
// Use batcher if enabled
if (this.batcher) {
return await this.batcher.add(request)
}
// Direct call without batching
return await this.rpcDirect(request)
}
/**
* Execute single RPC call directly (bypasses batcher)
*/
private async rpcDirect(request: RpcRequest): Promise<any> {
const response = await fetch(`${this.baseUrl}/rpc`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
})
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
}
const result: RpcResponse = await response.json()
if (!result.success) {
throw new Error(result.error || 'RPC call failed')
}
return result.result
}
/**
* Execute batch RPC calls directly (bypasses batcher)
*/
private async rpcBatchDirect(requests: RpcRequest[]): Promise<any[]> {
const response = await fetch(`${this.baseUrl}/rpc`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(requests),
})
if (!response.ok) {
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
}
const results: RpcResponse[] = await response.json()
// Validate response is an array
if (!Array.isArray(results)) {
console.error('Invalid RPC batch response:', results)
throw new Error('Server returned invalid batch response (not an array)')
}
// Check response length matches request length
if (results.length !== requests.length) {
console.error(`Response length mismatch: expected ${requests.length}, got ${results.length}`)
}
return results.map((result, i) => {
if (!result || typeof result !== 'object') {
throw new Error(`Invalid response at index ${i}`)
}
if (!result.success) {
throw new Error(result.error || `RPC call ${i} failed`)
}
return result.result
})
}
// ============================================
// Ed25519 Cryptography Helpers
// ============================================
/**
* Generate an Ed25519 keypair for username claiming and service publishing
* @param cryptoAdapter - Optional crypto adapter (defaults to WebCryptoAdapter)
*/
static async generateKeypair(cryptoAdapter?: CryptoAdapter): Promise<Keypair> {
const adapter = cryptoAdapter || new WebCryptoAdapter()
return await adapter.generateKeypair()
}
/**
* Sign a message with an Ed25519 private key
* @param cryptoAdapter - Optional crypto adapter (defaults to WebCryptoAdapter)
*/
static async signMessage(
message: string,
privateKeyBase64: string,
cryptoAdapter?: CryptoAdapter
): Promise<string> {
const adapter = cryptoAdapter || new WebCryptoAdapter()
return await adapter.signMessage(message, privateKeyBase64)
}
/**
* Verify an Ed25519 signature
* @param cryptoAdapter - Optional crypto adapter (defaults to WebCryptoAdapter)
*/
static async verifySignature(
message: string,
signatureBase64: string,
publicKeyBase64: string,
cryptoAdapter?: CryptoAdapter
): Promise<boolean> {
const adapter = cryptoAdapter || new WebCryptoAdapter()
return await adapter.verifySignature(message, signatureBase64, publicKeyBase64)
}
// ============================================
// Username Management
// ============================================
/**
* Check if a username is available
*/
async isUsernameAvailable(username: string): Promise<boolean> {
const auth = await this.generateAuth('getUser', username)
const result = await this.rpc({
method: 'getUser',
message: auth.message,
signature: auth.signature,
params: { username },
})
return result.available
}
/**
* Check if current username is claimed
*/
async isUsernameClaimed(): Promise<boolean> {
const auth = await this.generateAuth('getUser', this.username)
const result = await this.rpc({
method: 'getUser',
message: auth.message,
signature: auth.signature,
params: { username: this.username },
})
return !result.available
}
// ============================================
// Service Management
// ============================================
/**
* Publish a service
*/
async publishService(service: ServiceRequest): Promise<Service> {
const auth = await this.generateAuth('publishService', service.serviceFqn)
return await this.rpc({
method: 'publishService',
message: auth.message,
signature: auth.signature,
publicKey: this.keypair.publicKey,
params: {
serviceFqn: service.serviceFqn,
offers: service.offers,
ttl: service.ttl,
},
})
}
/**
* Get service by FQN (direct lookup, random, or paginated)
*/
async getService(
serviceFqn: string,
options?: { limit?: number; offset?: number }
): Promise<any> {
const auth = await this.generateAuth('getService', serviceFqn)
return await this.rpc({
method: 'getService',
message: auth.message,
signature: auth.signature,
publicKey: this.keypair.publicKey,
params: {
serviceFqn,
...options,
},
})
}
/**
* Delete a service
*/
async deleteService(serviceFqn: string): Promise<void> {
const auth = await this.generateAuth('deleteService', serviceFqn)
await this.rpc({
method: 'deleteService',
message: auth.message,
signature: auth.signature,
publicKey: this.keypair.publicKey,
params: { serviceFqn },
})
}
// ============================================
// WebRTC Signaling
// ============================================
/**
* Answer an offer
*/
async answerOffer(serviceFqn: string, offerId: string, sdp: string): Promise<void> {
const auth = await this.generateAuth('answerOffer', offerId)
await this.rpc({
method: 'answerOffer',
message: auth.message,
signature: auth.signature,
publicKey: this.keypair.publicKey,
params: { serviceFqn, offerId, sdp },
})
}
/**
* Get answer for a specific offer (offerer polls this)
*/
async getOfferAnswer(
serviceFqn: string,
offerId: string
): Promise<{ sdp: string; offerId: string; answererId: string; answeredAt: number } | null> {
try {
const auth = await this.generateAuth('getOfferAnswer', offerId)
return await this.rpc({
method: 'getOfferAnswer',
message: auth.message,
signature: auth.signature,
publicKey: this.keypair.publicKey,
params: { serviceFqn, offerId },
})
} catch (err) {
if ((err as Error).message.includes('not yet answered')) {
return null
}
throw err
}
}
/**
* Combined polling for answers and ICE candidates
*/
async poll(since?: number): Promise<{
answers: Array<{
offerId: string
serviceId?: string
answererId: string
sdp: string
answeredAt: number
}>
iceCandidates: Record<
string,
Array<{
candidate: RTCIceCandidateInit | null
role: 'offerer' | 'answerer'
peerId: string
createdAt: number
}>
>
}> {
const auth = await this.generateAuth('poll')
return await this.rpc({
method: 'poll',
message: auth.message,
signature: auth.signature,
publicKey: this.keypair.publicKey,
params: { since },
})
}
/**
* Add ICE candidates to a specific offer
*/
async addOfferIceCandidates(
serviceFqn: string,
offerId: string,
candidates: RTCIceCandidateInit[]
): Promise<{ count: number; offerId: string }> {
const auth = await this.generateAuth('addIceCandidates', offerId)
return await this.rpc({
method: 'addIceCandidates',
message: auth.message,
signature: auth.signature,
publicKey: this.keypair.publicKey,
params: { serviceFqn, offerId, candidates },
})
}
/**
* Get ICE candidates for a specific offer
*/
async getOfferIceCandidates(
serviceFqn: string,
offerId: string,
since: number = 0
): Promise<{ candidates: IceCandidate[]; offerId: string }> {
const auth = await this.generateAuth('getIceCandidates', `${offerId}:${since}`)
const result = await this.rpc({
method: 'getIceCandidates',
message: auth.message,
signature: auth.signature,
publicKey: this.keypair.publicKey,
params: { serviceFqn, offerId, since },
})
return {
candidates: result.candidates || [],
offerId: result.offerId,
}
}
}

View File

@@ -1,9 +0,0 @@
/**
* ConnectionManager - Manages WebRTC peer connections
*/
export class ConnectionManager {
constructor() {
// TODO: Initialize connection manager
}
}

48
src/crypto-adapter.ts Normal file
View File

@@ -0,0 +1,48 @@
/**
* Crypto adapter interface for platform-independent cryptographic operations
*/
export interface Keypair {
publicKey: string
privateKey: string
}
/**
* Platform-independent crypto adapter interface
* Implementations provide platform-specific crypto operations
*/
export interface CryptoAdapter {
/**
* Generate an Ed25519 keypair
*/
generateKeypair(): Promise<Keypair>
/**
* Sign a message with an Ed25519 private key
*/
signMessage(message: string, privateKeyBase64: string): Promise<string>
/**
* Verify an Ed25519 signature
*/
verifySignature(
message: string,
signatureBase64: string,
publicKeyBase64: string
): Promise<boolean>
/**
* Convert Uint8Array to base64 string
*/
bytesToBase64(bytes: Uint8Array): string
/**
* Convert base64 string to Uint8Array
*/
base64ToBytes(base64: string): Uint8Array
/**
* Generate random bytes
*/
randomBytes(length: number): Uint8Array
}

View File

@@ -1,104 +0,0 @@
/**
* Type-safe EventBus with event name to payload type mapping
*/
type EventHandler<T = any> = (data: T) => void;
/**
* EventBus - Type-safe event emitter with inferred event data types
*
* @example
* interface MyEvents {
* 'user:connected': { userId: string; timestamp: number };
* 'user:disconnected': { userId: string };
* 'message:received': string;
* }
*
* const bus = new EventBus<MyEvents>();
*
* // TypeScript knows data is { userId: string; timestamp: number }
* bus.on('user:connected', (data) => {
* console.log(data.userId, data.timestamp);
* });
*
* // TypeScript knows data is string
* bus.on('message:received', (data) => {
* console.log(data.toUpperCase());
* });
*/
export class EventBus<TEvents extends Record<string, any>> {
private handlers: Map<keyof TEvents, Set<EventHandler>>;
constructor() {
this.handlers = new Map();
}
/**
* Subscribe to an event
*/
on<K extends keyof TEvents>(event: K, handler: EventHandler<TEvents[K]>): void {
if (!this.handlers.has(event)) {
this.handlers.set(event, new Set());
}
this.handlers.get(event)!.add(handler);
}
/**
* Subscribe to an event once (auto-unsubscribe after first call)
*/
once<K extends keyof TEvents>(event: K, handler: EventHandler<TEvents[K]>): void {
const wrappedHandler = (data: TEvents[K]) => {
handler(data);
this.off(event, wrappedHandler);
};
this.on(event, wrappedHandler);
}
/**
* Unsubscribe from an event
*/
off<K extends keyof TEvents>(event: K, handler: EventHandler<TEvents[K]>): void {
const eventHandlers = this.handlers.get(event);
if (eventHandlers) {
eventHandlers.delete(handler);
if (eventHandlers.size === 0) {
this.handlers.delete(event);
}
}
}
/**
* Emit an event with data
*/
emit<K extends keyof TEvents>(event: K, data: TEvents[K]): void {
const eventHandlers = this.handlers.get(event);
if (eventHandlers) {
eventHandlers.forEach(handler => handler(data));
}
}
/**
* Remove all handlers for a specific event, or all handlers if no event specified
*/
clear<K extends keyof TEvents>(event?: K): void {
if (event !== undefined) {
this.handlers.delete(event);
} else {
this.handlers.clear();
}
}
/**
* Get count of handlers for an event
*/
listenerCount<K extends keyof TEvents>(event: K): number {
return this.handlers.get(event)?.size ?? 0;
}
/**
* Get all event names that have handlers
*/
eventNames(): Array<keyof TEvents> {
return Array.from(this.handlers.keys());
}
}

View File

@@ -3,14 +3,37 @@
* WebRTC peer signaling client
*/
export { ConnectionManager } from './connection-manager.js';
export { EventBus } from './event-bus.js';
export { Rondevu } from './rondevu.js'
export { RondevuAPI } from './api.js'
export { RpcBatcher } from './rpc-batcher.js'
// Export crypto adapters
export { WebCryptoAdapter } from './web-crypto-adapter.js'
export { NodeCryptoAdapter } from './node-crypto-adapter.js'
// Export types
export type {
ConnectionIdentity,
ConnectionState,
ConnectionInterface,
Connection,
QueueMessageOptions
} from './types.js';
Signaler,
Binnable,
} from './types.js'
export type {
Keypair,
OfferRequest,
ServiceRequest,
Service,
ServiceOffer,
IceCandidate,
} from './api.js'
export type {
RondevuOptions,
PublishServiceOptions,
ConnectToServiceOptions,
ConnectionContext,
OfferContext,
OfferFactory
} from './rondevu.js'
export type { CryptoAdapter } from './crypto-adapter.js'

View File

@@ -0,0 +1,98 @@
/**
* Node.js Crypto adapter for Node.js environments
* Requires Node.js 19+ or Node.js 18 with --experimental-global-webcrypto flag
*/
import * as ed25519 from '@noble/ed25519'
import { CryptoAdapter, Keypair } from './crypto-adapter.js'
/**
* Node.js Crypto implementation using Node.js built-in APIs
* Uses Buffer for base64 encoding and crypto.randomBytes for random generation
*
* Requirements:
* - Node.js 19+ (crypto.subtle available globally)
* - OR Node.js 18 with --experimental-global-webcrypto flag
*
* @example
* ```typescript
* import { RondevuAPI } from '@xtr-dev/rondevu-client'
* import { NodeCryptoAdapter } from '@xtr-dev/rondevu-client/node'
*
* const api = new RondevuAPI(
* 'https://signal.example.com',
* 'alice',
* keypair,
* new NodeCryptoAdapter()
* )
* ```
*/
export class NodeCryptoAdapter implements CryptoAdapter {
constructor() {
// Set SHA-512 hash function for ed25519 using Node's crypto.subtle
if (typeof crypto === 'undefined' || !crypto.subtle) {
throw new Error(
'crypto.subtle is not available. ' +
'Node.js 19+ is required, or Node.js 18 with --experimental-global-webcrypto flag'
)
}
ed25519.hashes.sha512Async = async (message: Uint8Array) => {
const hash = await crypto.subtle.digest('SHA-512', message as BufferSource)
return new Uint8Array(hash)
}
}
async generateKeypair(): Promise<Keypair> {
const privateKey = ed25519.utils.randomSecretKey()
const publicKey = await ed25519.getPublicKeyAsync(privateKey)
return {
publicKey: this.bytesToBase64(publicKey),
privateKey: this.bytesToBase64(privateKey),
}
}
async signMessage(message: string, privateKeyBase64: string): Promise<string> {
const privateKey = this.base64ToBytes(privateKeyBase64)
const encoder = new TextEncoder()
const messageBytes = encoder.encode(message)
const signature = await ed25519.signAsync(messageBytes, privateKey)
return this.bytesToBase64(signature)
}
async verifySignature(
message: string,
signatureBase64: string,
publicKeyBase64: string
): Promise<boolean> {
try {
const signature = this.base64ToBytes(signatureBase64)
const publicKey = this.base64ToBytes(publicKeyBase64)
const encoder = new TextEncoder()
const messageBytes = encoder.encode(message)
return await ed25519.verifyAsync(signature, messageBytes, publicKey)
} catch {
return false
}
}
bytesToBase64(bytes: Uint8Array): string {
// Node.js Buffer provides native base64 encoding
// @ts-expect-error - Buffer is available in Node.js but not in browser TypeScript definitions
return Buffer.from(bytes).toString('base64')
}
base64ToBytes(base64: string): Uint8Array {
// Node.js Buffer provides native base64 decoding
// @ts-expect-error - Buffer is available in Node.js but not in browser TypeScript definitions
return new Uint8Array(Buffer.from(base64, 'base64'))
}
randomBytes(length: number): Uint8Array {
// Use Web Crypto API's getRandomValues (available in Node 19+)
return crypto.getRandomValues(new Uint8Array(length))
}
}

888
src/rondevu.ts Normal file
View File

@@ -0,0 +1,888 @@
import { RondevuAPI, Keypair, IceCandidate, BatcherOptions } from './api.js'
import { CryptoAdapter } from './crypto-adapter.js'
// ICE server preset names
export type IceServerPreset = 'ipv4-turn' | 'hostname-turns' | 'google-stun' | 'relay-only'
// ICE server presets
export const ICE_SERVER_PRESETS: Record<IceServerPreset, RTCIceServer[]> = {
'ipv4-turn': [
{ urls: 'stun:57.129.61.67:3478' },
{
urls: [
'turn:57.129.61.67:3478?transport=tcp',
'turn:57.129.61.67:3478?transport=udp',
],
username: 'webrtcuser',
credential: 'supersecretpassword'
}
],
'hostname-turns': [
{ urls: 'stun:turn.share.fish:3478' },
{
urls: [
'turns:turn.share.fish:5349?transport=tcp',
'turns:turn.share.fish:5349?transport=udp',
'turn:turn.share.fish:3478?transport=tcp',
'turn:turn.share.fish:3478?transport=udp',
],
username: 'webrtcuser',
credential: 'supersecretpassword'
}
],
'google-stun': [
{ urls: 'stun:stun.l.google.com:19302' },
{ urls: 'stun:stun1.l.google.com:19302' }
],
'relay-only': [
{ urls: 'stun:57.129.61.67:3478' },
{
urls: [
'turn:57.129.61.67:3478?transport=tcp',
'turn:57.129.61.67:3478?transport=udp',
],
username: 'webrtcuser',
credential: 'supersecretpassword',
// @ts-expect-error - iceTransportPolicy is valid but not in RTCIceServer type
iceTransportPolicy: 'relay'
}
]
}
export interface RondevuOptions {
apiUrl: string
username?: string // Optional, will generate anonymous if not provided
keypair?: Keypair // Optional, will generate if not provided
cryptoAdapter?: CryptoAdapter // Optional, defaults to WebCryptoAdapter
batching?: BatcherOptions | false // Optional, defaults to enabled with default options
iceServers?: IceServerPreset | RTCIceServer[] // Optional: preset name or custom STUN/TURN servers
debug?: boolean // Optional: enable debug logging (default: false)
}
export interface OfferContext {
pc: RTCPeerConnection
dc?: RTCDataChannel
offer: RTCSessionDescriptionInit
}
export type OfferFactory = (rtcConfig: RTCConfiguration) => Promise<OfferContext>
export interface PublishServiceOptions {
service: string // Service name and version (e.g., "chat:2.0.0") - username will be auto-appended
maxOffers: number // Maximum number of concurrent offers to maintain
offerFactory?: OfferFactory // Optional: custom offer creation (defaults to simple data channel)
ttl?: number // Time-to-live for offers in milliseconds (default: 300000)
}
export interface ConnectionContext {
pc: RTCPeerConnection
dc: RTCDataChannel
serviceFqn: string
offerId: string
peerUsername: string
}
export interface ConnectToServiceOptions {
serviceFqn?: string // Full FQN like 'chat:2.0.0@alice'
service?: string // Service without username (for discovery)
username?: string // Target username (combined with service)
onConnection?: (context: ConnectionContext) => void | Promise<void> // Called when data channel opens
rtcConfig?: RTCConfiguration // Optional: override default ICE servers
}
interface ActiveOffer {
offerId: string
serviceFqn: string
pc: RTCPeerConnection
dc?: RTCDataChannel
answered: boolean
createdAt: number
}
/**
* Rondevu - Complete WebRTC signaling client
*
* Provides a unified API for:
* - Implicit username claiming (auto-claimed on first authenticated request)
* - Service publishing with automatic signature generation
* - Service discovery (direct, random, paginated)
* - WebRTC signaling (offer/answer exchange, ICE relay)
* - Keypair management
*
* @example
* ```typescript
* // Create and initialize Rondevu instance with preset ICE servers
* const rondevu = await Rondevu.connect({
* apiUrl: 'https://signal.example.com',
* username: 'alice',
* iceServers: 'ipv4-turn' // Use preset: 'ipv4-turn', 'hostname-turns', 'google-stun', or 'relay-only'
* })
*
* // Or use custom ICE servers
* const rondevu2 = await Rondevu.connect({
* apiUrl: 'https://signal.example.com',
* username: 'bob',
* iceServers: [
* { urls: 'stun:stun.l.google.com:19302' },
* { urls: 'turn:turn.example.com:3478', username: 'user', credential: 'pass' }
* ]
* })
*
* // Publish a service with automatic offer management
* await rondevu.publishService({
* service: 'chat:2.0.0',
* maxOffers: 5, // Maintain up to 5 concurrent offers
* offerFactory: async (rtcConfig) => {
* const pc = new RTCPeerConnection(rtcConfig)
* const dc = pc.createDataChannel('chat')
* const offer = await pc.createOffer()
* await pc.setLocalDescription(offer)
* return { pc, dc, offer }
* }
* })
*
* // Start accepting connections (auto-fills offers and polls)
* await rondevu.startFilling()
*
* // Access active connections
* for (const offer of rondevu.getActiveOffers()) {
* offer.dc?.addEventListener('message', (e) => console.log(e.data))
* }
*
* // Stop when done
* rondevu.stopFilling()
* ```
*/
export class Rondevu {
// Constants
private static readonly DEFAULT_TTL_MS = 300000 // 5 minutes
private static readonly POLLING_INTERVAL_MS = 1000 // 1 second
private api: RondevuAPI
private readonly apiUrl: string
private username: string
private keypair: Keypair
private usernameClaimed = false
private cryptoAdapter?: CryptoAdapter
private batchingOptions?: BatcherOptions | false
private iceServers: RTCIceServer[]
private debugEnabled: boolean
// Service management
private currentService: string | null = null
private maxOffers = 0
private offerFactory: OfferFactory | null = null
private ttl = Rondevu.DEFAULT_TTL_MS
private activeOffers = new Map<string, ActiveOffer>()
// Polling
private filling = false
private pollingInterval: ReturnType<typeof setInterval> | null = null
private lastPollTimestamp = 0
private constructor(
apiUrl: string,
username: string,
keypair: Keypair,
api: RondevuAPI,
iceServers: RTCIceServer[],
cryptoAdapter?: CryptoAdapter,
batchingOptions?: BatcherOptions | false,
debugEnabled = false
) {
this.apiUrl = apiUrl
this.username = username
this.keypair = keypair
this.api = api
this.iceServers = iceServers
this.cryptoAdapter = cryptoAdapter
this.batchingOptions = batchingOptions
this.debugEnabled = debugEnabled
this.debug('Instance created:', {
username: this.username,
publicKey: this.keypair.publicKey,
hasIceServers: iceServers.length > 0,
batchingEnabled: batchingOptions !== false
})
}
/**
* Internal debug logging - only logs if debug mode is enabled
*/
private debug(message: string, ...args: any[]): void {
if (this.debugEnabled) {
console.log(`[Rondevu] ${message}`, ...args)
}
}
/**
* Create and initialize a Rondevu client
*
* @example
* ```typescript
* const rondevu = await Rondevu.connect({
* apiUrl: 'https://api.ronde.vu',
* username: 'alice'
* })
* ```
*/
static async connect(options: RondevuOptions): Promise<Rondevu> {
const username = options.username || Rondevu.generateAnonymousUsername()
// Handle preset string or custom array
let iceServers: RTCIceServer[]
if (typeof options.iceServers === 'string') {
iceServers = ICE_SERVER_PRESETS[options.iceServers]
} else {
iceServers = options.iceServers || [
{ urls: 'stun:stun.l.google.com:19302' }
]
}
if (options.debug) {
console.log('[Rondevu] Connecting:', {
username,
hasKeypair: !!options.keypair,
iceServers: iceServers.length,
batchingEnabled: options.batching !== false
})
}
// Generate keypair if not provided
let keypair = options.keypair
if (!keypair) {
if (options.debug) console.log('[Rondevu] Generating new keypair...')
keypair = await RondevuAPI.generateKeypair(options.cryptoAdapter)
if (options.debug) console.log('[Rondevu] Generated keypair, publicKey:', keypair.publicKey)
} else {
if (options.debug) console.log('[Rondevu] Using existing keypair, publicKey:', keypair.publicKey)
}
// Create API instance
const api = new RondevuAPI(
options.apiUrl,
username,
keypair,
options.cryptoAdapter,
options.batching
)
if (options.debug) console.log('[Rondevu] Created API instance')
return new Rondevu(
options.apiUrl,
username,
keypair,
api,
iceServers,
options.cryptoAdapter,
options.batching,
options.debug || false
)
}
/**
* Generate an anonymous username with timestamp and random component
*/
private static generateAnonymousUsername(): string {
const timestamp = Date.now().toString(36)
const random = Array.from(crypto.getRandomValues(new Uint8Array(3)))
.map(b => b.toString(16).padStart(2, '0')).join('')
return `anon-${timestamp}-${random}`
}
// ============================================
// Username Management
// ============================================
/**
* Check if username has been claimed (checks with server)
*/
async isUsernameClaimed(): Promise<boolean> {
try {
const claimed = await this.api.isUsernameClaimed()
// Update internal flag to match server state
this.usernameClaimed = claimed
return claimed
} catch (err) {
console.error('Failed to check username claim status:', err)
return false
}
}
// ============================================
// Service Publishing
// ============================================
/**
* Default offer factory - creates a simple data channel connection
*/
private async defaultOfferFactory(rtcConfig: RTCConfiguration): Promise<OfferContext> {
const pc = new RTCPeerConnection(rtcConfig)
const dc = pc.createDataChannel('default')
const offer = await pc.createOffer()
await pc.setLocalDescription(offer)
return { pc, dc, offer }
}
/**
* Publish a service with automatic offer management
* Call startFilling() to begin accepting connections
*
* @example
* ```typescript
* await rondevu.publishService({
* service: 'chat:2.0.0',
* maxOffers: 5
* })
* await rondevu.startFilling()
* ```
*/
async publishService(options: PublishServiceOptions): Promise<void> {
const { service, maxOffers, offerFactory, ttl } = options
this.currentService = service
this.maxOffers = maxOffers
this.offerFactory = offerFactory || this.defaultOfferFactory.bind(this)
this.ttl = ttl || Rondevu.DEFAULT_TTL_MS
this.debug(`Publishing service: ${service} with maxOffers: ${maxOffers}`)
this.usernameClaimed = true
}
/**
* Set up ICE candidate handler to send candidates to the server
*/
private setupIceCandidateHandler(
pc: RTCPeerConnection,
serviceFqn: string,
offerId: string
): void {
pc.onicecandidate = async (event) => {
if (event.candidate) {
try {
await this.api.addOfferIceCandidates(
serviceFqn,
offerId,
[event.candidate.toJSON()]
)
} catch (err) {
console.error('[Rondevu] Failed to send ICE candidate:', err)
}
}
}
}
/**
* Create a single offer and publish it to the server
*/
private async createOffer(): Promise<void> {
if (!this.currentService || !this.offerFactory) {
throw new Error('Service not published. Call publishService() first.')
}
const rtcConfig: RTCConfiguration = {
iceServers: this.iceServers
}
this.debug('Creating new offer...')
// Create the offer using the factory
const { pc, dc, offer } = await this.offerFactory(rtcConfig)
// Auto-append username to service
const serviceFqn = `${this.currentService}@${this.username}`
// Publish to server
const result = await this.api.publishService({
serviceFqn,
offers: [{ sdp: offer.sdp! }],
ttl: this.ttl,
signature: '',
message: '',
})
const offerId = result.offers[0].offerId
// Store active offer
this.activeOffers.set(offerId, {
offerId,
serviceFqn,
pc,
dc,
answered: false,
createdAt: Date.now()
})
this.debug(`Offer created: ${offerId}`)
// Set up ICE candidate handler
this.setupIceCandidateHandler(pc, serviceFqn, offerId)
// Monitor connection state
pc.onconnectionstatechange = () => {
this.debug(`Offer ${offerId} connection state: ${pc.connectionState}`)
if (pc.connectionState === 'failed' || pc.connectionState === 'closed') {
this.activeOffers.delete(offerId)
this.fillOffers() // Try to replace failed offer
}
}
}
/**
* Fill offers to reach maxOffers count
*/
private async fillOffers(): Promise<void> {
if (!this.filling || !this.currentService) return
const currentCount = this.activeOffers.size
const needed = this.maxOffers - currentCount
this.debug(`Filling offers: current=${currentCount}, needed=${needed}`)
for (let i = 0; i < needed; i++) {
try {
await this.createOffer()
} catch (err) {
console.error('[Rondevu] Failed to create offer:', err)
}
}
}
/**
* Poll for answers and ICE candidates (internal use for automatic offer management)
*/
private async pollInternal(): Promise<void> {
if (!this.filling) return
try {
const result = await this.api.poll(this.lastPollTimestamp)
// Process answers
for (const answer of result.answers) {
const activeOffer = this.activeOffers.get(answer.offerId)
if (activeOffer && !activeOffer.answered) {
this.debug(`Received answer for offer ${answer.offerId}`)
await activeOffer.pc.setRemoteDescription({
type: 'answer',
sdp: answer.sdp
})
activeOffer.answered = true
this.lastPollTimestamp = answer.answeredAt
// Create replacement offer
this.fillOffers()
}
}
// Process ICE candidates
for (const [offerId, candidates] of Object.entries(result.iceCandidates)) {
const activeOffer = this.activeOffers.get(offerId)
if (activeOffer) {
const answererCandidates = candidates.filter(c => c.role === 'answerer')
for (const item of answererCandidates) {
if (item.candidate) {
await activeOffer.pc.addIceCandidate(new RTCIceCandidate(item.candidate))
this.lastPollTimestamp = Math.max(this.lastPollTimestamp, item.createdAt)
}
}
}
}
} catch (err) {
console.error('[Rondevu] Polling error:', err)
}
}
/**
* Start filling offers and polling for answers/ICE
* Call this after publishService() to begin accepting connections
*/
async startFilling(): Promise<void> {
if (this.filling) {
this.debug('Already filling')
return
}
if (!this.currentService) {
throw new Error('No service published. Call publishService() first.')
}
this.debug('Starting offer filling and polling')
this.filling = true
// Fill initial offers
await this.fillOffers()
// Start polling
this.pollingInterval = setInterval(() => {
this.pollInternal()
}, Rondevu.POLLING_INTERVAL_MS)
}
/**
* Stop filling offers and polling
* Closes all active peer connections
*/
stopFilling(): void {
this.debug('Stopping offer filling and polling')
this.filling = false
// Stop polling
if (this.pollingInterval) {
clearInterval(this.pollingInterval)
this.pollingInterval = null
}
// Close all active connections
for (const [offerId, offer] of this.activeOffers.entries()) {
this.debug(`Closing offer ${offerId}`)
offer.dc?.close()
offer.pc.close()
}
this.activeOffers.clear()
}
/**
* Resolve the full service FQN from various input options
* Supports direct FQN, service+username, or service discovery
*/
private async resolveServiceFqn(options: ConnectToServiceOptions): Promise<string> {
const { serviceFqn, service, username } = options
if (serviceFqn) {
return serviceFqn
} else if (service && username) {
return `${service}@${username}`
} else if (service) {
// Discovery mode - get random service
this.debug(`Discovering service: ${service}`)
const discovered = await this.discoverService(service)
return discovered.serviceFqn
} else {
throw new Error('Either serviceFqn or service must be provided')
}
}
/**
* Start polling for remote ICE candidates
* Returns the polling interval ID
*/
private startIcePolling(
pc: RTCPeerConnection,
serviceFqn: string,
offerId: string
): ReturnType<typeof setInterval> {
let lastIceTimestamp = 0
return setInterval(async () => {
try {
const result = await this.api.getOfferIceCandidates(
serviceFqn,
offerId,
lastIceTimestamp
)
for (const item of result.candidates) {
if (item.candidate) {
await pc.addIceCandidate(new RTCIceCandidate(item.candidate))
lastIceTimestamp = item.createdAt
}
}
} catch (err) {
console.error('[Rondevu] Failed to poll ICE candidates:', err)
}
}, Rondevu.POLLING_INTERVAL_MS)
}
/**
* Automatically connect to a service (answerer side)
* Handles the entire connection flow: discovery, WebRTC setup, answer exchange, ICE candidates
*
* @example
* ```typescript
* // Connect to specific user
* const connection = await rondevu.connectToService({
* serviceFqn: 'chat:2.0.0@alice',
* onConnection: ({ dc, peerUsername }) => {
* console.log('Connected to', peerUsername)
* dc.addEventListener('message', (e) => console.log(e.data))
* dc.addEventListener('open', () => dc.send('Hello!'))
* }
* })
*
* // Discover random service
* const connection = await rondevu.connectToService({
* service: 'chat:2.0.0',
* onConnection: ({ dc, peerUsername }) => {
* console.log('Connected to', peerUsername)
* }
* })
* ```
*/
async connectToService(options: ConnectToServiceOptions): Promise<ConnectionContext> {
const { onConnection, rtcConfig } = options
// Validate inputs
if (options.serviceFqn !== undefined && typeof options.serviceFqn === 'string' && !options.serviceFqn.trim()) {
throw new Error('serviceFqn cannot be empty')
}
if (options.service !== undefined && typeof options.service === 'string' && !options.service.trim()) {
throw new Error('service cannot be empty')
}
if (options.username !== undefined && typeof options.username === 'string' && !options.username.trim()) {
throw new Error('username cannot be empty')
}
// Determine the full service FQN
const fqn = await this.resolveServiceFqn(options)
this.debug(`Connecting to service: ${fqn}`)
// 1. Get service offer
const serviceData = await this.api.getService(fqn)
this.debug(`Found service from @${serviceData.username}`)
// 2. Create RTCPeerConnection
const rtcConfiguration = rtcConfig || {
iceServers: this.iceServers
}
const pc = new RTCPeerConnection(rtcConfiguration)
// 3. Set up data channel handler (answerer receives it from offerer)
let dc: RTCDataChannel | null = null
const dataChannelPromise = new Promise<RTCDataChannel>((resolve) => {
pc.ondatachannel = (event) => {
this.debug('Data channel received from offerer')
dc = event.channel
resolve(dc)
}
})
// 4. Set up ICE candidate exchange
this.setupIceCandidateHandler(pc, serviceData.serviceFqn, serviceData.offerId)
// 5. Poll for remote ICE candidates
const icePollInterval = this.startIcePolling(pc, serviceData.serviceFqn, serviceData.offerId)
// 6. Set remote description
await pc.setRemoteDescription({
type: 'offer',
sdp: serviceData.sdp
})
// 7. Create and send answer
const answer = await pc.createAnswer()
await pc.setLocalDescription(answer)
await this.api.answerOffer(
serviceData.serviceFqn,
serviceData.offerId,
answer.sdp!
)
// 8. Wait for data channel to be established
dc = await dataChannelPromise
// Create connection context
const context: ConnectionContext = {
pc,
dc,
serviceFqn: serviceData.serviceFqn,
offerId: serviceData.offerId,
peerUsername: serviceData.username
}
// 9. Set up connection state monitoring
pc.onconnectionstatechange = () => {
this.debug(`Connection state: ${pc.connectionState}`)
if (pc.connectionState === 'failed' || pc.connectionState === 'closed') {
clearInterval(icePollInterval)
}
}
// 10. Wait for data channel to open and call onConnection
if (dc.readyState === 'open') {
this.debug('Data channel already open')
if (onConnection) {
await onConnection(context)
}
} else {
await new Promise<void>((resolve) => {
dc!.addEventListener('open', async () => {
this.debug('Data channel opened')
if (onConnection) {
await onConnection(context)
}
resolve()
})
})
}
return context
}
// ============================================
// Service Discovery
// ============================================
/**
* Get service by FQN (with username) - Direct lookup
* Example: chat:1.0.0@alice
*/
async getService(serviceFqn: string): Promise<{
serviceId: string
username: string
serviceFqn: string
offerId: string
sdp: string
createdAt: number
expiresAt: number
}> {
return await this.api.getService(serviceFqn)
}
/**
* Discover a random available service without knowing the username
* Example: chat:1.0.0 (without @username)
*/
async discoverService(serviceVersion: string): Promise<{
serviceId: string
username: string
serviceFqn: string
offerId: string
sdp: string
createdAt: number
expiresAt: number
}> {
return await this.api.getService(serviceVersion)
}
/**
* Discover multiple available services with pagination
* Example: chat:1.0.0 (without @username)
*/
async discoverServices(serviceVersion: string, limit: number = 10, offset: number = 0): Promise<{
services: Array<{
serviceId: string
username: string
serviceFqn: string
offerId: string
sdp: string
createdAt: number
expiresAt: number
}>
count: number
limit: number
offset: number
}> {
return await this.api.getService(serviceVersion, { limit, offset })
}
// ============================================
// WebRTC Signaling
// ============================================
/**
* Post answer SDP to specific offer
*/
async postOfferAnswer(serviceFqn: string, offerId: string, sdp: string): Promise<{
success: boolean
offerId: string
}> {
await this.api.answerOffer(serviceFqn, offerId, sdp)
return { success: true, offerId }
}
/**
* Get answer SDP (offerer polls this)
*/
async getOfferAnswer(serviceFqn: string, offerId: string): Promise<{
sdp: string
offerId: string
answererId: string
answeredAt: number
} | null> {
return await this.api.getOfferAnswer(serviceFqn, offerId)
}
/**
* Combined polling for answers and ICE candidates
* Returns all answered offers and ICE candidates for all peer's offers since timestamp
*/
async poll(since?: number): Promise<{
answers: Array<{
offerId: string
serviceId?: string
answererId: string
sdp: string
answeredAt: number
}>
iceCandidates: Record<string, Array<{
candidate: RTCIceCandidateInit | null
role: 'offerer' | 'answerer'
peerId: string
createdAt: number
}>>
}> {
return await this.api.poll(since)
}
/**
* Add ICE candidates to specific offer
*/
async addOfferIceCandidates(serviceFqn: string, offerId: string, candidates: RTCIceCandidateInit[]): Promise<{
count: number
offerId: string
}> {
return await this.api.addOfferIceCandidates(serviceFqn, offerId, candidates)
}
/**
* Get ICE candidates for specific offer (with polling support)
*/
async getOfferIceCandidates(serviceFqn: string, offerId: string, since: number = 0): Promise<{
candidates: IceCandidate[]
offerId: string
}> {
return await this.api.getOfferIceCandidates(serviceFqn, offerId, since)
}
// ============================================
// Utility Methods
// ============================================
/**
* Get the current keypair (for backup/storage)
*/
getKeypair(): Keypair {
return this.keypair
}
/**
* Get the username
*/
getUsername(): string {
return this.username
}
/**
* Get the public key
*/
getPublicKey(): string {
return this.keypair.publicKey
}
/**
* Access to underlying API for advanced operations
* @deprecated Use direct methods on Rondevu instance instead
*/
getAPIPublic(): RondevuAPI {
return this.api
}
}

157
src/rpc-batcher.ts Normal file
View File

@@ -0,0 +1,157 @@
/**
* RPC Batcher - Throttles and batches RPC requests to reduce HTTP overhead
*/
export interface BatcherOptions {
/**
* Maximum number of requests to batch together
* Default: 10
*/
maxBatchSize?: number
/**
* Maximum time to wait before sending a batch (ms)
* Default: 50ms
*/
maxWaitTime?: number
/**
* Minimum time between batches (ms)
* Default: 10ms
*/
throttleInterval?: number
}
interface QueuedRequest {
request: any
resolve: (value: any) => void
reject: (error: Error) => void
}
/**
* Batches and throttles RPC requests to optimize network usage
*
* @example
* ```typescript
* const batcher = new RpcBatcher(
* (requests) => api.rpcBatch(requests),
* { maxBatchSize: 10, maxWaitTime: 50 }
* )
*
* // These will be batched together if called within maxWaitTime
* const result1 = await batcher.add(request1)
* const result2 = await batcher.add(request2)
* const result3 = await batcher.add(request3)
* ```
*/
export class RpcBatcher {
private queue: QueuedRequest[] = []
private batchTimeout: ReturnType<typeof setTimeout> | null = null
private lastBatchTime: number = 0
private options: Required<BatcherOptions>
private sendBatch: (requests: any[]) => Promise<any[]>
constructor(
sendBatch: (requests: any[]) => Promise<any[]>,
options?: BatcherOptions
) {
this.sendBatch = sendBatch
this.options = {
maxBatchSize: options?.maxBatchSize ?? 10,
maxWaitTime: options?.maxWaitTime ?? 50,
throttleInterval: options?.throttleInterval ?? 10,
}
}
/**
* Add an RPC request to the batch queue
* Returns a promise that resolves when the request completes
*/
async add(request: any): Promise<any> {
return new Promise((resolve, reject) => {
this.queue.push({ request, resolve, reject })
// Send immediately if batch is full
if (this.queue.length >= this.options.maxBatchSize) {
this.flush()
return
}
// Schedule batch if not already scheduled
if (!this.batchTimeout) {
this.batchTimeout = setTimeout(() => {
this.flush()
}, this.options.maxWaitTime)
}
})
}
/**
* Flush the queue immediately
*/
async flush(): Promise<void> {
// Clear timeout if set
if (this.batchTimeout) {
clearTimeout(this.batchTimeout)
this.batchTimeout = null
}
// Nothing to flush
if (this.queue.length === 0) {
return
}
// Throttle: wait if we sent a batch too recently
const now = Date.now()
const timeSinceLastBatch = now - this.lastBatchTime
if (timeSinceLastBatch < this.options.throttleInterval) {
const waitTime = this.options.throttleInterval - timeSinceLastBatch
await new Promise(resolve => setTimeout(resolve, waitTime))
}
// Extract requests from queue
const batch = this.queue.splice(0, this.options.maxBatchSize)
const requests = batch.map(item => item.request)
this.lastBatchTime = Date.now()
try {
// Send batch request
const results = await this.sendBatch(requests)
// Resolve individual promises
for (let i = 0; i < batch.length; i++) {
batch[i].resolve(results[i])
}
} catch (error) {
// Reject all promises in batch
for (const item of batch) {
item.reject(error as Error)
}
}
}
/**
* Get current queue size
*/
getQueueSize(): number {
return this.queue.length
}
/**
* Clear the queue without sending
*/
clear(): void {
if (this.batchTimeout) {
clearTimeout(this.batchTimeout)
this.batchTimeout = null
}
// Reject all pending requests
for (const item of this.queue) {
item.reject(new Error('Batch queue cleared'))
}
this.queue = []
}
}

View File

@@ -1,24 +1,20 @@
/**
* Core connection types
* Core signaling types
*/
export interface ConnectionIdentity {
id: string;
hostUsername: string;
}
/**
* Cleanup function returned by listener methods
*/
export type Binnable = () => void
export interface ConnectionState {
state: 'connected' | 'disconnected' | 'connecting';
lastActive: number;
/**
* Signaler interface for WebRTC offer/answer/ICE exchange
*/
export interface Signaler {
addIceCandidate(candidate: RTCIceCandidate): Promise<void>
addListener(callback: (candidate: RTCIceCandidate) => void): Binnable
addOfferListener(callback: (offer: RTCSessionDescriptionInit) => void): Binnable
addAnswerListener(callback: (answer: RTCSessionDescriptionInit) => void): Binnable
setOffer(offer: RTCSessionDescriptionInit): Promise<void>
setAnswer(answer: RTCSessionDescriptionInit): Promise<void>
}
export interface QueueMessageOptions {
expiresAt?: number;
}
export interface ConnectionInterface {
queueMessage(message: string | ArrayBuffer, options?: QueueMessageOptions): void;
sendMessage(message: string | ArrayBuffer): void;
}
export type Connection = ConnectionIdentity & ConnectionState & ConnectionInterface;

67
src/web-crypto-adapter.ts Normal file
View File

@@ -0,0 +1,67 @@
/**
* Web Crypto adapter for browser environments
*/
import * as ed25519 from '@noble/ed25519'
import { CryptoAdapter, Keypair } from './crypto-adapter.js'
// Set SHA-512 hash function for ed25519 (required in @noble/ed25519 v3+)
ed25519.hashes.sha512Async = async (message: Uint8Array) => {
return new Uint8Array(await crypto.subtle.digest('SHA-512', message as BufferSource))
}
/**
* Web Crypto implementation using browser APIs
* Uses btoa/atob for base64 encoding and crypto.getRandomValues for random bytes
*/
export class WebCryptoAdapter implements CryptoAdapter {
async generateKeypair(): Promise<Keypair> {
const privateKey = ed25519.utils.randomSecretKey()
const publicKey = await ed25519.getPublicKeyAsync(privateKey)
return {
publicKey: this.bytesToBase64(publicKey),
privateKey: this.bytesToBase64(privateKey),
}
}
async signMessage(message: string, privateKeyBase64: string): Promise<string> {
const privateKey = this.base64ToBytes(privateKeyBase64)
const encoder = new TextEncoder()
const messageBytes = encoder.encode(message)
const signature = await ed25519.signAsync(messageBytes, privateKey)
return this.bytesToBase64(signature)
}
async verifySignature(
message: string,
signatureBase64: string,
publicKeyBase64: string
): Promise<boolean> {
try {
const signature = this.base64ToBytes(signatureBase64)
const publicKey = this.base64ToBytes(publicKeyBase64)
const encoder = new TextEncoder()
const messageBytes = encoder.encode(message)
return await ed25519.verifyAsync(signature, messageBytes, publicKey)
} catch {
return false
}
}
bytesToBase64(bytes: Uint8Array): string {
const binString = Array.from(bytes, byte => String.fromCodePoint(byte)).join('')
return btoa(binString)
}
base64ToBytes(base64: string): Uint8Array {
const binString = atob(base64)
return Uint8Array.from(binString, char => char.codePointAt(0)!)
}
randomBytes(length: number): Uint8Array {
return crypto.getRandomValues(new Uint8Array(length))
}
}