mirror of
https://github.com/xtr-dev/rondevu-server.git
synced 2025-12-13 20:33:25 +00:00
Compare commits
61 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 9e93ed506e | |||
| 9002fe3f6d | |||
| 88a038a12a | |||
| 3c0d1c8411 | |||
| 53a576670e | |||
| 7e2e8c703e | |||
| 05fe34be01 | |||
| 68bb28bbc2 | |||
| 677bbbb37e | |||
| caae10bcac | |||
| 34babd036e | |||
| 876ac2602c | |||
| df9f3311e9 | |||
| 9f30f8b46d | |||
| 17765a9f4f | |||
| 4e73157a16 | |||
| 8d47424a82 | |||
| 1612bd78b7 | |||
| 01b751afc3 | |||
| 0a98ace6f7 | |||
| 51fe405440 | |||
| 95596dd462 | |||
| 1bf21d7df8 | |||
| e3ede0033e | |||
| cfa58f1dfa | |||
| c14a8c24fc | |||
| b282bf6470 | |||
| 9088abe305 | |||
| 00c5bbc501 | |||
| 85a3de65e2 | |||
| 8111cb9cec | |||
| b446adaee4 | |||
| 163e1f73d4 | |||
| 1d47d47ef7 | |||
| 1d70cd79e8 | |||
| 2aa1fee4d6 | |||
| d564e2250f | |||
| 06ec5020f7 | |||
| 5c71f66a26 | |||
| ca3db47009 | |||
| 3efed6e9d2 | |||
| 1257867dff | |||
| 52cf734858 | |||
| 5622867411 | |||
| ac0e064e34 | |||
| e7cd90b905 | |||
| 67b1decbad | |||
| e9d0f26726 | |||
| 595eac8692 | |||
| 65a13fefa4 | |||
| 1dadf5461e | |||
| bd35f7919c | |||
| 683bc42bf0 | |||
| c3fc498c81 | |||
| 4f772c50c9 | |||
| 08e1433088 | |||
| 70d018c666 | |||
| 2cff4c8544 | |||
| 00499732c4 | |||
| 341d043358 | |||
| 23c27d4509 |
502
ADVANCED.md
Normal file
502
ADVANCED.md
Normal file
@@ -0,0 +1,502 @@
|
|||||||
|
# Rondevu Server - Advanced Usage
|
||||||
|
|
||||||
|
Comprehensive API reference, configuration guide, database schema, and security details.
|
||||||
|
|
||||||
|
## Table of Contents
|
||||||
|
|
||||||
|
- [RPC Methods](#rpc-methods)
|
||||||
|
- [Configuration](#configuration)
|
||||||
|
- [Database Schema](#database-schema)
|
||||||
|
- [Security](#security)
|
||||||
|
- [Migration Guide](#migration-guide)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## RPC Methods
|
||||||
|
|
||||||
|
### `getUser`
|
||||||
|
Check username availability
|
||||||
|
|
||||||
|
**Parameters:**
|
||||||
|
- `username` - Username to check
|
||||||
|
|
||||||
|
**Message format:** `getUser:{username}:{timestamp}` (no authentication required)
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"method": "getUser",
|
||||||
|
"message": "getUser:alice:1733404800000",
|
||||||
|
"signature": "base64-signature",
|
||||||
|
"params": { "username": "alice" }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"result": {
|
||||||
|
"username": "alice",
|
||||||
|
"available": false,
|
||||||
|
"claimedAt": 1733404800000,
|
||||||
|
"expiresAt": 1765027200000,
|
||||||
|
"publicKey": "base64-encoded-public-key"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `claimUsername`
|
||||||
|
Claim a username with cryptographic proof
|
||||||
|
|
||||||
|
**Parameters:**
|
||||||
|
- `username` - Username to claim
|
||||||
|
- `publicKey` - Base64-encoded Ed25519 public key
|
||||||
|
|
||||||
|
**Message format:** `claim:{username}:{timestamp}`
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"method": "claimUsername",
|
||||||
|
"message": "claim:alice:1733404800000",
|
||||||
|
"signature": "base64-signature",
|
||||||
|
"params": {
|
||||||
|
"username": "alice",
|
||||||
|
"publicKey": "base64-encoded-public-key"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"result": {
|
||||||
|
"success": true,
|
||||||
|
"username": "alice"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `getService`
|
||||||
|
Get service by FQN (direct lookup, random discovery, or paginated)
|
||||||
|
|
||||||
|
**Parameters:**
|
||||||
|
- `serviceFqn` - Service FQN (e.g., `chat:1.0.0` or `chat:1.0.0@alice`)
|
||||||
|
- `limit` - (optional) Number of results for paginated mode
|
||||||
|
- `offset` - (optional) Offset for paginated mode
|
||||||
|
|
||||||
|
**Message format:** `getService:{username}:{serviceFqn}:{timestamp}`
|
||||||
|
|
||||||
|
**Modes:**
|
||||||
|
1. **Direct lookup** (with @username): Returns specific user's service
|
||||||
|
2. **Random** (without @username, no limit): Returns random service
|
||||||
|
3. **Paginated** (without @username, with limit): Returns multiple services
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"method": "getService",
|
||||||
|
"message": "getService:bob:chat:1.0.0:1733404800000",
|
||||||
|
"signature": "base64-signature",
|
||||||
|
"params": {
|
||||||
|
"serviceFqn": "chat:1.0.0@alice"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"result": {
|
||||||
|
"serviceId": "uuid",
|
||||||
|
"username": "alice",
|
||||||
|
"serviceFqn": "chat:1.0.0@alice",
|
||||||
|
"offerId": "offer-hash",
|
||||||
|
"sdp": "v=0...",
|
||||||
|
"createdAt": 1733404800000,
|
||||||
|
"expiresAt": 1733405100000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `publishService`
|
||||||
|
Publish a service with offers
|
||||||
|
|
||||||
|
**Parameters:**
|
||||||
|
- `serviceFqn` - Service FQN with username (e.g., `chat:1.0.0@alice`)
|
||||||
|
- `offers` - Array of offers, each with `sdp` field
|
||||||
|
- `ttl` - (optional) Time to live in milliseconds
|
||||||
|
|
||||||
|
**Message format:** `publishService:{username}:{serviceFqn}:{timestamp}`
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"method": "publishService",
|
||||||
|
"message": "publishService:alice:chat:1.0.0@alice:1733404800000",
|
||||||
|
"signature": "base64-signature",
|
||||||
|
"params": {
|
||||||
|
"serviceFqn": "chat:1.0.0@alice",
|
||||||
|
"offers": [
|
||||||
|
{ "sdp": "v=0..." },
|
||||||
|
{ "sdp": "v=0..." }
|
||||||
|
],
|
||||||
|
"ttl": 300000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"result": {
|
||||||
|
"serviceId": "uuid",
|
||||||
|
"username": "alice",
|
||||||
|
"serviceFqn": "chat:1.0.0@alice",
|
||||||
|
"offers": [
|
||||||
|
{
|
||||||
|
"offerId": "offer-hash-1",
|
||||||
|
"sdp": "v=0...",
|
||||||
|
"createdAt": 1733404800000,
|
||||||
|
"expiresAt": 1733405100000
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"createdAt": 1733404800000,
|
||||||
|
"expiresAt": 1733405100000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `deleteService`
|
||||||
|
Delete a service
|
||||||
|
|
||||||
|
**Parameters:**
|
||||||
|
- `serviceFqn` - Service FQN with username
|
||||||
|
|
||||||
|
**Message format:** `deleteService:{username}:{serviceFqn}:{timestamp}`
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"method": "deleteService",
|
||||||
|
"message": "deleteService:alice:chat:1.0.0@alice:1733404800000",
|
||||||
|
"signature": "base64-signature",
|
||||||
|
"params": {
|
||||||
|
"serviceFqn": "chat:1.0.0@alice"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"result": { "success": true }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `answerOffer`
|
||||||
|
Answer a specific offer
|
||||||
|
|
||||||
|
**Parameters:**
|
||||||
|
- `serviceFqn` - Service FQN
|
||||||
|
- `offerId` - Offer ID
|
||||||
|
- `sdp` - Answer SDP
|
||||||
|
|
||||||
|
**Message format:** `answerOffer:{username}:{offerId}:{timestamp}`
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"method": "answerOffer",
|
||||||
|
"message": "answerOffer:bob:offer-hash:1733404800000",
|
||||||
|
"signature": "base64-signature",
|
||||||
|
"params": {
|
||||||
|
"serviceFqn": "chat:1.0.0@alice",
|
||||||
|
"offerId": "offer-hash",
|
||||||
|
"sdp": "v=0..."
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"result": {
|
||||||
|
"success": true,
|
||||||
|
"offerId": "offer-hash"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `getOfferAnswer`
|
||||||
|
Get answer for an offer (offerer polls this)
|
||||||
|
|
||||||
|
**Parameters:**
|
||||||
|
- `serviceFqn` - Service FQN
|
||||||
|
- `offerId` - Offer ID
|
||||||
|
|
||||||
|
**Message format:** `getOfferAnswer:{username}:{offerId}:{timestamp}`
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"method": "getOfferAnswer",
|
||||||
|
"message": "getOfferAnswer:alice:offer-hash:1733404800000",
|
||||||
|
"signature": "base64-signature",
|
||||||
|
"params": {
|
||||||
|
"serviceFqn": "chat:1.0.0@alice",
|
||||||
|
"offerId": "offer-hash"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"result": {
|
||||||
|
"sdp": "v=0...",
|
||||||
|
"offerId": "offer-hash",
|
||||||
|
"answererId": "bob",
|
||||||
|
"answeredAt": 1733404800000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `poll`
|
||||||
|
Combined polling for answers and ICE candidates
|
||||||
|
|
||||||
|
**Parameters:**
|
||||||
|
- `since` - (optional) Timestamp to get only new data
|
||||||
|
|
||||||
|
**Message format:** `poll:{username}:{timestamp}`
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"method": "poll",
|
||||||
|
"message": "poll:alice:1733404800000",
|
||||||
|
"signature": "base64-signature",
|
||||||
|
"params": {
|
||||||
|
"since": 1733404800000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"result": {
|
||||||
|
"answers": [
|
||||||
|
{
|
||||||
|
"offerId": "offer-hash",
|
||||||
|
"serviceId": "service-uuid",
|
||||||
|
"answererId": "bob",
|
||||||
|
"sdp": "v=0...",
|
||||||
|
"answeredAt": 1733404800000
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"iceCandidates": {
|
||||||
|
"offer-hash": [
|
||||||
|
{
|
||||||
|
"candidate": { "candidate": "...", "sdpMid": "0", "sdpMLineIndex": 0 },
|
||||||
|
"role": "answerer",
|
||||||
|
"username": "bob",
|
||||||
|
"createdAt": 1733404800000
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `addIceCandidates`
|
||||||
|
Add ICE candidates to an offer
|
||||||
|
|
||||||
|
**Parameters:**
|
||||||
|
- `serviceFqn` - Service FQN
|
||||||
|
- `offerId` - Offer ID
|
||||||
|
- `candidates` - Array of ICE candidates
|
||||||
|
|
||||||
|
**Message format:** `addIceCandidates:{username}:{offerId}:{timestamp}`
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"method": "addIceCandidates",
|
||||||
|
"message": "addIceCandidates:alice:offer-hash:1733404800000",
|
||||||
|
"signature": "base64-signature",
|
||||||
|
"params": {
|
||||||
|
"serviceFqn": "chat:1.0.0@alice",
|
||||||
|
"offerId": "offer-hash",
|
||||||
|
"candidates": [
|
||||||
|
{
|
||||||
|
"candidate": "candidate:...",
|
||||||
|
"sdpMid": "0",
|
||||||
|
"sdpMLineIndex": 0
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"result": {
|
||||||
|
"count": 1,
|
||||||
|
"offerId": "offer-hash"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### `getIceCandidates`
|
||||||
|
Get ICE candidates for an offer
|
||||||
|
|
||||||
|
**Parameters:**
|
||||||
|
- `serviceFqn` - Service FQN
|
||||||
|
- `offerId` - Offer ID
|
||||||
|
- `since` - (optional) Timestamp to get only new candidates
|
||||||
|
|
||||||
|
**Message format:** `getIceCandidates:{username}:{offerId}:{timestamp}`
|
||||||
|
|
||||||
|
**Example:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"method": "getIceCandidates",
|
||||||
|
"message": "getIceCandidates:alice:offer-hash:1733404800000",
|
||||||
|
"signature": "base64-signature",
|
||||||
|
"params": {
|
||||||
|
"serviceFqn": "chat:1.0.0@alice",
|
||||||
|
"offerId": "offer-hash",
|
||||||
|
"since": 1733404800000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**Response:**
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"result": {
|
||||||
|
"candidates": [
|
||||||
|
{
|
||||||
|
"candidate": {
|
||||||
|
"candidate": "candidate:...",
|
||||||
|
"sdpMid": "0",
|
||||||
|
"sdpMLineIndex": 0
|
||||||
|
},
|
||||||
|
"createdAt": 1733404800000
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"offerId": "offer-hash"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
## Configuration
|
||||||
|
|
||||||
|
Environment variables:
|
||||||
|
|
||||||
|
| Variable | Default | Description |
|
||||||
|
|----------|---------|-------------|
|
||||||
|
| `PORT` | `3000` | Server port (Node.js/Docker) |
|
||||||
|
| `CORS_ORIGINS` | `*` | Comma-separated allowed origins |
|
||||||
|
| `STORAGE_PATH` | `./rondevu.db` | SQLite database path (use `:memory:` for in-memory) |
|
||||||
|
| `VERSION` | `0.5.0` | Server version (semver) |
|
||||||
|
| `OFFER_DEFAULT_TTL` | `60000` | Default offer TTL in ms (1 minute) |
|
||||||
|
| `OFFER_MIN_TTL` | `60000` | Minimum offer TTL in ms (1 minute) |
|
||||||
|
| `OFFER_MAX_TTL` | `86400000` | Maximum offer TTL in ms (24 hours) |
|
||||||
|
| `CLEANUP_INTERVAL` | `60000` | Cleanup interval in ms (1 minute) |
|
||||||
|
| `MAX_OFFERS_PER_REQUEST` | `100` | Maximum offers per create request |
|
||||||
|
|
||||||
|
## Database Schema
|
||||||
|
|
||||||
|
### usernames
|
||||||
|
- `username` (PK): Claimed username
|
||||||
|
- `public_key`: Ed25519 public key (base64)
|
||||||
|
- `claimed_at`: Claim timestamp
|
||||||
|
- `expires_at`: Expiry timestamp (365 days)
|
||||||
|
- `last_used`: Last activity timestamp
|
||||||
|
- `metadata`: Optional JSON metadata
|
||||||
|
|
||||||
|
### services
|
||||||
|
- `id` (PK): Service ID (UUID)
|
||||||
|
- `username` (FK): Owner username
|
||||||
|
- `service_fqn`: Fully qualified name (chat:1.0.0@alice)
|
||||||
|
- `service_name`: Service name component (chat)
|
||||||
|
- `version`: Version component (1.0.0)
|
||||||
|
- `created_at`, `expires_at`: Timestamps
|
||||||
|
- UNIQUE constraint on (service_name, version, username)
|
||||||
|
|
||||||
|
### offers
|
||||||
|
- `id` (PK): Offer ID (hash of SDP)
|
||||||
|
- `username` (FK): Owner username
|
||||||
|
- `service_id` (FK): Link to service
|
||||||
|
- `service_fqn`: Denormalized service FQN
|
||||||
|
- `sdp`: WebRTC offer SDP
|
||||||
|
- `answerer_username`: Username of answerer (null until answered)
|
||||||
|
- `answer_sdp`: WebRTC answer SDP (null until answered)
|
||||||
|
- `answered_at`: Timestamp when answered
|
||||||
|
- `created_at`, `expires_at`, `last_seen`: Timestamps
|
||||||
|
|
||||||
|
### ice_candidates
|
||||||
|
- `id` (PK): Auto-increment ID
|
||||||
|
- `offer_id` (FK): Link to offer
|
||||||
|
- `username`: Username who sent the candidate
|
||||||
|
- `role`: 'offerer' or 'answerer'
|
||||||
|
- `candidate`: JSON-encoded candidate
|
||||||
|
- `created_at`: Timestamp
|
||||||
|
|
||||||
|
## Security
|
||||||
|
|
||||||
|
### Ed25519 Signature Authentication
|
||||||
|
All authenticated requests require:
|
||||||
|
- **message**: Signed message with format-specific structure
|
||||||
|
- **signature**: Base64-encoded Ed25519 signature of the message
|
||||||
|
- Username is extracted from the message
|
||||||
|
|
||||||
|
### Username Claiming
|
||||||
|
- **Algorithm**: Ed25519 signatures
|
||||||
|
- **Message Format**: `claim:{username}:{timestamp}`
|
||||||
|
- **Replay Protection**: Timestamp must be within 5 minutes
|
||||||
|
- **Key Management**: Private keys never leave the client
|
||||||
|
- **Validity**: 365 days, auto-renewed on use
|
||||||
|
|
||||||
|
### Anonymous Users
|
||||||
|
- **Format**: `anon-{timestamp}-{random}` (e.g., `anon-lx2w34-a3f501`)
|
||||||
|
- **Generation**: Can be generated by client for testing
|
||||||
|
- **Behavior**: Same as regular usernames, must be explicitly claimed like any username
|
||||||
|
|
||||||
|
### Service Publishing
|
||||||
|
- **Ownership Verification**: Every publish requires username signature
|
||||||
|
- **Message Format**: `publishService:{username}:{serviceFqn}:{timestamp}`
|
||||||
|
- **Auto-Renewal**: Publishing a service extends username expiry
|
||||||
|
|
||||||
|
### ICE Candidate Filtering
|
||||||
|
- Server filters candidates by role to prevent peers from receiving their own candidates
|
||||||
|
- Offerers receive only answerer candidates
|
||||||
|
- Answerers receive only offerer candidates
|
||||||
|
|
||||||
|
## Migration from v0.4.x
|
||||||
|
|
||||||
|
See [MIGRATION.md](../MIGRATION.md) for detailed migration guide.
|
||||||
|
|
||||||
|
**Key Changes:**
|
||||||
|
- Moved from REST API to RPC interface with single `/rpc` endpoint
|
||||||
|
- All methods now use POST with JSON body
|
||||||
|
- Batch operations supported
|
||||||
|
- Authentication is per-method instead of per-endpoint middleware
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT
|
||||||
458
API.md
458
API.md
@@ -1,458 +0,0 @@
|
|||||||
# HTTP API
|
|
||||||
|
|
||||||
This API provides peer signaling and tracking endpoints for distributed peer-to-peer applications. Uses JSON request/response bodies with Origin-based session isolation.
|
|
||||||
|
|
||||||
All endpoints require an `Origin` header and accept `application/json` content type.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Overview
|
|
||||||
|
|
||||||
Sessions are organized by:
|
|
||||||
- **Origin**: The HTTP Origin header (e.g., `https://example.com`) - isolates sessions by application
|
|
||||||
- **Topic**: A string identifier for grouping related peers (max 256 chars)
|
|
||||||
- **Info**: User-provided metadata (max 1024 chars) to uniquely identify each peer
|
|
||||||
|
|
||||||
This allows multiple peers from the same application (origin) to discover each other through topics while preventing duplicate connections by comparing the info field.
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## GET `/`
|
|
||||||
|
|
||||||
Returns server version information including the git commit hash used to build the server.
|
|
||||||
|
|
||||||
### Response
|
|
||||||
|
|
||||||
**Content-Type:** `application/json`
|
|
||||||
|
|
||||||
**Success (200 OK):**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"version": "a1b2c3d"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Notes:**
|
|
||||||
- Returns the git commit hash from build time
|
|
||||||
- Returns "unknown" if git information is not available
|
|
||||||
|
|
||||||
### Example
|
|
||||||
|
|
||||||
```bash
|
|
||||||
curl -X GET http://localhost:3000/
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## GET `/topics`
|
|
||||||
|
|
||||||
Lists all topics with the count of available peers for each (paginated). Returns only topics that have unanswered sessions.
|
|
||||||
|
|
||||||
### Request
|
|
||||||
|
|
||||||
**Headers:**
|
|
||||||
- `Origin: https://example.com` (required)
|
|
||||||
|
|
||||||
**Query Parameters:**
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Default | Description |
|
|
||||||
|-----------|--------|----------|---------|---------------------------------|
|
|
||||||
| `page` | number | No | `1` | Page number (starting from 1) |
|
|
||||||
| `limit` | number | No | `100` | Results per page (max 1000) |
|
|
||||||
|
|
||||||
### Response
|
|
||||||
|
|
||||||
**Content-Type:** `application/json`
|
|
||||||
|
|
||||||
**Success (200 OK):**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"topics": [
|
|
||||||
{
|
|
||||||
"topic": "my-room",
|
|
||||||
"count": 3
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"topic": "another-room",
|
|
||||||
"count": 1
|
|
||||||
}
|
|
||||||
],
|
|
||||||
"pagination": {
|
|
||||||
"page": 1,
|
|
||||||
"limit": 100,
|
|
||||||
"total": 2,
|
|
||||||
"hasMore": false
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Notes:**
|
|
||||||
- Only returns topics from the same origin as the request
|
|
||||||
- Only includes topics with at least one unanswered session
|
|
||||||
- Topics are sorted alphabetically
|
|
||||||
- Counts only include unexpired sessions
|
|
||||||
- Maximum 1000 results per page
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
**Default pagination (page 1, limit 100):**
|
|
||||||
```bash
|
|
||||||
curl -X GET http://localhost:3000/topics \
|
|
||||||
-H "Origin: https://example.com"
|
|
||||||
```
|
|
||||||
|
|
||||||
**Custom pagination:**
|
|
||||||
```bash
|
|
||||||
curl -X GET "http://localhost:3000/topics?page=2&limit=50" \
|
|
||||||
-H "Origin: https://example.com"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## GET `/:topic/sessions`
|
|
||||||
|
|
||||||
Discovers available peers for a given topic. Returns all unanswered sessions from the requesting origin.
|
|
||||||
|
|
||||||
### Request
|
|
||||||
|
|
||||||
**Headers:**
|
|
||||||
- `Origin: https://example.com` (required)
|
|
||||||
|
|
||||||
**Path Parameters:**
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
|-----------|--------|----------|-------------------------------|
|
|
||||||
| `topic` | string | Yes | Topic identifier to query |
|
|
||||||
|
|
||||||
### Response
|
|
||||||
|
|
||||||
**Content-Type:** `application/json`
|
|
||||||
|
|
||||||
**Success (200 OK):**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"sessions": [
|
|
||||||
{
|
|
||||||
"code": "550e8400-e29b-41d4-a716-446655440000",
|
|
||||||
"info": "peer-123",
|
|
||||||
"offer": "<SIGNALING_DATA>",
|
|
||||||
"offerCandidates": ["<SIGNALING_DATA>"],
|
|
||||||
"createdAt": 1699564800000,
|
|
||||||
"expiresAt": 1699565100000
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "660e8400-e29b-41d4-a716-446655440001",
|
|
||||||
"info": "peer-456",
|
|
||||||
"offer": "<SIGNALING_DATA>",
|
|
||||||
"offerCandidates": [],
|
|
||||||
"createdAt": 1699564850000,
|
|
||||||
"expiresAt": 1699565150000
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Notes:**
|
|
||||||
- Only returns sessions from the same origin as the request
|
|
||||||
- Only returns sessions that haven't been answered yet
|
|
||||||
- Sessions are ordered by creation time (newest first)
|
|
||||||
- Use the `info` field to avoid answering your own offers
|
|
||||||
|
|
||||||
### Example
|
|
||||||
|
|
||||||
```bash
|
|
||||||
curl -X GET http://localhost:3000/my-room/sessions \
|
|
||||||
-H "Origin: https://example.com"
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## POST `/:topic/offer`
|
|
||||||
|
|
||||||
Announces peer availability and creates a new session for the specified topic. Returns a unique session code (UUID) for other peers to connect to.
|
|
||||||
|
|
||||||
### Request
|
|
||||||
|
|
||||||
**Headers:**
|
|
||||||
- `Content-Type: application/json`
|
|
||||||
- `Origin: https://example.com` (required)
|
|
||||||
|
|
||||||
**Path Parameters:**
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
|-----------|--------|----------|----------------------------------------------|
|
|
||||||
| `topic` | string | Yes | Topic identifier for grouping peers (max 256 characters) |
|
|
||||||
|
|
||||||
**Body Parameters:**
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
|-----------|--------|----------|----------------------------------------------|
|
|
||||||
| `info` | string | Yes | Peer identifier/metadata (max 1024 characters) |
|
|
||||||
| `offer` | string | Yes | Signaling data for peer connection |
|
|
||||||
|
|
||||||
### Response
|
|
||||||
|
|
||||||
**Content-Type:** `application/json`
|
|
||||||
|
|
||||||
**Success (200 OK):**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"code": "550e8400-e29b-41d4-a716-446655440000"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Returns a unique UUID session code.
|
|
||||||
|
|
||||||
### Example
|
|
||||||
|
|
||||||
```bash
|
|
||||||
curl -X POST http://localhost:3000/my-room/offer \
|
|
||||||
-H "Content-Type: application/json" \
|
|
||||||
-H "Origin: https://example.com" \
|
|
||||||
-d '{
|
|
||||||
"info": "peer-123",
|
|
||||||
"offer": "<SIGNALING_DATA>"
|
|
||||||
}'
|
|
||||||
|
|
||||||
# Response:
|
|
||||||
# {"code":"550e8400-e29b-41d4-a716-446655440000"}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## POST `/answer`
|
|
||||||
|
|
||||||
Connects to an existing peer session by sending connection data or exchanging signaling information.
|
|
||||||
|
|
||||||
### Request
|
|
||||||
|
|
||||||
**Headers:**
|
|
||||||
- `Content-Type: application/json`
|
|
||||||
- `Origin: https://example.com` (required)
|
|
||||||
|
|
||||||
**Body Parameters:**
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
|-------------|--------|----------|----------------------------------------------------------|
|
|
||||||
| `code` | string | Yes | The session UUID from the offer |
|
|
||||||
| `answer` | string | No* | Response signaling data for connection establishment |
|
|
||||||
| `candidate` | string | No* | Additional signaling data for connection negotiation |
|
|
||||||
| `side` | string | Yes | Which peer is sending: `offerer` or `answerer` |
|
|
||||||
|
|
||||||
*Either `answer` or `candidate` must be provided, but not both.
|
|
||||||
|
|
||||||
### Response
|
|
||||||
|
|
||||||
**Content-Type:** `application/json`
|
|
||||||
|
|
||||||
**Success (200 OK):**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"success": true
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Notes:**
|
|
||||||
- Origin header must match the session's origin
|
|
||||||
- Sessions are isolated by origin to group topics by domain
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
**Sending connection response:**
|
|
||||||
```bash
|
|
||||||
curl -X POST http://localhost:3000/answer \
|
|
||||||
-H "Content-Type: application/json" \
|
|
||||||
-H "Origin: https://example.com" \
|
|
||||||
-d '{
|
|
||||||
"code": "550e8400-e29b-41d4-a716-446655440000",
|
|
||||||
"answer": "<SIGNALING_DATA>",
|
|
||||||
"side": "answerer"
|
|
||||||
}'
|
|
||||||
|
|
||||||
# Response:
|
|
||||||
# {"success":true}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Sending additional signaling data:**
|
|
||||||
```bash
|
|
||||||
curl -X POST http://localhost:3000/answer \
|
|
||||||
-H "Content-Type: application/json" \
|
|
||||||
-H "Origin: https://example.com" \
|
|
||||||
-d '{
|
|
||||||
"code": "550e8400-e29b-41d4-a716-446655440000",
|
|
||||||
"candidate": "<SIGNALING_DATA>",
|
|
||||||
"side": "offerer"
|
|
||||||
}'
|
|
||||||
|
|
||||||
# Response:
|
|
||||||
# {"success":true}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## POST `/poll`
|
|
||||||
|
|
||||||
Retrieves session data including offers, responses, and signaling information from the other peer.
|
|
||||||
|
|
||||||
### Request
|
|
||||||
|
|
||||||
**Headers:**
|
|
||||||
- `Content-Type: application/json`
|
|
||||||
- `Origin: https://example.com` (required)
|
|
||||||
|
|
||||||
**Body Parameters:**
|
|
||||||
|
|
||||||
| Parameter | Type | Required | Description |
|
|
||||||
|-----------|--------|----------|-------------------------------------------------|
|
|
||||||
| `code` | string | Yes | The session UUID |
|
|
||||||
| `side` | string | Yes | Which side is polling: `offerer` or `answerer` |
|
|
||||||
|
|
||||||
### Response
|
|
||||||
|
|
||||||
**Content-Type:** `application/json`
|
|
||||||
|
|
||||||
**Success (200 OK):**
|
|
||||||
|
|
||||||
Response varies by side:
|
|
||||||
|
|
||||||
**For `side=offerer` (the offerer polls for response from answerer):**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"answer": "<SIGNALING_DATA>",
|
|
||||||
"answerCandidates": [
|
|
||||||
"<SIGNALING_DATA_1>",
|
|
||||||
"<SIGNALING_DATA_2>"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**For `side=answerer` (the answerer polls for offer from offerer):**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"offer": "<SIGNALING_DATA>",
|
|
||||||
"offerCandidates": [
|
|
||||||
"<SIGNALING_DATA_1>",
|
|
||||||
"<SIGNALING_DATA_2>"
|
|
||||||
]
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**Notes:**
|
|
||||||
- `answer` will be `null` if the answerer hasn't responded yet
|
|
||||||
- Candidate arrays will be empty `[]` if no additional signaling data has been sent
|
|
||||||
- Use this endpoint for polling to check for new signaling data
|
|
||||||
- Origin header must match the session's origin
|
|
||||||
|
|
||||||
### Examples
|
|
||||||
|
|
||||||
**Answerer polling for signaling data:**
|
|
||||||
```bash
|
|
||||||
curl -X POST http://localhost:3000/poll \
|
|
||||||
-H "Content-Type: application/json" \
|
|
||||||
-H "Origin: https://example.com" \
|
|
||||||
-d '{
|
|
||||||
"code": "550e8400-e29b-41d4-a716-446655440000",
|
|
||||||
"side": "answerer"
|
|
||||||
}'
|
|
||||||
|
|
||||||
# Response:
|
|
||||||
# {
|
|
||||||
# "offer": "<SIGNALING_DATA>",
|
|
||||||
# "offerCandidates": ["<SIGNALING_DATA>"]
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
**Offerer polling for response:**
|
|
||||||
```bash
|
|
||||||
curl -X POST http://localhost:3000/poll \
|
|
||||||
-H "Content-Type: application/json" \
|
|
||||||
-H "Origin: https://example.com" \
|
|
||||||
-d '{
|
|
||||||
"code": "550e8400-e29b-41d4-a716-446655440000",
|
|
||||||
"side": "offerer"
|
|
||||||
}'
|
|
||||||
|
|
||||||
# Response:
|
|
||||||
# {
|
|
||||||
# "answer": "<SIGNALING_DATA>",
|
|
||||||
# "answerCandidates": ["<SIGNALING_DATA>"]
|
|
||||||
# }
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## GET `/health`
|
|
||||||
|
|
||||||
Health check endpoint.
|
|
||||||
|
|
||||||
### Response
|
|
||||||
|
|
||||||
**Content-Type:** `application/json`
|
|
||||||
|
|
||||||
**Success (200 OK):**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"status": "ok",
|
|
||||||
"timestamp": 1699564800000
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Error Responses
|
|
||||||
|
|
||||||
All endpoints may return the following error responses:
|
|
||||||
|
|
||||||
**400 Bad Request:**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"error": "Missing or invalid required parameter: topic"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**404 Not Found:**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"error": "Session not found, expired, or origin mismatch"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**500 Internal Server Error:**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"error": "Internal server error"
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## Usage Flow
|
|
||||||
|
|
||||||
### Peer Discovery and Connection
|
|
||||||
|
|
||||||
1. **Check server version (optional):**
|
|
||||||
- GET `/` to see server version information
|
|
||||||
|
|
||||||
2. **Discover active topics:**
|
|
||||||
- GET `/topics` to see all topics and peer counts
|
|
||||||
- Optional: paginate through results with `?page=2&limit=100`
|
|
||||||
|
|
||||||
3. **Peer A announces availability:**
|
|
||||||
- POST `/:topic/offer` with peer identifier and signaling data
|
|
||||||
- Receives a unique session code
|
|
||||||
|
|
||||||
4. **Peer B discovers peers:**
|
|
||||||
- GET `/:topic/sessions` to list available sessions in a topic
|
|
||||||
- Filters out sessions with their own info to avoid self-connection
|
|
||||||
- Selects a peer to connect to
|
|
||||||
|
|
||||||
5. **Peer B initiates connection:**
|
|
||||||
- POST `/answer` with the session code and their signaling data
|
|
||||||
|
|
||||||
6. **Both peers exchange signaling information:**
|
|
||||||
- POST `/answer` with additional signaling data as needed
|
|
||||||
- POST `/poll` to retrieve signaling data from the other peer
|
|
||||||
|
|
||||||
7. **Peer connection established**
|
|
||||||
- Peers use exchanged signaling data to establish direct connection
|
|
||||||
- Session automatically expires after configured timeout
|
|
||||||
302
README.md
302
README.md
@@ -2,9 +2,9 @@
|
|||||||
|
|
||||||
[](https://www.npmjs.com/package/@xtr-dev/rondevu-server)
|
[](https://www.npmjs.com/package/@xtr-dev/rondevu-server)
|
||||||
|
|
||||||
🌐 **Topic-based peer discovery and WebRTC signaling**
|
🌐 **Simple WebRTC signaling with RPC interface**
|
||||||
|
|
||||||
Scalable peer-to-peer connection establishment with topic-based discovery, stateless authentication, and complete WebRTC signaling.
|
Scalable WebRTC signaling server with cryptographic username claiming, service publishing with semantic versioning, and efficient offer/answer exchange via JSON-RPC interface.
|
||||||
|
|
||||||
**Related repositories:**
|
**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))
|
- [@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,14 +15,32 @@ Scalable peer-to-peer connection establishment with topic-based discovery, state
|
|||||||
|
|
||||||
## Features
|
## Features
|
||||||
|
|
||||||
- **Topic-Based Discovery**: Tag offers with topics (e.g., torrent infohashes) for efficient peer finding
|
- **RPC Interface**: Single endpoint for all operations with batching support
|
||||||
- **Stateless Authentication**: AES-256-GCM encrypted credentials, no server-side sessions
|
- **Username Claiming**: Cryptographic username ownership with Ed25519 signatures (365-day validity, auto-renewed on use)
|
||||||
- **Protected Offers**: Optional secret field for access-controlled peer connections
|
- **Service Publishing**: Service:version@username naming (e.g., `chat:1.0.0@alice`)
|
||||||
- **Bloom Filters**: Client-side peer exclusion for efficient discovery
|
- **Service Discovery**: Random and paginated discovery for finding services without knowing usernames
|
||||||
- **Multi-Offer Support**: Create multiple offers per peer simultaneously
|
- **Semantic Versioning**: Compatible version matching (chat:1.0.0 matches any 1.x.x)
|
||||||
|
- **Signature-Based Authentication**: All authenticated requests use Ed25519 signatures
|
||||||
- **Complete WebRTC Signaling**: Offer/answer exchange and ICE candidate relay
|
- **Complete WebRTC Signaling**: Offer/answer exchange and ICE candidate relay
|
||||||
|
- **Batch Operations**: Execute multiple operations in a single HTTP request
|
||||||
- **Dual Storage**: SQLite (Node.js/Docker) and Cloudflare D1 (Workers) backends
|
- **Dual Storage**: SQLite (Node.js/Docker) and Cloudflare D1 (Workers) backends
|
||||||
|
|
||||||
|
## Architecture
|
||||||
|
|
||||||
|
```
|
||||||
|
Username Claiming → Service Publishing → Service Discovery → WebRTC Connection
|
||||||
|
|
||||||
|
alice claims "alice" with Ed25519 signature
|
||||||
|
↓
|
||||||
|
alice publishes chat:1.0.0@alice with offers
|
||||||
|
↓
|
||||||
|
bob queries chat:1.0.0@alice (direct) or chat:1.0.0 (discovery) → gets offer SDP
|
||||||
|
↓
|
||||||
|
bob posts answer SDP → WebRTC connection established
|
||||||
|
↓
|
||||||
|
ICE candidates exchanged via server relay
|
||||||
|
```
|
||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
**Node.js:**
|
**Node.js:**
|
||||||
@@ -40,159 +58,201 @@ docker build -t rondevu . && docker run -p 3000:3000 -e STORAGE_PATH=:memory: ro
|
|||||||
npx wrangler deploy
|
npx wrangler deploy
|
||||||
```
|
```
|
||||||
|
|
||||||
## API Endpoints
|
## RPC Interface
|
||||||
|
|
||||||
### Public Endpoints
|
All API calls are made to `POST /rpc` with JSON-RPC format.
|
||||||
|
|
||||||
#### `GET /`
|
### Request Format
|
||||||
Returns server version and info
|
|
||||||
|
|
||||||
#### `GET /health`
|
**Single method call:**
|
||||||
Health check endpoint with version
|
|
||||||
|
|
||||||
#### `POST /register`
|
|
||||||
Register a new peer and receive credentials (peerId + secret)
|
|
||||||
|
|
||||||
**Response:**
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"peerId": "f17c195f067255e357232e34cf0735d9",
|
"method": "getUser",
|
||||||
"secret": "DdorTR8QgSn9yngn+4qqR8cs1aMijvX..."
|
"message": "getUser:alice:1733404800000",
|
||||||
|
"signature": "base64-encoded-signature",
|
||||||
|
"params": {
|
||||||
|
"username": "alice"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### `GET /topics?limit=50&offset=0`
|
**Batch calls:**
|
||||||
List all topics with active peer counts (paginated)
|
|
||||||
|
|
||||||
**Query Parameters:**
|
|
||||||
- `limit` (optional): Maximum number of topics to return (default: 50, max: 200)
|
|
||||||
- `offset` (optional): Number of topics to skip (default: 0)
|
|
||||||
|
|
||||||
**Response:**
|
|
||||||
```json
|
```json
|
||||||
{
|
[
|
||||||
"topics": [
|
{
|
||||||
{"topic": "movie-xyz", "activePeers": 42},
|
"method": "getUser",
|
||||||
{"topic": "torrent-abc", "activePeers": 15}
|
"message": "getUser:alice:1733404800000",
|
||||||
],
|
"signature": "base64-encoded-signature",
|
||||||
"total": 123,
|
"params": { "username": "alice" }
|
||||||
"limit": 50,
|
},
|
||||||
"offset": 0
|
{
|
||||||
}
|
"method": "claimUsername",
|
||||||
```
|
"message": "claim:bob:1733404800000",
|
||||||
|
"signature": "base64-encoded-signature",
|
||||||
#### `GET /offers/by-topic/:topic?limit=50&bloom=...`
|
"params": {
|
||||||
Find offers by topic with optional bloom filter exclusion
|
"username": "bob",
|
||||||
|
"publicKey": "base64-encoded-public-key"
|
||||||
**Query Parameters:**
|
|
||||||
- `limit` (optional): Maximum offers to return (default: 50, max: 200)
|
|
||||||
- `bloom` (optional): Base64-encoded bloom filter to exclude known peers
|
|
||||||
|
|
||||||
**Response:**
|
|
||||||
```json
|
|
||||||
{
|
|
||||||
"topic": "movie-xyz",
|
|
||||||
"offers": [
|
|
||||||
{
|
|
||||||
"id": "offer-id",
|
|
||||||
"peerId": "peer-id",
|
|
||||||
"sdp": "v=0...",
|
|
||||||
"topics": ["movie-xyz", "hd-content"],
|
|
||||||
"expiresAt": 1234567890,
|
|
||||||
"lastSeen": 1234567890,
|
|
||||||
"hasSecret": true // Indicates if secret is required to answer
|
|
||||||
}
|
}
|
||||||
],
|
}
|
||||||
"total": 42,
|
]
|
||||||
"returned": 10
|
|
||||||
}
|
|
||||||
```
|
```
|
||||||
|
|
||||||
**Notes:**
|
### Response Format
|
||||||
- `hasSecret`: Boolean flag indicating whether a secret is required to answer this offer. The actual secret is never exposed in public endpoints.
|
|
||||||
|
|
||||||
#### `GET /peers/:peerId/offers`
|
**Single response:**
|
||||||
View all offers from a specific peer
|
|
||||||
|
|
||||||
### Authenticated Endpoints
|
|
||||||
|
|
||||||
All authenticated endpoints require `Authorization: Bearer {peerId}:{secret}` header.
|
|
||||||
|
|
||||||
#### `POST /offers`
|
|
||||||
Create one or more offers
|
|
||||||
|
|
||||||
**Request:**
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"offers": [
|
"success": true,
|
||||||
{
|
"result": { /* method-specific data */ }
|
||||||
"sdp": "v=0...",
|
|
||||||
"topics": ["movie-xyz", "hd-content"],
|
|
||||||
"ttl": 300000,
|
|
||||||
"secret": "my-secret-password" // Optional: protect offer (max 128 chars)
|
|
||||||
}
|
|
||||||
]
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
**Notes:**
|
**Error response:**
|
||||||
- `secret` (optional): Protect the offer with a secret. Answerers must provide the correct secret to connect.
|
|
||||||
|
|
||||||
#### `GET /offers/mine`
|
|
||||||
List all offers owned by authenticated peer
|
|
||||||
|
|
||||||
#### `PUT /offers/:offerId/heartbeat`
|
|
||||||
Update last_seen timestamp for an offer
|
|
||||||
|
|
||||||
#### `DELETE /offers/:offerId`
|
|
||||||
Delete a specific offer
|
|
||||||
|
|
||||||
#### `POST /offers/:offerId/answer`
|
|
||||||
Answer an offer (locks it to answerer)
|
|
||||||
|
|
||||||
**Request:**
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"sdp": "v=0...",
|
"success": false,
|
||||||
"secret": "my-secret-password" // Required if offer is protected
|
"error": "Error message"
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
**Notes:**
|
**Batch responses:** Array of responses matching request array order.
|
||||||
- `secret` (optional): Required if the offer was created with a secret. Must match the offer's secret.
|
|
||||||
|
|
||||||
#### `GET /offers/answers`
|
## Core Methods
|
||||||
Poll for answers to your offers
|
|
||||||
|
|
||||||
#### `POST /offers/:offerId/ice-candidates`
|
### Username Management
|
||||||
Post ICE candidates for an offer
|
|
||||||
|
|
||||||
**Request:**
|
```typescript
|
||||||
```json
|
// Check username availability
|
||||||
|
POST /rpc
|
||||||
{
|
{
|
||||||
"candidates": ["candidate:1 1 UDP..."]
|
"method": "getUser",
|
||||||
|
"params": { "username": "alice" }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Claim username (requires signature)
|
||||||
|
POST /rpc
|
||||||
|
{
|
||||||
|
"method": "claimUsername",
|
||||||
|
"message": "claim:alice:1733404800000",
|
||||||
|
"signature": "base64-signature",
|
||||||
|
"params": {
|
||||||
|
"username": "alice",
|
||||||
|
"publicKey": "base64-public-key"
|
||||||
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### `GET /offers/:offerId/ice-candidates?since=1234567890`
|
### Service Publishing
|
||||||
Get ICE candidates from the other peer
|
|
||||||
|
```typescript
|
||||||
|
// Publish service (requires signature)
|
||||||
|
POST /rpc
|
||||||
|
{
|
||||||
|
"method": "publishService",
|
||||||
|
"message": "publishService:alice:chat:1.0.0@alice:1733404800000",
|
||||||
|
"signature": "base64-signature",
|
||||||
|
"params": {
|
||||||
|
"serviceFqn": "chat:1.0.0@alice",
|
||||||
|
"offers": [{ "sdp": "webrtc-offer-sdp" }],
|
||||||
|
"ttl": 300000
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### Service Discovery
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Get specific service
|
||||||
|
POST /rpc
|
||||||
|
{
|
||||||
|
"method": "getService",
|
||||||
|
"params": { "serviceFqn": "chat:1.0.0@alice" }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Random discovery
|
||||||
|
POST /rpc
|
||||||
|
{
|
||||||
|
"method": "getService",
|
||||||
|
"params": { "serviceFqn": "chat:1.0.0" }
|
||||||
|
}
|
||||||
|
|
||||||
|
// Paginated discovery
|
||||||
|
POST /rpc
|
||||||
|
{
|
||||||
|
"method": "getService",
|
||||||
|
"params": {
|
||||||
|
"serviceFqn": "chat:1.0.0",
|
||||||
|
"limit": 10,
|
||||||
|
"offset": 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### WebRTC Signaling
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
// Answer offer (requires signature)
|
||||||
|
POST /rpc
|
||||||
|
{
|
||||||
|
"method": "answerOffer",
|
||||||
|
"message": "answer:bob:offer-id:1733404800000",
|
||||||
|
"signature": "base64-signature",
|
||||||
|
"params": {
|
||||||
|
"serviceFqn": "chat:1.0.0@alice",
|
||||||
|
"offerId": "offer-id",
|
||||||
|
"sdp": "webrtc-answer-sdp"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add ICE candidates (requires signature)
|
||||||
|
POST /rpc
|
||||||
|
{
|
||||||
|
"method": "addIceCandidates",
|
||||||
|
"params": {
|
||||||
|
"serviceFqn": "chat:1.0.0@alice",
|
||||||
|
"offerId": "offer-id",
|
||||||
|
"candidates": [{ /* RTCIceCandidateInit */ }]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Poll for answers and ICE candidates (requires signature)
|
||||||
|
POST /rpc
|
||||||
|
{
|
||||||
|
"method": "poll",
|
||||||
|
"params": { "since": 1733404800000 }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
## Configuration
|
## Configuration
|
||||||
|
|
||||||
Environment variables:
|
Quick reference for common environment variables:
|
||||||
|
|
||||||
| Variable | Default | Description |
|
| Variable | Default | Description |
|
||||||
|----------|---------|-------------|
|
|----------|---------|-------------|
|
||||||
| `PORT` | `3000` | Server port (Node.js/Docker) |
|
| `PORT` | `3000` | Server port (Node.js/Docker) |
|
||||||
| `CORS_ORIGINS` | `*` | Comma-separated allowed origins |
|
| `CORS_ORIGINS` | `*` | Comma-separated allowed origins |
|
||||||
| `STORAGE_PATH` | `./rondevu.db` | SQLite database path (use `:memory:` for in-memory) |
|
| `STORAGE_PATH` | `./rondevu.db` | SQLite database path (use `:memory:` for in-memory) |
|
||||||
| `VERSION` | `0.4.0` | Server version (semver) |
|
|
||||||
| `AUTH_SECRET` | Random 32-byte hex | Secret key for credential encryption |
|
📚 See [ADVANCED.md](./ADVANCED.md#configuration) for complete configuration reference.
|
||||||
| `OFFER_DEFAULT_TTL` | `300000` | Default offer TTL in ms (5 minutes) |
|
|
||||||
| `OFFER_MIN_TTL` | `60000` | Minimum offer TTL in ms (1 minute) |
|
## Documentation
|
||||||
| `OFFER_MAX_TTL` | `3600000` | Maximum offer TTL in ms (1 hour) |
|
|
||||||
| `MAX_OFFERS_PER_REQUEST` | `10` | Maximum offers per create request |
|
📚 **[ADVANCED.md](./ADVANCED.md)** - Comprehensive guide including:
|
||||||
| `MAX_TOPICS_PER_OFFER` | `20` | Maximum topics per offer |
|
- Complete RPC method reference with examples
|
||||||
|
- Full configuration options
|
||||||
|
- Database schema documentation
|
||||||
|
- Security implementation details
|
||||||
|
- Migration guides
|
||||||
|
|
||||||
|
## Security
|
||||||
|
|
||||||
|
All authenticated operations require Ed25519 signatures:
|
||||||
|
- **Message Format**: `{method}:{username}:{context}:{timestamp}`
|
||||||
|
- **Signature**: Base64-encoded Ed25519 signature of the message
|
||||||
|
- **Replay Protection**: Timestamps must be within 5 minutes
|
||||||
|
- **Username Ownership**: Verified via public key signature
|
||||||
|
|
||||||
|
See [ADVANCED.md](./ADVANCED.md#security) for detailed security documentation.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
|||||||
83
migrations/0005_v2_schema.sql
Normal file
83
migrations/0005_v2_schema.sql
Normal file
@@ -0,0 +1,83 @@
|
|||||||
|
-- V2 Migration: Add offers, usernames, and services tables
|
||||||
|
|
||||||
|
-- Offers table (replaces sessions)
|
||||||
|
CREATE TABLE IF NOT EXISTS offers (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
peer_id TEXT NOT NULL,
|
||||||
|
sdp TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL,
|
||||||
|
last_seen INTEGER NOT NULL,
|
||||||
|
secret TEXT,
|
||||||
|
answerer_peer_id TEXT,
|
||||||
|
answer_sdp TEXT,
|
||||||
|
answered_at INTEGER
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_offers_peer ON offers(peer_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_offers_expires ON offers(expires_at);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_offers_last_seen ON offers(last_seen);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_offers_answerer ON offers(answerer_peer_id);
|
||||||
|
|
||||||
|
-- ICE candidates table
|
||||||
|
CREATE TABLE IF NOT EXISTS ice_candidates (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
offer_id TEXT NOT NULL,
|
||||||
|
peer_id TEXT NOT NULL,
|
||||||
|
role TEXT NOT NULL CHECK(role IN ('offerer', 'answerer')),
|
||||||
|
candidate TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
FOREIGN KEY (offer_id) REFERENCES offers(id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_ice_offer ON ice_candidates(offer_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_ice_peer ON ice_candidates(peer_id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_ice_created ON ice_candidates(created_at);
|
||||||
|
|
||||||
|
-- Usernames table
|
||||||
|
CREATE TABLE IF NOT EXISTS usernames (
|
||||||
|
username TEXT PRIMARY KEY,
|
||||||
|
public_key TEXT NOT NULL UNIQUE,
|
||||||
|
claimed_at INTEGER NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL,
|
||||||
|
last_used INTEGER NOT NULL,
|
||||||
|
metadata TEXT,
|
||||||
|
CHECK(length(username) >= 3 AND length(username) <= 32)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_usernames_expires ON usernames(expires_at);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_usernames_public_key ON usernames(public_key);
|
||||||
|
|
||||||
|
-- Services table
|
||||||
|
CREATE TABLE IF NOT EXISTS services (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
username TEXT NOT NULL,
|
||||||
|
service_fqn TEXT NOT NULL,
|
||||||
|
offer_id TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL,
|
||||||
|
is_public INTEGER NOT NULL DEFAULT 0,
|
||||||
|
metadata TEXT,
|
||||||
|
FOREIGN KEY (username) REFERENCES usernames(username) ON DELETE CASCADE,
|
||||||
|
FOREIGN KEY (offer_id) REFERENCES offers(id) ON DELETE CASCADE,
|
||||||
|
UNIQUE(username, service_fqn)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_services_username ON services(username);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_services_fqn ON services(service_fqn);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_services_expires ON services(expires_at);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_services_offer ON services(offer_id);
|
||||||
|
|
||||||
|
-- Service index table (privacy layer)
|
||||||
|
CREATE TABLE IF NOT EXISTS service_index (
|
||||||
|
uuid TEXT PRIMARY KEY,
|
||||||
|
service_id TEXT NOT NULL,
|
||||||
|
username TEXT NOT NULL,
|
||||||
|
service_fqn TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL,
|
||||||
|
FOREIGN KEY (service_id) REFERENCES services(id) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_service_index_username ON service_index(username);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_service_index_expires ON service_index(expires_at);
|
||||||
40
migrations/0006_service_offer_refactor.sql
Normal file
40
migrations/0006_service_offer_refactor.sql
Normal file
@@ -0,0 +1,40 @@
|
|||||||
|
-- V0.4.0 Migration: Refactor service-to-offer relationship
|
||||||
|
-- Change from one-to-one (service has offer_id) to one-to-many (offer has service_id)
|
||||||
|
|
||||||
|
-- Step 1: Add service_id column to offers table
|
||||||
|
ALTER TABLE offers ADD COLUMN service_id TEXT;
|
||||||
|
|
||||||
|
-- Step 2: Create new services table without offer_id
|
||||||
|
CREATE TABLE services_new (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
username TEXT NOT NULL,
|
||||||
|
service_fqn TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL,
|
||||||
|
is_public INTEGER NOT NULL DEFAULT 0,
|
||||||
|
metadata TEXT,
|
||||||
|
FOREIGN KEY (username) REFERENCES usernames(username) ON DELETE CASCADE,
|
||||||
|
UNIQUE(username, service_fqn)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Step 3: Copy data from old services table (if any exists)
|
||||||
|
INSERT INTO services_new (id, username, service_fqn, created_at, expires_at, is_public, metadata)
|
||||||
|
SELECT id, username, service_fqn, created_at, expires_at, is_public, metadata
|
||||||
|
FROM services;
|
||||||
|
|
||||||
|
-- Step 4: Drop old services table
|
||||||
|
DROP TABLE services;
|
||||||
|
|
||||||
|
-- Step 5: Rename new table to services
|
||||||
|
ALTER TABLE services_new RENAME TO services;
|
||||||
|
|
||||||
|
-- Step 6: Recreate indexes
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_services_username ON services(username);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_services_fqn ON services(service_fqn);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_services_expires ON services(expires_at);
|
||||||
|
|
||||||
|
-- Step 7: Add index for service_id in offers
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_offers_service ON offers(service_id);
|
||||||
|
|
||||||
|
-- Step 8: Add foreign key constraint (D1 doesn't enforce FK in ALTER, but good for documentation)
|
||||||
|
-- FOREIGN KEY (service_id) REFERENCES services(id) ON DELETE CASCADE
|
||||||
54
migrations/0007_simplify_schema.sql
Normal file
54
migrations/0007_simplify_schema.sql
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
-- V0.4.1 Migration: Simplify schema and add service discovery
|
||||||
|
-- Remove privacy layer (service_index) and add extracted fields for discovery
|
||||||
|
|
||||||
|
-- Step 1: Drop service_index table (privacy layer removal)
|
||||||
|
DROP TABLE IF EXISTS service_index;
|
||||||
|
|
||||||
|
-- Step 2: Create new services table with extracted fields for discovery
|
||||||
|
CREATE TABLE services_new (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
service_fqn TEXT NOT NULL,
|
||||||
|
service_name TEXT NOT NULL,
|
||||||
|
version TEXT NOT NULL,
|
||||||
|
username TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL,
|
||||||
|
FOREIGN KEY (username) REFERENCES usernames(username) ON DELETE CASCADE,
|
||||||
|
UNIQUE(service_fqn)
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Step 3: Migrate existing data (if any) - parse FQN to extract components
|
||||||
|
-- Note: This migration assumes FQN format is already "service:version@username"
|
||||||
|
-- If there's old data with different format, manual intervention may be needed
|
||||||
|
INSERT INTO services_new (id, service_fqn, service_name, version, username, created_at, expires_at)
|
||||||
|
SELECT
|
||||||
|
id,
|
||||||
|
service_fqn,
|
||||||
|
-- Extract service_name: everything before first ':'
|
||||||
|
substr(service_fqn, 1, instr(service_fqn, ':') - 1) as service_name,
|
||||||
|
-- Extract version: between ':' and '@'
|
||||||
|
substr(
|
||||||
|
service_fqn,
|
||||||
|
instr(service_fqn, ':') + 1,
|
||||||
|
instr(service_fqn, '@') - instr(service_fqn, ':') - 1
|
||||||
|
) as version,
|
||||||
|
username,
|
||||||
|
created_at,
|
||||||
|
expires_at
|
||||||
|
FROM services
|
||||||
|
WHERE service_fqn LIKE '%:%@%'; -- Only migrate properly formatted FQNs
|
||||||
|
|
||||||
|
-- Step 4: Drop old services table
|
||||||
|
DROP TABLE services;
|
||||||
|
|
||||||
|
-- Step 5: Rename new table to services
|
||||||
|
ALTER TABLE services_new RENAME TO services;
|
||||||
|
|
||||||
|
-- Step 6: Create indexes for efficient querying
|
||||||
|
CREATE INDEX idx_services_fqn ON services(service_fqn);
|
||||||
|
CREATE INDEX idx_services_discovery ON services(service_name, version);
|
||||||
|
CREATE INDEX idx_services_username ON services(username);
|
||||||
|
CREATE INDEX idx_services_expires ON services(expires_at);
|
||||||
|
|
||||||
|
-- Step 7: Create index on offers for available offer filtering
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_offers_available ON offers(answerer_peer_id) WHERE answerer_peer_id IS NULL;
|
||||||
67
migrations/0008_peer_id_to_username.sql
Normal file
67
migrations/0008_peer_id_to_username.sql
Normal file
@@ -0,0 +1,67 @@
|
|||||||
|
-- Migration: Convert peer_id to username in offers and ice_candidates tables
|
||||||
|
-- This migration aligns the database with the unified Ed25519 authentication system
|
||||||
|
|
||||||
|
-- Step 1: Recreate offers table with username instead of peer_id
|
||||||
|
CREATE TABLE offers_new (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
username TEXT NOT NULL,
|
||||||
|
service_id TEXT,
|
||||||
|
service_fqn TEXT,
|
||||||
|
sdp TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL,
|
||||||
|
last_seen INTEGER NOT NULL,
|
||||||
|
answerer_username TEXT,
|
||||||
|
answer_sdp TEXT,
|
||||||
|
answered_at INTEGER,
|
||||||
|
FOREIGN KEY (username) REFERENCES usernames(username) ON DELETE CASCADE,
|
||||||
|
FOREIGN KEY (answerer_username) REFERENCES usernames(username) ON DELETE SET NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Step 2: Migrate data (if any) - peer_id becomes username
|
||||||
|
-- Note: This assumes peer_id values were already usernames in practice
|
||||||
|
INSERT INTO offers_new (id, username, service_id, service_fqn, sdp, created_at, expires_at, last_seen, answerer_username, answer_sdp, answered_at)
|
||||||
|
SELECT id, peer_id as username, service_id, NULL as service_fqn, sdp, created_at, expires_at, last_seen, answerer_peer_id as answerer_username, answer_sdp, answered_at
|
||||||
|
FROM offers;
|
||||||
|
|
||||||
|
-- Step 3: Drop old offers table
|
||||||
|
DROP TABLE offers;
|
||||||
|
|
||||||
|
-- Step 4: Rename new table
|
||||||
|
ALTER TABLE offers_new RENAME TO offers;
|
||||||
|
|
||||||
|
-- Step 5: Recreate indexes
|
||||||
|
CREATE INDEX idx_offers_username ON offers(username);
|
||||||
|
CREATE INDEX idx_offers_service ON offers(service_id);
|
||||||
|
CREATE INDEX idx_offers_expires ON offers(expires_at);
|
||||||
|
CREATE INDEX idx_offers_last_seen ON offers(last_seen);
|
||||||
|
CREATE INDEX idx_offers_answerer ON offers(answerer_username);
|
||||||
|
|
||||||
|
-- Step 6: Recreate ice_candidates table with username instead of peer_id
|
||||||
|
CREATE TABLE ice_candidates_new (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
offer_id TEXT NOT NULL,
|
||||||
|
username TEXT NOT NULL,
|
||||||
|
role TEXT NOT NULL CHECK(role IN ('offerer', 'answerer')),
|
||||||
|
candidate TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
FOREIGN KEY (offer_id) REFERENCES offers(id) ON DELETE CASCADE,
|
||||||
|
FOREIGN KEY (username) REFERENCES usernames(username) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
-- Step 7: Migrate ICE candidates data
|
||||||
|
INSERT INTO ice_candidates_new (offer_id, username, role, candidate, created_at)
|
||||||
|
SELECT offer_id, peer_id as username, role, candidate, created_at
|
||||||
|
FROM ice_candidates;
|
||||||
|
|
||||||
|
-- Step 8: Drop old ice_candidates table
|
||||||
|
DROP TABLE ice_candidates;
|
||||||
|
|
||||||
|
-- Step 9: Rename new table
|
||||||
|
ALTER TABLE ice_candidates_new RENAME TO ice_candidates;
|
||||||
|
|
||||||
|
-- Step 10: Recreate indexes
|
||||||
|
CREATE INDEX idx_ice_offer ON ice_candidates(offer_id);
|
||||||
|
CREATE INDEX idx_ice_username ON ice_candidates(username);
|
||||||
|
CREATE INDEX idx_ice_role ON ice_candidates(role);
|
||||||
|
CREATE INDEX idx_ice_created ON ice_candidates(created_at);
|
||||||
81
migrations/fresh_schema.sql
Normal file
81
migrations/fresh_schema.sql
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
-- Fresh schema for Rondevu v0.5.0+
|
||||||
|
-- Unified Ed25519 authentication - username/keypair only
|
||||||
|
-- This is the complete schema without migration steps
|
||||||
|
|
||||||
|
-- Drop existing tables if they exist
|
||||||
|
DROP TABLE IF EXISTS ice_candidates;
|
||||||
|
DROP TABLE IF EXISTS services;
|
||||||
|
DROP TABLE IF EXISTS offers;
|
||||||
|
DROP TABLE IF EXISTS usernames;
|
||||||
|
|
||||||
|
-- Usernames table (now required for all users, even anonymous)
|
||||||
|
CREATE TABLE usernames (
|
||||||
|
username TEXT PRIMARY KEY,
|
||||||
|
public_key TEXT NOT NULL UNIQUE,
|
||||||
|
claimed_at INTEGER NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL,
|
||||||
|
last_used INTEGER NOT NULL,
|
||||||
|
metadata TEXT,
|
||||||
|
CHECK(length(username) >= 3 AND length(username) <= 32)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_usernames_expires ON usernames(expires_at);
|
||||||
|
CREATE INDEX idx_usernames_public_key ON usernames(public_key);
|
||||||
|
|
||||||
|
-- Services table with discovery fields
|
||||||
|
CREATE TABLE services (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
service_fqn TEXT NOT NULL,
|
||||||
|
service_name TEXT NOT NULL,
|
||||||
|
version TEXT NOT NULL,
|
||||||
|
username TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL,
|
||||||
|
FOREIGN KEY (username) REFERENCES usernames(username) ON DELETE CASCADE,
|
||||||
|
UNIQUE(service_name, version, username)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_services_fqn ON services(service_fqn);
|
||||||
|
CREATE INDEX idx_services_discovery ON services(service_name, version);
|
||||||
|
CREATE INDEX idx_services_username ON services(username);
|
||||||
|
CREATE INDEX idx_services_expires ON services(expires_at);
|
||||||
|
|
||||||
|
-- Offers table (now uses username instead of peer_id)
|
||||||
|
CREATE TABLE offers (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
username TEXT NOT NULL,
|
||||||
|
service_id TEXT,
|
||||||
|
service_fqn TEXT,
|
||||||
|
sdp TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL,
|
||||||
|
last_seen INTEGER NOT NULL,
|
||||||
|
answerer_username TEXT,
|
||||||
|
answer_sdp TEXT,
|
||||||
|
answered_at INTEGER,
|
||||||
|
FOREIGN KEY (username) REFERENCES usernames(username) ON DELETE CASCADE,
|
||||||
|
FOREIGN KEY (answerer_username) REFERENCES usernames(username) ON DELETE SET NULL
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_offers_username ON offers(username);
|
||||||
|
CREATE INDEX idx_offers_service ON offers(service_id);
|
||||||
|
CREATE INDEX idx_offers_expires ON offers(expires_at);
|
||||||
|
CREATE INDEX idx_offers_last_seen ON offers(last_seen);
|
||||||
|
CREATE INDEX idx_offers_answerer ON offers(answerer_username);
|
||||||
|
|
||||||
|
-- ICE candidates table (now uses username instead of peer_id)
|
||||||
|
CREATE TABLE ice_candidates (
|
||||||
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
|
offer_id TEXT NOT NULL,
|
||||||
|
username TEXT NOT NULL,
|
||||||
|
role TEXT NOT NULL CHECK(role IN ('offerer', 'answerer')),
|
||||||
|
candidate TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
FOREIGN KEY (offer_id) REFERENCES offers(id) ON DELETE CASCADE,
|
||||||
|
FOREIGN KEY (username) REFERENCES usernames(username) ON DELETE CASCADE
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX idx_ice_offer ON ice_candidates(offer_id);
|
||||||
|
CREATE INDEX idx_ice_username ON ice_candidates(username);
|
||||||
|
CREATE INDEX idx_ice_role ON ice_candidates(role);
|
||||||
|
CREATE INDEX idx_ice_created ON ice_candidates(created_at);
|
||||||
56
package-lock.json
generated
56
package-lock.json
generated
@@ -1,14 +1,16 @@
|
|||||||
{
|
{
|
||||||
"name": "@xtr-dev/rondevu-server",
|
"name": "@xtr-dev/rondevu-server",
|
||||||
"version": "0.1.2",
|
"version": "0.5.0",
|
||||||
"lockfileVersion": 3,
|
"lockfileVersion": 3,
|
||||||
"requires": true,
|
"requires": true,
|
||||||
"packages": {
|
"packages": {
|
||||||
"": {
|
"": {
|
||||||
"name": "@xtr-dev/rondevu-server",
|
"name": "@xtr-dev/rondevu-server",
|
||||||
"version": "0.1.2",
|
"version": "0.5.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@hono/node-server": "^1.19.6",
|
"@hono/node-server": "^1.19.6",
|
||||||
|
"@noble/ed25519": "^3.0.0",
|
||||||
|
"@xtr-dev/rondevu-client": "^0.13.0",
|
||||||
"better-sqlite3": "^12.4.1",
|
"better-sqlite3": "^12.4.1",
|
||||||
"hono": "^4.10.4"
|
"hono": "^4.10.4"
|
||||||
},
|
},
|
||||||
@@ -22,9 +24,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@cloudflare/workers-types": {
|
"node_modules/@cloudflare/workers-types": {
|
||||||
"version": "4.20251115.0",
|
"version": "4.20251209.0",
|
||||||
"resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-4.20251115.0.tgz",
|
"resolved": "https://registry.npmjs.org/@cloudflare/workers-types/-/workers-types-4.20251209.0.tgz",
|
||||||
"integrity": "sha512-aM7jp7IfKhqKvfSaK1IhVTbSzxB6KQ4gX8e/W29tOuZk+YHlYXuRd/bMm4hWkfd7B1HWNWdsx1GTaEUoZIuVsw==",
|
"integrity": "sha512-O+cbUVwgb4NgUB39R1cITbRshlAAPy1UQV0l8xEy2xcZ3wTh3fMl9f5oBwLsVmE9JRhIZx6llCLOBVf53eI5xA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT OR Apache-2.0"
|
"license": "MIT OR Apache-2.0"
|
||||||
},
|
},
|
||||||
@@ -484,9 +486,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@hono/node-server": {
|
"node_modules/@hono/node-server": {
|
||||||
"version": "1.19.6",
|
"version": "1.19.7",
|
||||||
"resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.6.tgz",
|
"resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-1.19.7.tgz",
|
||||||
"integrity": "sha512-Shz/KjlIeAhfiuE93NDKVdZ7HdBVLQAfdbaXEaoAVO3ic9ibRSLGIQGkcBbFyuLr+7/1D5ZCINM8B+6IvXeMtw==",
|
"integrity": "sha512-vUcD0uauS7EU2caukW8z5lJKtoGMokxNbJtBiwHgpqxEXokaHCBkQUmCHhjFB1VUTWdqj25QoMkMKzgjq+uhrw==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=18.14.1"
|
"node": ">=18.14.1"
|
||||||
@@ -523,6 +525,15 @@
|
|||||||
"@jridgewell/sourcemap-codec": "^1.4.10"
|
"@jridgewell/sourcemap-codec": "^1.4.10"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@noble/ed25519": {
|
||||||
|
"version": "3.0.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@noble/ed25519/-/ed25519-3.0.0.tgz",
|
||||||
|
"integrity": "sha512-QyteqMNm0GLqfa5SoYbSC3+Pvykwpn95Zgth4MFVSMKBB75ELl9tX1LAVsN4c3HXOrakHsF2gL4zWDAYCcsnzg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"funding": {
|
||||||
|
"url": "https://paulmillr.com/funding/"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/@tsconfig/node10": {
|
"node_modules/@tsconfig/node10": {
|
||||||
"version": "1.0.12",
|
"version": "1.0.12",
|
||||||
"resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.12.tgz",
|
"resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.12.tgz",
|
||||||
@@ -562,15 +573,24 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/@types/node": {
|
"node_modules/@types/node": {
|
||||||
"version": "24.10.1",
|
"version": "24.10.2",
|
||||||
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.1.tgz",
|
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.2.tgz",
|
||||||
"integrity": "sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ==",
|
"integrity": "sha512-WOhQTZ4G8xZ1tjJTvKOpyEVSGgOTvJAfDK3FNFgELyaTpzhdgHVHeqW8V+UJvzF5BT+/B54T/1S2K6gd9c7bbA==",
|
||||||
"dev": true,
|
"dev": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"undici-types": "~7.16.0"
|
"undici-types": "~7.16.0"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@xtr-dev/rondevu-client": {
|
||||||
|
"version": "0.13.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@xtr-dev/rondevu-client/-/rondevu-client-0.13.0.tgz",
|
||||||
|
"integrity": "sha512-oauCveLga4lploxpoW8U0Fd9Fyz+SAsNQzIDvAIG1fkAnAJu9eajmLsZ5JfzzDi7h2Ew1ClZ7MOrmlRfG4vaBg==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@noble/ed25519": "^3.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/acorn": {
|
"node_modules/acorn": {
|
||||||
"version": "8.15.0",
|
"version": "8.15.0",
|
||||||
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
|
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
|
||||||
@@ -625,9 +645,9 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/better-sqlite3": {
|
"node_modules/better-sqlite3": {
|
||||||
"version": "12.4.1",
|
"version": "12.5.0",
|
||||||
"resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.4.1.tgz",
|
"resolved": "https://registry.npmjs.org/better-sqlite3/-/better-sqlite3-12.5.0.tgz",
|
||||||
"integrity": "sha512-3yVdyZhklTiNrtg+4WqHpJpFDd+WHTg2oM7UcR80GqL05AOV0xEJzc6qNvFYoEtE+hRp1n9MpN6/+4yhlGkDXQ==",
|
"integrity": "sha512-WwCZ/5Diz7rsF29o27o0Gcc1Du+l7Zsv7SYtVPG0X3G/uUI1LqdxrQI7c9Hs2FWpqXXERjW9hp6g3/tH7DlVKg==",
|
||||||
"hasInstallScript": true,
|
"hasInstallScript": true,
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
@@ -635,7 +655,7 @@
|
|||||||
"prebuild-install": "^7.1.1"
|
"prebuild-install": "^7.1.1"
|
||||||
},
|
},
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": "20.x || 22.x || 23.x || 24.x"
|
"node": "20.x || 22.x || 23.x || 24.x || 25.x"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"node_modules/bindings": {
|
"node_modules/bindings": {
|
||||||
@@ -817,9 +837,9 @@
|
|||||||
"license": "MIT"
|
"license": "MIT"
|
||||||
},
|
},
|
||||||
"node_modules/hono": {
|
"node_modules/hono": {
|
||||||
"version": "4.10.6",
|
"version": "4.10.8",
|
||||||
"resolved": "https://registry.npmjs.org/hono/-/hono-4.10.6.tgz",
|
"resolved": "https://registry.npmjs.org/hono/-/hono-4.10.8.tgz",
|
||||||
"integrity": "sha512-BIdolzGpDO9MQ4nu3AUuDwHZZ+KViNm+EZ75Ae55eMXMqLVhDFqEMXxtUe9Qh8hjL+pIna/frs2j6Y2yD5Ua/g==",
|
"integrity": "sha512-DDT0A0r6wzhe8zCGoYOmMeuGu3dyTAE40HHjwUsWFTEy5WxK1x2WDSsBPlEXgPbRIFY6miDualuUDbasPogIww==",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"engines": {
|
"engines": {
|
||||||
"node": ">=16.9.0"
|
"node": ">=16.9.0"
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
{
|
{
|
||||||
"name": "@xtr-dev/rondevu-server",
|
"name": "@xtr-dev/rondevu-server",
|
||||||
"version": "0.1.2",
|
"version": "0.5.0",
|
||||||
"description": "Topic-based peer discovery and signaling server for distributed P2P applications",
|
"description": "DNS-like WebRTC signaling server with username claiming and service discovery",
|
||||||
"main": "dist/index.js",
|
"main": "dist/index.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"build": "node build.js",
|
"build": "node build.js",
|
||||||
@@ -21,6 +21,8 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@hono/node-server": "^1.19.6",
|
"@hono/node-server": "^1.19.6",
|
||||||
|
"@noble/ed25519": "^3.0.0",
|
||||||
|
"@xtr-dev/rondevu-client": "^0.13.0",
|
||||||
"better-sqlite3": "^12.4.1",
|
"better-sqlite3": "^12.4.1",
|
||||||
"hono": "^4.10.4"
|
"hono": "^4.10.4"
|
||||||
}
|
}
|
||||||
|
|||||||
510
src/app.ts
510
src/app.ts
@@ -2,520 +2,92 @@ import { Hono } from 'hono';
|
|||||||
import { cors } from 'hono/cors';
|
import { cors } from 'hono/cors';
|
||||||
import { Storage } from './storage/types.ts';
|
import { Storage } from './storage/types.ts';
|
||||||
import { Config } from './config.ts';
|
import { Config } from './config.ts';
|
||||||
import { createAuthMiddleware, getAuthenticatedPeerId } from './middleware/auth.ts';
|
import { handleRpc, RpcRequest } from './rpc.ts';
|
||||||
import { generatePeerId, encryptPeerId } from './crypto.ts';
|
|
||||||
import { parseBloomFilter } from './bloom.ts';
|
// Constants
|
||||||
import type { Context } from 'hono';
|
const MAX_BATCH_SIZE = 100;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates the Hono application with topic-based WebRTC signaling endpoints
|
* Creates the Hono application with RPC interface
|
||||||
*/
|
*/
|
||||||
export function createApp(storage: Storage, config: Config) {
|
export function createApp(storage: Storage, config: Config) {
|
||||||
const app = new Hono();
|
const app = new Hono();
|
||||||
|
|
||||||
// Create auth middleware
|
// Enable CORS
|
||||||
const authMiddleware = createAuthMiddleware(config.authSecret);
|
|
||||||
|
|
||||||
// Enable CORS with dynamic origin handling
|
|
||||||
app.use('/*', cors({
|
app.use('/*', cors({
|
||||||
origin: (origin) => {
|
origin: (origin) => {
|
||||||
// If no origin restrictions (wildcard), allow any origin
|
|
||||||
if (config.corsOrigins.length === 1 && config.corsOrigins[0] === '*') {
|
if (config.corsOrigins.length === 1 && config.corsOrigins[0] === '*') {
|
||||||
return origin;
|
return origin;
|
||||||
}
|
}
|
||||||
// Otherwise check if origin is in allowed list
|
|
||||||
if (config.corsOrigins.includes(origin)) {
|
if (config.corsOrigins.includes(origin)) {
|
||||||
return origin;
|
return origin;
|
||||||
}
|
}
|
||||||
// Default to first allowed origin
|
|
||||||
return config.corsOrigins[0];
|
return config.corsOrigins[0];
|
||||||
},
|
},
|
||||||
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
|
allowMethods: ['GET', 'POST', 'OPTIONS'],
|
||||||
allowHeaders: ['Content-Type', 'Origin', 'Authorization'],
|
allowHeaders: ['Content-Type', 'Origin'],
|
||||||
exposeHeaders: ['Content-Type'],
|
exposeHeaders: ['Content-Type'],
|
||||||
maxAge: 600,
|
credentials: false,
|
||||||
credentials: true,
|
maxAge: 86400,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
/**
|
// Root endpoint - server info
|
||||||
* GET /
|
|
||||||
* Returns server version information
|
|
||||||
*/
|
|
||||||
app.get('/', (c) => {
|
app.get('/', (c) => {
|
||||||
return c.json({
|
return c.json({
|
||||||
version: config.version,
|
version: config.version,
|
||||||
name: 'Rondevu',
|
name: 'Rondevu',
|
||||||
description: 'Topic-based peer discovery and signaling server'
|
description: 'WebRTC signaling with RPC interface and Ed25519 authentication',
|
||||||
});
|
}, 200);
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
// Health check
|
||||||
* GET /health
|
|
||||||
* Health check endpoint with version
|
|
||||||
*/
|
|
||||||
app.get('/health', (c) => {
|
app.get('/health', (c) => {
|
||||||
return c.json({
|
return c.json({
|
||||||
status: 'ok',
|
status: 'ok',
|
||||||
timestamp: Date.now(),
|
timestamp: Date.now(),
|
||||||
version: config.version
|
version: config.version,
|
||||||
});
|
}, 200);
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* POST /register
|
* POST /rpc
|
||||||
* Register a new peer and receive credentials
|
* RPC endpoint - accepts single or batch method calls
|
||||||
*/
|
*/
|
||||||
app.post('/register', async (c) => {
|
app.post('/rpc', async (c) => {
|
||||||
try {
|
|
||||||
// Generate new peer ID
|
|
||||||
const peerId = generatePeerId();
|
|
||||||
|
|
||||||
// Encrypt peer ID with server secret (async operation)
|
|
||||||
const secret = await encryptPeerId(peerId, config.authSecret);
|
|
||||||
|
|
||||||
return c.json({
|
|
||||||
peerId,
|
|
||||||
secret
|
|
||||||
}, 200);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Error registering peer:', err);
|
|
||||||
return c.json({ error: 'Internal server error' }, 500);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* POST /offers
|
|
||||||
* Creates one or more offers with topics
|
|
||||||
* Requires authentication
|
|
||||||
*/
|
|
||||||
app.post('/offers', authMiddleware, async (c) => {
|
|
||||||
try {
|
try {
|
||||||
const body = await c.req.json();
|
const body = await c.req.json();
|
||||||
const { offers } = body;
|
|
||||||
|
|
||||||
if (!Array.isArray(offers) || offers.length === 0) {
|
// Support both single request and batch array
|
||||||
return c.json({ error: 'Missing or invalid required parameter: offers (must be non-empty array)' }, 400);
|
const requests: RpcRequest[] = Array.isArray(body) ? body : [body];
|
||||||
|
|
||||||
|
// Validate requests
|
||||||
|
if (requests.length === 0) {
|
||||||
|
return c.json({ error: 'Empty request array' }, 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (offers.length > config.maxOffersPerRequest) {
|
if (requests.length > MAX_BATCH_SIZE) {
|
||||||
return c.json({ error: `Too many offers. Maximum ${config.maxOffersPerRequest} per request` }, 400);
|
return c.json({ error: `Too many requests in batch (max ${MAX_BATCH_SIZE})` }, 400);
|
||||||
}
|
}
|
||||||
|
|
||||||
const peerId = getAuthenticatedPeerId(c);
|
// Handle RPC
|
||||||
|
const responses = await handleRpc(requests, storage, config);
|
||||||
|
|
||||||
// Validate and prepare offers
|
// Return single response or array based on input
|
||||||
const offerRequests = [];
|
return c.json(Array.isArray(body) ? responses : responses[0], 200);
|
||||||
for (const offer of offers) {
|
|
||||||
// Validate SDP
|
|
||||||
if (!offer.sdp || typeof offer.sdp !== 'string') {
|
|
||||||
return c.json({ error: 'Each offer must have an sdp field' }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (offer.sdp.length > 65536) {
|
|
||||||
return c.json({ error: 'SDP must be 64KB or less' }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate secret if provided
|
|
||||||
if (offer.secret !== undefined) {
|
|
||||||
if (typeof offer.secret !== 'string') {
|
|
||||||
return c.json({ error: 'Secret must be a string' }, 400);
|
|
||||||
}
|
|
||||||
if (offer.secret.length > 128) {
|
|
||||||
return c.json({ error: 'Secret must be 128 characters or less' }, 400);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate topics
|
|
||||||
if (!Array.isArray(offer.topics) || offer.topics.length === 0) {
|
|
||||||
return c.json({ error: 'Each offer must have a non-empty topics array' }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (offer.topics.length > config.maxTopicsPerOffer) {
|
|
||||||
return c.json({ error: `Too many topics. Maximum ${config.maxTopicsPerOffer} per offer` }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const topic of offer.topics) {
|
|
||||||
if (typeof topic !== 'string' || topic.length === 0 || topic.length > 256) {
|
|
||||||
return c.json({ error: 'Each topic must be a string between 1 and 256 characters' }, 400);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate and clamp TTL
|
|
||||||
let ttl = offer.ttl || config.offerDefaultTtl;
|
|
||||||
if (ttl < config.offerMinTtl) {
|
|
||||||
ttl = config.offerMinTtl;
|
|
||||||
}
|
|
||||||
if (ttl > config.offerMaxTtl) {
|
|
||||||
ttl = config.offerMaxTtl;
|
|
||||||
}
|
|
||||||
|
|
||||||
offerRequests.push({
|
|
||||||
id: offer.id,
|
|
||||||
peerId,
|
|
||||||
sdp: offer.sdp,
|
|
||||||
topics: offer.topics,
|
|
||||||
expiresAt: Date.now() + ttl,
|
|
||||||
secret: offer.secret,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create offers
|
|
||||||
const createdOffers = await storage.createOffers(offerRequests);
|
|
||||||
|
|
||||||
// Return simplified response
|
|
||||||
return c.json({
|
|
||||||
offers: createdOffers.map(o => ({
|
|
||||||
id: o.id,
|
|
||||||
peerId: o.peerId,
|
|
||||||
topics: o.topics,
|
|
||||||
expiresAt: o.expiresAt
|
|
||||||
}))
|
|
||||||
}, 200);
|
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.error('Error creating offers:', err);
|
console.error('RPC error:', err);
|
||||||
return c.json({ error: 'Internal server error' }, 500);
|
return c.json({
|
||||||
|
success: false,
|
||||||
|
error: 'Invalid request format',
|
||||||
|
}, 400);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
/**
|
// 404 for all other routes
|
||||||
* GET /offers/by-topic/:topic
|
app.all('*', (c) => {
|
||||||
* Find offers by topic with optional bloom filter exclusion
|
return c.json({
|
||||||
* Public endpoint (no auth required)
|
error: 'Not found. Use POST /rpc for all API calls.',
|
||||||
*/
|
}, 404);
|
||||||
app.get('/offers/by-topic/:topic', async (c) => {
|
|
||||||
try {
|
|
||||||
const topic = c.req.param('topic');
|
|
||||||
const bloomParam = c.req.query('bloom');
|
|
||||||
const limitParam = c.req.query('limit');
|
|
||||||
|
|
||||||
const limit = limitParam ? Math.min(parseInt(limitParam, 10), 200) : 50;
|
|
||||||
|
|
||||||
// Parse bloom filter if provided
|
|
||||||
let excludePeerIds: string[] = [];
|
|
||||||
if (bloomParam) {
|
|
||||||
const bloom = parseBloomFilter(bloomParam);
|
|
||||||
if (!bloom) {
|
|
||||||
return c.json({ error: 'Invalid bloom filter format' }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get all offers for topic first
|
|
||||||
const allOffers = await storage.getOffersByTopic(topic);
|
|
||||||
|
|
||||||
// Test each peer ID against bloom filter
|
|
||||||
const excludeSet = new Set<string>();
|
|
||||||
for (const offer of allOffers) {
|
|
||||||
if (bloom.test(offer.peerId)) {
|
|
||||||
excludeSet.add(offer.peerId);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
excludePeerIds = Array.from(excludeSet);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Get filtered offers
|
|
||||||
let offers = await storage.getOffersByTopic(topic, excludePeerIds.length > 0 ? excludePeerIds : undefined);
|
|
||||||
|
|
||||||
// Apply limit
|
|
||||||
const total = offers.length;
|
|
||||||
offers = offers.slice(0, limit);
|
|
||||||
|
|
||||||
return c.json({
|
|
||||||
topic,
|
|
||||||
offers: offers.map(o => ({
|
|
||||||
id: o.id,
|
|
||||||
peerId: o.peerId,
|
|
||||||
sdp: o.sdp,
|
|
||||||
topics: o.topics,
|
|
||||||
expiresAt: o.expiresAt,
|
|
||||||
lastSeen: o.lastSeen,
|
|
||||||
hasSecret: !!o.secret // Indicate if secret is required without exposing it
|
|
||||||
})),
|
|
||||||
total: bloomParam ? total + excludePeerIds.length : total,
|
|
||||||
returned: offers.length
|
|
||||||
}, 200);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Error fetching offers by topic:', err);
|
|
||||||
return c.json({ error: 'Internal server error' }, 500);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* GET /topics
|
|
||||||
* List all topics with active peer counts (paginated)
|
|
||||||
* Public endpoint (no auth required)
|
|
||||||
* Query params:
|
|
||||||
* - limit: Max topics to return (default 50, max 200)
|
|
||||||
* - offset: Number of topics to skip (default 0)
|
|
||||||
* - startsWith: Filter topics starting with this prefix (optional)
|
|
||||||
*/
|
|
||||||
app.get('/topics', async (c) => {
|
|
||||||
try {
|
|
||||||
const limitParam = c.req.query('limit');
|
|
||||||
const offsetParam = c.req.query('offset');
|
|
||||||
const startsWithParam = c.req.query('startsWith');
|
|
||||||
|
|
||||||
const limit = limitParam ? Math.min(parseInt(limitParam, 10), 200) : 50;
|
|
||||||
const offset = offsetParam ? parseInt(offsetParam, 10) : 0;
|
|
||||||
const startsWith = startsWithParam || undefined;
|
|
||||||
|
|
||||||
const result = await storage.getTopics(limit, offset, startsWith);
|
|
||||||
|
|
||||||
return c.json({
|
|
||||||
topics: result.topics,
|
|
||||||
total: result.total,
|
|
||||||
limit,
|
|
||||||
offset,
|
|
||||||
...(startsWith && { startsWith })
|
|
||||||
}, 200);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Error fetching topics:', err);
|
|
||||||
return c.json({ error: 'Internal server error' }, 500);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* GET /peers/:peerId/offers
|
|
||||||
* View all offers from a specific peer
|
|
||||||
* Public endpoint
|
|
||||||
*/
|
|
||||||
app.get('/peers/:peerId/offers', async (c) => {
|
|
||||||
try {
|
|
||||||
const peerId = c.req.param('peerId');
|
|
||||||
const offers = await storage.getOffersByPeerId(peerId);
|
|
||||||
|
|
||||||
// Collect unique topics
|
|
||||||
const topicsSet = new Set<string>();
|
|
||||||
offers.forEach(o => o.topics.forEach(t => topicsSet.add(t)));
|
|
||||||
|
|
||||||
return c.json({
|
|
||||||
peerId,
|
|
||||||
offers: offers.map(o => ({
|
|
||||||
id: o.id,
|
|
||||||
sdp: o.sdp,
|
|
||||||
topics: o.topics,
|
|
||||||
expiresAt: o.expiresAt,
|
|
||||||
lastSeen: o.lastSeen,
|
|
||||||
hasSecret: !!o.secret // Indicate if secret is required without exposing it
|
|
||||||
})),
|
|
||||||
topics: Array.from(topicsSet)
|
|
||||||
}, 200);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Error fetching peer offers:', err);
|
|
||||||
return c.json({ error: 'Internal server error' }, 500);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* GET /offers/mine
|
|
||||||
* List all offers owned by authenticated peer
|
|
||||||
* Requires authentication
|
|
||||||
*/
|
|
||||||
app.get('/offers/mine', authMiddleware, async (c) => {
|
|
||||||
try {
|
|
||||||
const peerId = getAuthenticatedPeerId(c);
|
|
||||||
const offers = await storage.getOffersByPeerId(peerId);
|
|
||||||
|
|
||||||
return c.json({
|
|
||||||
peerId,
|
|
||||||
offers: offers.map(o => ({
|
|
||||||
id: o.id,
|
|
||||||
sdp: o.sdp,
|
|
||||||
topics: o.topics,
|
|
||||||
createdAt: o.createdAt,
|
|
||||||
expiresAt: o.expiresAt,
|
|
||||||
lastSeen: o.lastSeen,
|
|
||||||
secret: o.secret, // Owner can see the secret
|
|
||||||
answererPeerId: o.answererPeerId,
|
|
||||||
answeredAt: o.answeredAt
|
|
||||||
}))
|
|
||||||
}, 200);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Error fetching own offers:', err);
|
|
||||||
return c.json({ error: 'Internal server error' }, 500);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* DELETE /offers/:offerId
|
|
||||||
* Delete a specific offer
|
|
||||||
* Requires authentication and ownership
|
|
||||||
*/
|
|
||||||
app.delete('/offers/:offerId', authMiddleware, async (c) => {
|
|
||||||
try {
|
|
||||||
const offerId = c.req.param('offerId');
|
|
||||||
const peerId = getAuthenticatedPeerId(c);
|
|
||||||
|
|
||||||
const deleted = await storage.deleteOffer(offerId, peerId);
|
|
||||||
|
|
||||||
if (!deleted) {
|
|
||||||
return c.json({ error: 'Offer not found or not authorized' }, 404);
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.json({ deleted: true }, 200);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Error deleting offer:', err);
|
|
||||||
return c.json({ error: 'Internal server error' }, 500);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* POST /offers/:offerId/answer
|
|
||||||
* Answer a specific offer (locks it to answerer)
|
|
||||||
* Requires authentication
|
|
||||||
*/
|
|
||||||
app.post('/offers/:offerId/answer', authMiddleware, async (c) => {
|
|
||||||
try {
|
|
||||||
const offerId = c.req.param('offerId');
|
|
||||||
const peerId = getAuthenticatedPeerId(c);
|
|
||||||
const body = await c.req.json();
|
|
||||||
const { sdp, secret } = body;
|
|
||||||
|
|
||||||
if (!sdp || typeof sdp !== 'string') {
|
|
||||||
return c.json({ error: 'Missing or invalid required parameter: sdp' }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (sdp.length > 65536) {
|
|
||||||
return c.json({ error: 'SDP must be 64KB or less' }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Validate secret if provided
|
|
||||||
if (secret !== undefined && typeof secret !== 'string') {
|
|
||||||
return c.json({ error: 'Secret must be a string' }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = await storage.answerOffer(offerId, peerId, sdp, secret);
|
|
||||||
|
|
||||||
if (!result.success) {
|
|
||||||
return c.json({ error: result.error }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
return c.json({
|
|
||||||
offerId,
|
|
||||||
answererId: peerId,
|
|
||||||
answeredAt: Date.now()
|
|
||||||
}, 200);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Error answering offer:', err);
|
|
||||||
return c.json({ error: 'Internal server error' }, 500);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* GET /offers/answers
|
|
||||||
* Poll for answers to all of authenticated peer's offers
|
|
||||||
* Requires authentication (offerer)
|
|
||||||
*/
|
|
||||||
app.get('/offers/answers', authMiddleware, async (c) => {
|
|
||||||
try {
|
|
||||||
const peerId = getAuthenticatedPeerId(c);
|
|
||||||
const offers = await storage.getAnsweredOffers(peerId);
|
|
||||||
|
|
||||||
return c.json({
|
|
||||||
answers: offers.map(o => ({
|
|
||||||
offerId: o.id,
|
|
||||||
answererId: o.answererPeerId,
|
|
||||||
sdp: o.answerSdp,
|
|
||||||
answeredAt: o.answeredAt,
|
|
||||||
topics: o.topics
|
|
||||||
}))
|
|
||||||
}, 200);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Error fetching answers:', err);
|
|
||||||
return c.json({ error: 'Internal server error' }, 500);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* POST /offers/:offerId/ice-candidates
|
|
||||||
* Post ICE candidates for an offer
|
|
||||||
* Requires authentication (must be offerer or answerer)
|
|
||||||
*/
|
|
||||||
app.post('/offers/:offerId/ice-candidates', authMiddleware, async (c) => {
|
|
||||||
try {
|
|
||||||
const offerId = c.req.param('offerId');
|
|
||||||
const peerId = getAuthenticatedPeerId(c);
|
|
||||||
const body = await c.req.json();
|
|
||||||
const { candidates } = body;
|
|
||||||
|
|
||||||
if (!Array.isArray(candidates) || candidates.length === 0) {
|
|
||||||
return c.json({ error: 'Missing or invalid required parameter: candidates (must be non-empty array)' }, 400);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Verify offer exists and caller is offerer or answerer
|
|
||||||
const offer = await storage.getOfferById(offerId);
|
|
||||||
if (!offer) {
|
|
||||||
return c.json({ error: 'Offer not found or expired' }, 404);
|
|
||||||
}
|
|
||||||
|
|
||||||
let role: 'offerer' | 'answerer';
|
|
||||||
if (offer.peerId === peerId) {
|
|
||||||
role = 'offerer';
|
|
||||||
} else if (offer.answererPeerId === peerId) {
|
|
||||||
role = 'answerer';
|
|
||||||
} else {
|
|
||||||
return c.json({ error: 'Not authorized to post ICE candidates for this offer' }, 403);
|
|
||||||
}
|
|
||||||
|
|
||||||
const added = await storage.addIceCandidates(offerId, peerId, role, candidates);
|
|
||||||
|
|
||||||
return c.json({
|
|
||||||
offerId,
|
|
||||||
candidatesAdded: added
|
|
||||||
}, 200);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Error adding ICE candidates:', err);
|
|
||||||
return c.json({ error: 'Internal server error' }, 500);
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
/**
|
|
||||||
* GET /offers/:offerId/ice-candidates
|
|
||||||
* Poll for ICE candidates from the other peer
|
|
||||||
* Requires authentication (must be offerer or answerer)
|
|
||||||
*/
|
|
||||||
app.get('/offers/:offerId/ice-candidates', authMiddleware, async (c) => {
|
|
||||||
try {
|
|
||||||
const offerId = c.req.param('offerId');
|
|
||||||
const peerId = getAuthenticatedPeerId(c);
|
|
||||||
const sinceParam = c.req.query('since');
|
|
||||||
|
|
||||||
const since = sinceParam ? parseInt(sinceParam, 10) : undefined;
|
|
||||||
|
|
||||||
// Verify offer exists and caller is offerer or answerer
|
|
||||||
const offer = await storage.getOfferById(offerId);
|
|
||||||
if (!offer) {
|
|
||||||
return c.json({ error: 'Offer not found or expired' }, 404);
|
|
||||||
}
|
|
||||||
|
|
||||||
let targetRole: 'offerer' | 'answerer';
|
|
||||||
if (offer.peerId === peerId) {
|
|
||||||
// Offerer wants answerer's candidates
|
|
||||||
targetRole = 'answerer';
|
|
||||||
console.log(`[ICE GET] Offerer ${peerId} requesting answerer ICE candidates for offer ${offerId}, since=${since}, answererPeerId=${offer.answererPeerId}`);
|
|
||||||
} else if (offer.answererPeerId === peerId) {
|
|
||||||
// Answerer wants offerer's candidates
|
|
||||||
targetRole = 'offerer';
|
|
||||||
console.log(`[ICE GET] Answerer ${peerId} requesting offerer ICE candidates for offer ${offerId}, since=${since}, offererPeerId=${offer.peerId}`);
|
|
||||||
} else {
|
|
||||||
return c.json({ error: 'Not authorized to view ICE candidates for this offer' }, 403);
|
|
||||||
}
|
|
||||||
|
|
||||||
const candidates = await storage.getIceCandidates(offerId, targetRole, since);
|
|
||||||
console.log(`[ICE GET] Found ${candidates.length} candidates for offer ${offerId}, targetRole=${targetRole}, since=${since}`);
|
|
||||||
|
|
||||||
return c.json({
|
|
||||||
offerId,
|
|
||||||
candidates: candidates.map(c => ({
|
|
||||||
candidate: c.candidate,
|
|
||||||
peerId: c.peerId,
|
|
||||||
role: c.role,
|
|
||||||
createdAt: c.createdAt
|
|
||||||
}))
|
|
||||||
}, 200);
|
|
||||||
} catch (err) {
|
|
||||||
console.error('Error fetching ICE candidates:', err);
|
|
||||||
return c.json({ error: 'Internal server error' }, 500);
|
|
||||||
}
|
|
||||||
});
|
});
|
||||||
|
|
||||||
return app;
|
return app;
|
||||||
|
|||||||
66
src/bloom.ts
66
src/bloom.ts
@@ -1,66 +0,0 @@
|
|||||||
/**
|
|
||||||
* Bloom filter utility for testing if peer IDs might be in a set
|
|
||||||
* Used to filter out known peers from discovery results
|
|
||||||
*/
|
|
||||||
|
|
||||||
export class BloomFilter {
|
|
||||||
private bits: Uint8Array;
|
|
||||||
private size: number;
|
|
||||||
private numHashes: number;
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Creates a bloom filter from a base64 encoded bit array
|
|
||||||
*/
|
|
||||||
constructor(base64Data: string, numHashes: number = 3) {
|
|
||||||
// Decode base64 to Uint8Array (works in both Node.js and Workers)
|
|
||||||
const binaryString = atob(base64Data);
|
|
||||||
const bytes = new Uint8Array(binaryString.length);
|
|
||||||
for (let i = 0; i < binaryString.length; i++) {
|
|
||||||
bytes[i] = binaryString.charCodeAt(i);
|
|
||||||
}
|
|
||||||
this.bits = bytes;
|
|
||||||
this.size = this.bits.length * 8;
|
|
||||||
this.numHashes = numHashes;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Test if a peer ID might be in the filter
|
|
||||||
* Returns true if possibly in set, false if definitely not in set
|
|
||||||
*/
|
|
||||||
test(peerId: string): boolean {
|
|
||||||
for (let i = 0; i < this.numHashes; i++) {
|
|
||||||
const hash = this.hash(peerId, i);
|
|
||||||
const index = hash % this.size;
|
|
||||||
const byteIndex = Math.floor(index / 8);
|
|
||||||
const bitIndex = index % 8;
|
|
||||||
|
|
||||||
if (!(this.bits[byteIndex] & (1 << bitIndex))) {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Simple hash function (FNV-1a variant)
|
|
||||||
*/
|
|
||||||
private hash(str: string, seed: number): number {
|
|
||||||
let hash = 2166136261 ^ seed;
|
|
||||||
for (let i = 0; i < str.length; i++) {
|
|
||||||
hash ^= str.charCodeAt(i);
|
|
||||||
hash += (hash << 1) + (hash << 4) + (hash << 7) + (hash << 8) + (hash << 24);
|
|
||||||
}
|
|
||||||
return hash >>> 0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Helper to parse bloom filter from base64 string
|
|
||||||
*/
|
|
||||||
export function parseBloomFilter(base64: string): BloomFilter | null {
|
|
||||||
try {
|
|
||||||
return new BloomFilter(base64);
|
|
||||||
} catch {
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,5 +1,3 @@
|
|||||||
import { generateSecretKey } from './crypto.ts';
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Application configuration
|
* Application configuration
|
||||||
* Reads from environment variables with sensible defaults
|
* Reads from environment variables with sensible defaults
|
||||||
@@ -10,28 +8,17 @@ export interface Config {
|
|||||||
storagePath: string;
|
storagePath: string;
|
||||||
corsOrigins: string[];
|
corsOrigins: string[];
|
||||||
version: string;
|
version: string;
|
||||||
authSecret: string;
|
|
||||||
offerDefaultTtl: number;
|
offerDefaultTtl: number;
|
||||||
offerMaxTtl: number;
|
offerMaxTtl: number;
|
||||||
offerMinTtl: number;
|
offerMinTtl: number;
|
||||||
cleanupInterval: number;
|
cleanupInterval: number;
|
||||||
maxOffersPerRequest: number;
|
maxOffersPerRequest: number;
|
||||||
maxTopicsPerOffer: number;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Loads configuration from environment variables
|
* Loads configuration from environment variables
|
||||||
*/
|
*/
|
||||||
export function loadConfig(): Config {
|
export function loadConfig(): Config {
|
||||||
// Generate or load auth secret
|
|
||||||
let authSecret = process.env.AUTH_SECRET;
|
|
||||||
if (!authSecret) {
|
|
||||||
authSecret = generateSecretKey();
|
|
||||||
console.warn('WARNING: No AUTH_SECRET provided. Generated temporary secret:', authSecret);
|
|
||||||
console.warn('All peer credentials will be invalidated on server restart.');
|
|
||||||
console.warn('Set AUTH_SECRET environment variable to persist credentials across restarts.');
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
port: parseInt(process.env.PORT || '3000', 10),
|
port: parseInt(process.env.PORT || '3000', 10),
|
||||||
storageType: (process.env.STORAGE_TYPE || 'sqlite') as 'sqlite' | 'memory',
|
storageType: (process.env.STORAGE_TYPE || 'sqlite') as 'sqlite' | 'memory',
|
||||||
@@ -40,12 +27,10 @@ export function loadConfig(): Config {
|
|||||||
? process.env.CORS_ORIGINS.split(',').map(o => o.trim())
|
? process.env.CORS_ORIGINS.split(',').map(o => o.trim())
|
||||||
: ['*'],
|
: ['*'],
|
||||||
version: process.env.VERSION || 'unknown',
|
version: process.env.VERSION || 'unknown',
|
||||||
authSecret,
|
|
||||||
offerDefaultTtl: parseInt(process.env.OFFER_DEFAULT_TTL || '60000', 10),
|
offerDefaultTtl: parseInt(process.env.OFFER_DEFAULT_TTL || '60000', 10),
|
||||||
offerMaxTtl: parseInt(process.env.OFFER_MAX_TTL || '86400000', 10),
|
offerMaxTtl: parseInt(process.env.OFFER_MAX_TTL || '86400000', 10),
|
||||||
offerMinTtl: parseInt(process.env.OFFER_MIN_TTL || '60000', 10),
|
offerMinTtl: parseInt(process.env.OFFER_MIN_TTL || '60000', 10),
|
||||||
cleanupInterval: parseInt(process.env.CLEANUP_INTERVAL || '60000', 10),
|
cleanupInterval: parseInt(process.env.CLEANUP_INTERVAL || '60000', 10),
|
||||||
maxOffersPerRequest: parseInt(process.env.MAX_OFFERS_PER_REQUEST || '100', 10),
|
maxOffersPerRequest: parseInt(process.env.MAX_OFFERS_PER_REQUEST || '100', 10)
|
||||||
maxTopicsPerOffer: parseInt(process.env.MAX_TOPICS_PER_OFFER || '50', 10),
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|||||||
426
src/crypto.ts
426
src/crypto.ts
@@ -1,37 +1,35 @@
|
|||||||
/**
|
/**
|
||||||
* Crypto utilities for stateless peer authentication
|
* Crypto utilities for Ed25519-based authentication
|
||||||
|
* Uses @noble/ed25519 for Ed25519 signature verification
|
||||||
* Uses Web Crypto API for compatibility with both Node.js and Cloudflare Workers
|
* Uses Web Crypto API for compatibility with both Node.js and Cloudflare Workers
|
||||||
*/
|
*/
|
||||||
|
|
||||||
const ALGORITHM = 'AES-GCM';
|
import * as ed25519 from '@noble/ed25519';
|
||||||
const IV_LENGTH = 12; // 96 bits for GCM
|
|
||||||
const KEY_LENGTH = 32; // 256 bits
|
// Set SHA-512 hash function for ed25519 (required in @noble/ed25519 v3+)
|
||||||
|
// Uses Web Crypto API (compatible with both Node.js and Cloudflare Workers)
|
||||||
|
ed25519.hashes.sha512Async = async (message: Uint8Array) => {
|
||||||
|
return new Uint8Array(await crypto.subtle.digest('SHA-512', message as BufferSource));
|
||||||
|
};
|
||||||
|
|
||||||
|
// Username validation
|
||||||
|
const USERNAME_REGEX = /^[a-z0-9][a-z0-9-]*[a-z0-9]$/;
|
||||||
|
const USERNAME_MIN_LENGTH = 3;
|
||||||
|
const USERNAME_MAX_LENGTH = 32;
|
||||||
|
|
||||||
|
// Timestamp validation (5 minutes tolerance)
|
||||||
|
const TIMESTAMP_TOLERANCE_MS = 5 * 60 * 1000;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generates a random peer ID (16 bytes = 32 hex chars)
|
* Generates an anonymous username for users who don't want to claim one
|
||||||
|
* Format: anon-{timestamp}-{random}
|
||||||
|
* This reduces collision probability to near-zero
|
||||||
*/
|
*/
|
||||||
export function generatePeerId(): string {
|
export function generateAnonymousUsername(): string {
|
||||||
const bytes = crypto.getRandomValues(new Uint8Array(16));
|
const timestamp = Date.now().toString(36);
|
||||||
return Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
|
const random = crypto.getRandomValues(new Uint8Array(3));
|
||||||
}
|
const hex = Array.from(random).map(b => b.toString(16).padStart(2, '0')).join('');
|
||||||
|
return `anon-${timestamp}-${hex}`;
|
||||||
/**
|
|
||||||
* Generates a random secret key for encryption (32 bytes = 64 hex chars)
|
|
||||||
*/
|
|
||||||
export function generateSecretKey(): string {
|
|
||||||
const bytes = crypto.getRandomValues(new Uint8Array(KEY_LENGTH));
|
|
||||||
return Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Convert hex string to Uint8Array
|
|
||||||
*/
|
|
||||||
function hexToBytes(hex: string): Uint8Array {
|
|
||||||
const bytes = new Uint8Array(hex.length / 2);
|
|
||||||
for (let i = 0; i < hex.length; i += 2) {
|
|
||||||
bytes[i / 2] = parseInt(hex.substring(i, i + 2), 16);
|
|
||||||
}
|
|
||||||
return bytes;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -53,97 +51,331 @@ function base64ToBytes(base64: string): Uint8Array {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Encrypts a peer ID using the server secret key
|
* Validates a generic auth message format
|
||||||
* Returns base64-encoded encrypted data (IV + ciphertext)
|
* Expected format: action:username:params:timestamp
|
||||||
|
* Validates that the message contains the expected username and has a valid timestamp
|
||||||
*/
|
*/
|
||||||
export async function encryptPeerId(peerId: string, secretKeyHex: string): Promise<string> {
|
export function validateAuthMessage(
|
||||||
const keyBytes = hexToBytes(secretKeyHex);
|
expectedUsername: string,
|
||||||
|
message: string
|
||||||
|
): { valid: boolean; error?: string } {
|
||||||
|
const parts = message.split(':');
|
||||||
|
|
||||||
if (keyBytes.length !== KEY_LENGTH) {
|
if (parts.length < 3) {
|
||||||
throw new Error(`Secret key must be ${KEY_LENGTH * 2} hex characters (${KEY_LENGTH} bytes)`);
|
return { valid: false, error: 'Invalid message format: must have at least action:username:timestamp' };
|
||||||
}
|
}
|
||||||
|
|
||||||
// Import key
|
// Extract username (second part) and timestamp (last part)
|
||||||
const key = await crypto.subtle.importKey(
|
const messageUsername = parts[1];
|
||||||
'raw',
|
const timestamp = parseInt(parts[parts.length - 1], 10);
|
||||||
keyBytes,
|
|
||||||
{ name: ALGORITHM, length: 256 },
|
|
||||||
false,
|
|
||||||
['encrypt']
|
|
||||||
);
|
|
||||||
|
|
||||||
// Generate random IV
|
// Validate username matches
|
||||||
const iv = crypto.getRandomValues(new Uint8Array(IV_LENGTH));
|
if (messageUsername !== expectedUsername) {
|
||||||
|
return { valid: false, error: 'Username in message does not match authenticated username' };
|
||||||
|
}
|
||||||
|
|
||||||
// Encrypt peer ID
|
// Validate timestamp
|
||||||
const encoder = new TextEncoder();
|
if (isNaN(timestamp)) {
|
||||||
const data = encoder.encode(peerId);
|
return { valid: false, error: 'Invalid timestamp in message' };
|
||||||
|
}
|
||||||
|
|
||||||
const encrypted = await crypto.subtle.encrypt(
|
const timestampCheck = validateTimestamp(timestamp);
|
||||||
{ name: ALGORITHM, iv },
|
if (!timestampCheck.valid) {
|
||||||
key,
|
return timestampCheck;
|
||||||
data
|
}
|
||||||
);
|
|
||||||
|
|
||||||
// Combine IV + ciphertext and encode as base64
|
return { valid: true };
|
||||||
const combined = new Uint8Array(iv.length + encrypted.byteLength);
|
}
|
||||||
combined.set(iv, 0);
|
|
||||||
combined.set(new Uint8Array(encrypted), iv.length);
|
|
||||||
|
|
||||||
return bytesToBase64(combined);
|
// ===== Username and Ed25519 Signature Utilities =====
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates username format
|
||||||
|
* Rules: 3-32 chars, lowercase alphanumeric + dash, must start/end with alphanumeric
|
||||||
|
*/
|
||||||
|
export function validateUsername(username: string): { valid: boolean; error?: string } {
|
||||||
|
if (typeof username !== 'string') {
|
||||||
|
return { valid: false, error: 'Username must be a string' };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (username.length < USERNAME_MIN_LENGTH) {
|
||||||
|
return { valid: false, error: `Username must be at least ${USERNAME_MIN_LENGTH} characters` };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (username.length > USERNAME_MAX_LENGTH) {
|
||||||
|
return { valid: false, error: `Username must be at most ${USERNAME_MAX_LENGTH} characters` };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!USERNAME_REGEX.test(username)) {
|
||||||
|
return { valid: false, error: 'Username must be lowercase alphanumeric with optional dashes, and start/end with alphanumeric' };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { valid: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Decrypts an encrypted peer ID secret
|
* Validates service FQN format (service:version@username or service:version)
|
||||||
* Returns the plaintext peer ID or throws if decryption fails
|
* Service name: lowercase alphanumeric with dots/dashes (e.g., chat, file-share, com.example.chat)
|
||||||
|
* Version: semantic versioning (1.0.0, 2.1.3-beta, etc.)
|
||||||
|
* Username: optional, lowercase alphanumeric with dashes
|
||||||
*/
|
*/
|
||||||
export async function decryptPeerId(encryptedSecret: string, secretKeyHex: string): Promise<string> {
|
export function validateServiceFqn(fqn: string): { valid: boolean; error?: string } {
|
||||||
try {
|
if (typeof fqn !== 'string') {
|
||||||
const keyBytes = hexToBytes(secretKeyHex);
|
return { valid: false, error: 'Service FQN must be a string' };
|
||||||
|
}
|
||||||
|
|
||||||
if (keyBytes.length !== KEY_LENGTH) {
|
// Parse the FQN
|
||||||
throw new Error(`Secret key must be ${KEY_LENGTH * 2} hex characters (${KEY_LENGTH} bytes)`);
|
const parsed = parseServiceFqn(fqn);
|
||||||
|
if (!parsed) {
|
||||||
|
return { valid: false, error: 'Service FQN must be in format: service:version[@username]' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const { serviceName, version, username } = parsed;
|
||||||
|
|
||||||
|
// Validate service name (alphanumeric with dots/dashes)
|
||||||
|
const serviceNameRegex = /^[a-z0-9]([a-z0-9.-]*[a-z0-9])?$/;
|
||||||
|
if (!serviceNameRegex.test(serviceName)) {
|
||||||
|
return { valid: false, error: 'Service name must be lowercase alphanumeric with optional dots/dashes' };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (serviceName.length < 1 || serviceName.length > 128) {
|
||||||
|
return { valid: false, error: 'Service name must be 1-128 characters' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate version (semantic versioning)
|
||||||
|
const versionRegex = /^[0-9]+\.[0-9]+\.[0-9]+(-[a-z0-9.-]+)?$/;
|
||||||
|
if (!versionRegex.test(version)) {
|
||||||
|
return { valid: false, error: 'Version must be semantic versioning (e.g., 1.0.0, 2.1.3-beta)' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate username if present
|
||||||
|
if (username) {
|
||||||
|
const usernameCheck = validateUsername(username);
|
||||||
|
if (!usernameCheck.valid) {
|
||||||
|
return usernameCheck;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Decode base64
|
|
||||||
const combined = base64ToBytes(encryptedSecret);
|
|
||||||
|
|
||||||
// Extract IV and ciphertext
|
|
||||||
const iv = combined.slice(0, IV_LENGTH);
|
|
||||||
const ciphertext = combined.slice(IV_LENGTH);
|
|
||||||
|
|
||||||
// Import key
|
|
||||||
const key = await crypto.subtle.importKey(
|
|
||||||
'raw',
|
|
||||||
keyBytes,
|
|
||||||
{ name: ALGORITHM, length: 256 },
|
|
||||||
false,
|
|
||||||
['decrypt']
|
|
||||||
);
|
|
||||||
|
|
||||||
// Decrypt
|
|
||||||
const decrypted = await crypto.subtle.decrypt(
|
|
||||||
{ name: ALGORITHM, iv },
|
|
||||||
key,
|
|
||||||
ciphertext
|
|
||||||
);
|
|
||||||
|
|
||||||
const decoder = new TextDecoder();
|
|
||||||
return decoder.decode(decrypted);
|
|
||||||
} catch (err) {
|
|
||||||
throw new Error('Failed to decrypt peer ID: invalid secret or secret key');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
return { valid: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Validates that a peer ID and secret match
|
* Parse semantic version string into components
|
||||||
* Returns true if valid, false otherwise
|
|
||||||
*/
|
*/
|
||||||
export async function validateCredentials(peerId: string, encryptedSecret: string, secretKey: string): Promise<boolean> {
|
export function parseVersion(version: string): { major: number; minor: number; patch: number; prerelease?: string } | null {
|
||||||
|
const match = version.match(/^([0-9]+)\.([0-9]+)\.([0-9]+)(-[a-z0-9.-]+)?$/);
|
||||||
|
if (!match) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
major: parseInt(match[1], 10),
|
||||||
|
minor: parseInt(match[2], 10),
|
||||||
|
patch: parseInt(match[3], 10),
|
||||||
|
prerelease: match[4]?.substring(1), // Remove leading dash
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Check if two versions are compatible (same major version)
|
||||||
|
* Following semver rules: ^1.0.0 matches 1.x.x but not 2.x.x
|
||||||
|
*/
|
||||||
|
export function isVersionCompatible(requested: string, available: string): boolean {
|
||||||
|
const req = parseVersion(requested);
|
||||||
|
const avail = parseVersion(available);
|
||||||
|
|
||||||
|
if (!req || !avail) return false;
|
||||||
|
|
||||||
|
// Major version must match
|
||||||
|
if (req.major !== avail.major) return false;
|
||||||
|
|
||||||
|
// If major is 0, minor must also match (0.x.y is unstable)
|
||||||
|
if (req.major === 0 && req.minor !== avail.minor) return false;
|
||||||
|
|
||||||
|
// Available version must be >= requested version
|
||||||
|
if (avail.minor < req.minor) return false;
|
||||||
|
if (avail.minor === req.minor && avail.patch < req.patch) return false;
|
||||||
|
|
||||||
|
// Prerelease versions are only compatible with exact matches
|
||||||
|
if (req.prerelease && req.prerelease !== avail.prerelease) return false;
|
||||||
|
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Parse service FQN into components
|
||||||
|
* Formats supported:
|
||||||
|
* - service:version@username (e.g., "chat:1.0.0@alice")
|
||||||
|
* - service:version (e.g., "chat:1.0.0") for discovery
|
||||||
|
*/
|
||||||
|
export function parseServiceFqn(fqn: string): { serviceName: string; version: string; username: string | null } | null {
|
||||||
|
if (!fqn || typeof fqn !== 'string') return null;
|
||||||
|
|
||||||
|
// Check if username is present
|
||||||
|
const atIndex = fqn.lastIndexOf('@');
|
||||||
|
let serviceVersion: string;
|
||||||
|
let username: string | null = null;
|
||||||
|
|
||||||
|
if (atIndex > 0) {
|
||||||
|
// Format: service:version@username
|
||||||
|
serviceVersion = fqn.substring(0, atIndex);
|
||||||
|
username = fqn.substring(atIndex + 1);
|
||||||
|
} else {
|
||||||
|
// Format: service:version (no username)
|
||||||
|
serviceVersion = fqn;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Split service:version
|
||||||
|
const colonIndex = serviceVersion.indexOf(':');
|
||||||
|
if (colonIndex <= 0) return null; // No colon or colon at start
|
||||||
|
|
||||||
|
const serviceName = serviceVersion.substring(0, colonIndex);
|
||||||
|
const version = serviceVersion.substring(colonIndex + 1);
|
||||||
|
|
||||||
|
if (!serviceName || !version) return null;
|
||||||
|
|
||||||
|
return {
|
||||||
|
serviceName,
|
||||||
|
version,
|
||||||
|
username,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates timestamp is within acceptable range (prevents replay attacks)
|
||||||
|
*/
|
||||||
|
export function validateTimestamp(timestamp: number): { valid: boolean; error?: string } {
|
||||||
|
if (typeof timestamp !== 'number' || !Number.isFinite(timestamp)) {
|
||||||
|
return { valid: false, error: 'Timestamp must be a finite number' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const now = Date.now();
|
||||||
|
const diff = Math.abs(now - timestamp);
|
||||||
|
|
||||||
|
if (diff > TIMESTAMP_TOLERANCE_MS) {
|
||||||
|
return { valid: false, error: `Timestamp too old or too far in future (tolerance: ${TIMESTAMP_TOLERANCE_MS / 1000}s)` };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { valid: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verifies Ed25519 signature
|
||||||
|
* @param publicKey Base64-encoded Ed25519 public key (32 bytes)
|
||||||
|
* @param signature Base64-encoded Ed25519 signature (64 bytes)
|
||||||
|
* @param message Message that was signed (UTF-8 string)
|
||||||
|
* @returns true if signature is valid, false otherwise
|
||||||
|
*/
|
||||||
|
export async function verifyEd25519Signature(
|
||||||
|
publicKey: string,
|
||||||
|
signature: string,
|
||||||
|
message: string
|
||||||
|
): Promise<boolean> {
|
||||||
try {
|
try {
|
||||||
const decryptedPeerId = await decryptPeerId(encryptedSecret, secretKey);
|
// Decode base64 to bytes
|
||||||
return decryptedPeerId === peerId;
|
const publicKeyBytes = base64ToBytes(publicKey);
|
||||||
} catch {
|
const signatureBytes = base64ToBytes(signature);
|
||||||
|
|
||||||
|
// Encode message as UTF-8
|
||||||
|
const encoder = new TextEncoder();
|
||||||
|
const messageBytes = encoder.encode(message);
|
||||||
|
|
||||||
|
// Verify signature using @noble/ed25519 (async version)
|
||||||
|
const isValid = await ed25519.verifyAsync(signatureBytes, messageBytes, publicKeyBytes);
|
||||||
|
return isValid;
|
||||||
|
} catch (err) {
|
||||||
|
console.error('Ed25519 signature verification failed:', err);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates a username claim request
|
||||||
|
* Verifies format, timestamp, and signature
|
||||||
|
*/
|
||||||
|
export async function validateUsernameClaim(
|
||||||
|
username: string,
|
||||||
|
publicKey: string,
|
||||||
|
signature: string,
|
||||||
|
message: string
|
||||||
|
): Promise<{ valid: boolean; error?: string }> {
|
||||||
|
// Validate username format
|
||||||
|
const usernameCheck = validateUsername(username);
|
||||||
|
if (!usernameCheck.valid) {
|
||||||
|
return usernameCheck;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse message format: "claim:{username}:{timestamp}"
|
||||||
|
const parts = message.split(':');
|
||||||
|
if (parts.length !== 3 || parts[0] !== 'claim' || parts[1] !== username) {
|
||||||
|
return { valid: false, error: 'Invalid message format (expected: claim:{username}:{timestamp})' };
|
||||||
|
}
|
||||||
|
|
||||||
|
const timestamp = parseInt(parts[2], 10);
|
||||||
|
if (isNaN(timestamp)) {
|
||||||
|
return { valid: false, error: 'Invalid timestamp in message' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate timestamp
|
||||||
|
const timestampCheck = validateTimestamp(timestamp);
|
||||||
|
if (!timestampCheck.valid) {
|
||||||
|
return timestampCheck;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify signature
|
||||||
|
const signatureValid = await verifyEd25519Signature(publicKey, signature, message);
|
||||||
|
if (!signatureValid) {
|
||||||
|
return { valid: false, error: 'Invalid signature' };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { valid: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Validates a service publish signature
|
||||||
|
* Message format: publish:{username}:{serviceFqn}:{timestamp}
|
||||||
|
*/
|
||||||
|
export async function validateServicePublish(
|
||||||
|
username: string,
|
||||||
|
serviceFqn: string,
|
||||||
|
publicKey: string,
|
||||||
|
signature: string,
|
||||||
|
message: string
|
||||||
|
): Promise<{ valid: boolean; error?: string }> {
|
||||||
|
// Validate username format
|
||||||
|
const usernameCheck = validateUsername(username);
|
||||||
|
if (!usernameCheck.valid) {
|
||||||
|
return usernameCheck;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse message format: "publish:{username}:{serviceFqn}:{timestamp}"
|
||||||
|
// Note: serviceFqn can contain colons (e.g., "chat:2.0.0@user"), so we need careful parsing
|
||||||
|
const parts = message.split(':');
|
||||||
|
if (parts.length < 4 || parts[0] !== 'publish' || parts[1] !== username) {
|
||||||
|
return { valid: false, error: 'Invalid message format (expected: publish:{username}:{serviceFqn}:{timestamp})' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// The timestamp is the last part
|
||||||
|
const timestamp = parseInt(parts[parts.length - 1], 10);
|
||||||
|
if (isNaN(timestamp)) {
|
||||||
|
return { valid: false, error: 'Invalid timestamp in message' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// The serviceFqn is everything between username and timestamp
|
||||||
|
const extractedServiceFqn = parts.slice(2, parts.length - 1).join(':');
|
||||||
|
if (extractedServiceFqn !== serviceFqn) {
|
||||||
|
return { valid: false, error: `Service FQN mismatch (expected: ${serviceFqn}, got: ${extractedServiceFqn})` };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate timestamp
|
||||||
|
const timestampCheck = validateTimestamp(timestamp);
|
||||||
|
if (!timestampCheck.valid) {
|
||||||
|
return timestampCheck;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify signature
|
||||||
|
const signatureValid = await verifyEd25519Signature(publicKey, signature, message);
|
||||||
|
if (!signatureValid) {
|
||||||
|
return { valid: false, error: 'Invalid signature' };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { valid: true };
|
||||||
|
}
|
||||||
|
|||||||
@@ -20,7 +20,6 @@ async function main() {
|
|||||||
offerMinTtl: `${config.offerMinTtl}ms`,
|
offerMinTtl: `${config.offerMinTtl}ms`,
|
||||||
cleanupInterval: `${config.cleanupInterval}ms`,
|
cleanupInterval: `${config.cleanupInterval}ms`,
|
||||||
maxOffersPerRequest: config.maxOffersPerRequest,
|
maxOffersPerRequest: config.maxOffersPerRequest,
|
||||||
maxTopicsPerOffer: config.maxTopicsPerOffer,
|
|
||||||
corsOrigins: config.corsOrigins,
|
corsOrigins: config.corsOrigins,
|
||||||
version: config.version,
|
version: config.version,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -1,51 +0,0 @@
|
|||||||
import { Context, Next } from 'hono';
|
|
||||||
import { validateCredentials } from '../crypto.ts';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Authentication middleware for Rondevu
|
|
||||||
* Validates Bearer token in format: {peerId}:{encryptedSecret}
|
|
||||||
*/
|
|
||||||
export function createAuthMiddleware(authSecret: string) {
|
|
||||||
return async (c: Context, next: Next) => {
|
|
||||||
const authHeader = c.req.header('Authorization');
|
|
||||||
|
|
||||||
if (!authHeader) {
|
|
||||||
return c.json({ error: 'Missing Authorization header' }, 401);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Expect format: Bearer {peerId}:{secret}
|
|
||||||
const parts = authHeader.split(' ');
|
|
||||||
if (parts.length !== 2 || parts[0] !== 'Bearer') {
|
|
||||||
return c.json({ error: 'Invalid Authorization header format. Expected: Bearer {peerId}:{secret}' }, 401);
|
|
||||||
}
|
|
||||||
|
|
||||||
const credentials = parts[1].split(':');
|
|
||||||
if (credentials.length !== 2) {
|
|
||||||
return c.json({ error: 'Invalid credentials format. Expected: {peerId}:{secret}' }, 401);
|
|
||||||
}
|
|
||||||
|
|
||||||
const [peerId, encryptedSecret] = credentials;
|
|
||||||
|
|
||||||
// Validate credentials (async operation)
|
|
||||||
const isValid = await validateCredentials(peerId, encryptedSecret, authSecret);
|
|
||||||
if (!isValid) {
|
|
||||||
return c.json({ error: 'Invalid credentials' }, 401);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Attach peer ID to context for use in handlers
|
|
||||||
c.set('peerId', peerId);
|
|
||||||
|
|
||||||
await next();
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Helper to get authenticated peer ID from context
|
|
||||||
*/
|
|
||||||
export function getAuthenticatedPeerId(c: Context): string {
|
|
||||||
const peerId = c.get('peerId');
|
|
||||||
if (!peerId) {
|
|
||||||
throw new Error('No authenticated peer ID in context');
|
|
||||||
}
|
|
||||||
return peerId;
|
|
||||||
}
|
|
||||||
725
src/rpc.ts
Normal file
725
src/rpc.ts
Normal file
@@ -0,0 +1,725 @@
|
|||||||
|
import { Context } from 'hono';
|
||||||
|
import { Storage } from './storage/types.ts';
|
||||||
|
import { Config } from './config.ts';
|
||||||
|
import {
|
||||||
|
validateUsernameClaim,
|
||||||
|
validateServicePublish,
|
||||||
|
validateServiceFqn,
|
||||||
|
parseServiceFqn,
|
||||||
|
isVersionCompatible,
|
||||||
|
verifyEd25519Signature,
|
||||||
|
validateAuthMessage,
|
||||||
|
validateUsername,
|
||||||
|
} from './crypto.ts';
|
||||||
|
|
||||||
|
// Constants
|
||||||
|
const MAX_PAGE_SIZE = 100;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RPC request format
|
||||||
|
*/
|
||||||
|
export interface RpcRequest {
|
||||||
|
method: string;
|
||||||
|
message: string;
|
||||||
|
signature: string;
|
||||||
|
publicKey?: string; // Optional: for auto-claiming usernames
|
||||||
|
params?: any;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RPC response format
|
||||||
|
*/
|
||||||
|
export interface RpcResponse {
|
||||||
|
success: boolean;
|
||||||
|
result?: any;
|
||||||
|
error?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RPC method handler
|
||||||
|
*/
|
||||||
|
type RpcHandler = (
|
||||||
|
params: any,
|
||||||
|
message: string,
|
||||||
|
signature: string,
|
||||||
|
publicKey: string | undefined,
|
||||||
|
storage: Storage,
|
||||||
|
config: Config
|
||||||
|
) => Promise<any>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Verify authentication for a method call
|
||||||
|
* Automatically claims username if it doesn't exist
|
||||||
|
*/
|
||||||
|
async function verifyAuth(
|
||||||
|
username: string,
|
||||||
|
message: string,
|
||||||
|
signature: string,
|
||||||
|
publicKey: string | undefined,
|
||||||
|
storage: Storage
|
||||||
|
): Promise<{ valid: boolean; error?: string }> {
|
||||||
|
// Get username record to fetch public key
|
||||||
|
let usernameRecord = await storage.getUsername(username);
|
||||||
|
|
||||||
|
// Auto-claim username if it doesn't exist
|
||||||
|
if (!usernameRecord) {
|
||||||
|
if (!publicKey) {
|
||||||
|
return {
|
||||||
|
valid: false,
|
||||||
|
error: `Username "${username}" is not claimed and no public key provided for auto-claim.`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate username format before claiming
|
||||||
|
const usernameValidation = validateUsername(username);
|
||||||
|
if (!usernameValidation.valid) {
|
||||||
|
return usernameValidation;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify signature against the current message (not a claim message)
|
||||||
|
const signatureValid = await verifyEd25519Signature(publicKey, signature, message);
|
||||||
|
if (!signatureValid) {
|
||||||
|
return { valid: false, error: 'Invalid signature for auto-claim' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Auto-claim the username
|
||||||
|
const expiresAt = Date.now() + 365 * 24 * 60 * 60 * 1000; // 365 days
|
||||||
|
await storage.claimUsername({
|
||||||
|
username,
|
||||||
|
publicKey,
|
||||||
|
expiresAt,
|
||||||
|
});
|
||||||
|
|
||||||
|
usernameRecord = await storage.getUsername(username);
|
||||||
|
if (!usernameRecord) {
|
||||||
|
return { valid: false, error: 'Failed to claim username' };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify Ed25519 signature
|
||||||
|
const isValid = await verifyEd25519Signature(
|
||||||
|
usernameRecord.publicKey,
|
||||||
|
signature,
|
||||||
|
message
|
||||||
|
);
|
||||||
|
if (!isValid) {
|
||||||
|
return { valid: false, error: 'Invalid signature' };
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate message format and timestamp
|
||||||
|
const validation = validateAuthMessage(username, message);
|
||||||
|
if (!validation.valid) {
|
||||||
|
return { valid: false, error: validation.error };
|
||||||
|
}
|
||||||
|
|
||||||
|
return { valid: true };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Extract username from message
|
||||||
|
*/
|
||||||
|
function extractUsername(message: string): string | null {
|
||||||
|
// Message format: method:username:...
|
||||||
|
const parts = message.split(':');
|
||||||
|
if (parts.length < 2) return null;
|
||||||
|
return parts[1];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* RPC Method Handlers
|
||||||
|
*/
|
||||||
|
|
||||||
|
const handlers: Record<string, RpcHandler> = {
|
||||||
|
/**
|
||||||
|
* Check if username is available
|
||||||
|
*/
|
||||||
|
async getUser(params, message, signature, publicKey, storage, config) {
|
||||||
|
const { username } = params;
|
||||||
|
const claimed = await storage.getUsername(username);
|
||||||
|
|
||||||
|
if (!claimed) {
|
||||||
|
return {
|
||||||
|
username,
|
||||||
|
available: true,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
username: claimed.username,
|
||||||
|
available: false,
|
||||||
|
claimedAt: claimed.claimedAt,
|
||||||
|
expiresAt: claimed.expiresAt,
|
||||||
|
publicKey: claimed.publicKey,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get service by FQN - Supports 3 modes:
|
||||||
|
* 1. Direct lookup: FQN includes @username
|
||||||
|
* 2. Paginated discovery: FQN without @username, with limit/offset
|
||||||
|
* 3. Random discovery: FQN without @username, no limit
|
||||||
|
*/
|
||||||
|
async getService(params, message, signature, publicKey, storage, config) {
|
||||||
|
const { serviceFqn, limit, offset } = params;
|
||||||
|
const username = extractUsername(message);
|
||||||
|
|
||||||
|
// Verify authentication
|
||||||
|
if (username) {
|
||||||
|
const auth = await verifyAuth(username, message, signature, publicKey, storage);
|
||||||
|
if (!auth.valid) {
|
||||||
|
throw new Error(auth.error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse and validate FQN
|
||||||
|
const fqnValidation = validateServiceFqn(serviceFqn);
|
||||||
|
if (!fqnValidation.valid) {
|
||||||
|
throw new Error(fqnValidation.error || 'Invalid service FQN');
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = parseServiceFqn(serviceFqn);
|
||||||
|
if (!parsed) {
|
||||||
|
throw new Error('Failed to parse service FQN');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper: Filter services by version compatibility
|
||||||
|
const filterCompatibleServices = (services) => {
|
||||||
|
return services.filter((s) => {
|
||||||
|
const serviceVersion = parseServiceFqn(s.serviceFqn);
|
||||||
|
return (
|
||||||
|
serviceVersion &&
|
||||||
|
isVersionCompatible(parsed.version, serviceVersion.version)
|
||||||
|
);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
// Helper: Find available offer for service
|
||||||
|
const findAvailableOffer = async (service) => {
|
||||||
|
const offers = await storage.getOffersForService(service.id);
|
||||||
|
return offers.find((o) => !o.answererUsername);
|
||||||
|
};
|
||||||
|
|
||||||
|
// Helper: Build service response object
|
||||||
|
const buildServiceResponse = (service, offer) => ({
|
||||||
|
serviceId: service.id,
|
||||||
|
username: service.username,
|
||||||
|
serviceFqn: service.serviceFqn,
|
||||||
|
offerId: offer.id,
|
||||||
|
sdp: offer.sdp,
|
||||||
|
createdAt: service.createdAt,
|
||||||
|
expiresAt: service.expiresAt,
|
||||||
|
});
|
||||||
|
|
||||||
|
// Mode 1: Paginated discovery
|
||||||
|
if (limit !== undefined) {
|
||||||
|
const pageLimit = Math.min(Math.max(1, limit), MAX_PAGE_SIZE);
|
||||||
|
const pageOffset = Math.max(0, offset || 0);
|
||||||
|
|
||||||
|
const allServices = await storage.getServicesByName(parsed.service, parsed.version);
|
||||||
|
const compatibleServices = filterCompatibleServices(allServices);
|
||||||
|
|
||||||
|
// Get unique services per username with available offers
|
||||||
|
const usernameSet = new Set<string>();
|
||||||
|
const uniqueServices: any[] = [];
|
||||||
|
|
||||||
|
for (const service of compatibleServices) {
|
||||||
|
if (!usernameSet.has(service.username)) {
|
||||||
|
usernameSet.add(service.username);
|
||||||
|
const availableOffer = await findAvailableOffer(service);
|
||||||
|
|
||||||
|
if (availableOffer) {
|
||||||
|
uniqueServices.push(buildServiceResponse(service, availableOffer));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Paginate results
|
||||||
|
const paginatedServices = uniqueServices.slice(pageOffset, pageOffset + pageLimit);
|
||||||
|
|
||||||
|
return {
|
||||||
|
services: paginatedServices,
|
||||||
|
count: paginatedServices.length,
|
||||||
|
limit: pageLimit,
|
||||||
|
offset: pageOffset,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mode 2: Direct lookup with username
|
||||||
|
if (parsed.username) {
|
||||||
|
const service = await storage.getServiceByFqn(serviceFqn);
|
||||||
|
if (!service) {
|
||||||
|
throw new Error('Service not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const availableOffer = await findAvailableOffer(service);
|
||||||
|
if (!availableOffer) {
|
||||||
|
throw new Error('Service has no available offers');
|
||||||
|
}
|
||||||
|
|
||||||
|
return buildServiceResponse(service, availableOffer);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mode 3: Random discovery without username
|
||||||
|
const allServices = await storage.getServicesByName(parsed.service, parsed.version);
|
||||||
|
const compatibleServices = filterCompatibleServices(allServices);
|
||||||
|
|
||||||
|
if (compatibleServices.length === 0) {
|
||||||
|
throw new Error('No services found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const randomService = compatibleServices[Math.floor(Math.random() * compatibleServices.length)];
|
||||||
|
const availableOffer = await findAvailableOffer(randomService);
|
||||||
|
|
||||||
|
if (!availableOffer) {
|
||||||
|
throw new Error('Service has no available offers');
|
||||||
|
}
|
||||||
|
|
||||||
|
return buildServiceResponse(randomService, availableOffer);
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Publish a service
|
||||||
|
*/
|
||||||
|
async publishService(params, message, signature, publicKey, storage, config) {
|
||||||
|
const { serviceFqn, offers, ttl } = params;
|
||||||
|
const username = extractUsername(message);
|
||||||
|
|
||||||
|
if (!username) {
|
||||||
|
throw new Error('Username required for service publishing');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify authentication
|
||||||
|
const auth = await verifyAuth(username, message, signature, publicKey, storage);
|
||||||
|
if (!auth.valid) {
|
||||||
|
throw new Error(auth.error);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate service FQN
|
||||||
|
const fqnValidation = validateServiceFqn(serviceFqn);
|
||||||
|
if (!fqnValidation.valid) {
|
||||||
|
throw new Error(fqnValidation.error || 'Invalid service FQN');
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = parseServiceFqn(serviceFqn);
|
||||||
|
if (!parsed || !parsed.username) {
|
||||||
|
throw new Error('Service FQN must include username');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (parsed.username !== username) {
|
||||||
|
throw new Error('Service FQN username must match authenticated username');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate offers
|
||||||
|
if (!offers || !Array.isArray(offers) || offers.length === 0) {
|
||||||
|
throw new Error('Must provide at least one offer');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (offers.length > config.maxOffersPerRequest) {
|
||||||
|
throw new Error(
|
||||||
|
`Too many offers (max ${config.maxOffersPerRequest})`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate each offer has valid SDP
|
||||||
|
offers.forEach((offer, index) => {
|
||||||
|
if (!offer || typeof offer !== 'object') {
|
||||||
|
throw new Error(`Invalid offer at index ${index}: must be an object`);
|
||||||
|
}
|
||||||
|
if (!offer.sdp || typeof offer.sdp !== 'string') {
|
||||||
|
throw new Error(`Invalid offer at index ${index}: missing or invalid SDP`);
|
||||||
|
}
|
||||||
|
if (!offer.sdp.trim()) {
|
||||||
|
throw new Error(`Invalid offer at index ${index}: SDP cannot be empty`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Create service with offers
|
||||||
|
const now = Date.now();
|
||||||
|
const offerTtl =
|
||||||
|
ttl !== undefined
|
||||||
|
? Math.min(
|
||||||
|
Math.max(ttl, config.offerMinTtl),
|
||||||
|
config.offerMaxTtl
|
||||||
|
)
|
||||||
|
: config.offerDefaultTtl;
|
||||||
|
const expiresAt = now + offerTtl;
|
||||||
|
|
||||||
|
// Prepare offer requests with TTL
|
||||||
|
const offerRequests = offers.map(offer => ({
|
||||||
|
username,
|
||||||
|
serviceFqn,
|
||||||
|
sdp: offer.sdp,
|
||||||
|
expiresAt,
|
||||||
|
}));
|
||||||
|
|
||||||
|
const result = await storage.createService({
|
||||||
|
serviceFqn,
|
||||||
|
expiresAt,
|
||||||
|
offers: offerRequests,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
serviceId: result.service.id,
|
||||||
|
username: result.service.username,
|
||||||
|
serviceFqn: result.service.serviceFqn,
|
||||||
|
offers: result.offers.map(offer => ({
|
||||||
|
offerId: offer.id,
|
||||||
|
sdp: offer.sdp,
|
||||||
|
createdAt: offer.createdAt,
|
||||||
|
expiresAt: offer.expiresAt,
|
||||||
|
})),
|
||||||
|
createdAt: result.service.createdAt,
|
||||||
|
expiresAt: result.service.expiresAt,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete a service
|
||||||
|
*/
|
||||||
|
async deleteService(params, message, signature, publicKey, storage, config) {
|
||||||
|
const { serviceFqn } = params;
|
||||||
|
const username = extractUsername(message);
|
||||||
|
|
||||||
|
if (!username) {
|
||||||
|
throw new Error('Username required');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify authentication
|
||||||
|
const auth = await verifyAuth(username, message, signature, publicKey, storage);
|
||||||
|
if (!auth.valid) {
|
||||||
|
throw new Error(auth.error);
|
||||||
|
}
|
||||||
|
|
||||||
|
const parsed = parseServiceFqn(serviceFqn);
|
||||||
|
if (!parsed || !parsed.username) {
|
||||||
|
throw new Error('Service FQN must include username');
|
||||||
|
}
|
||||||
|
|
||||||
|
const service = await storage.getServiceByFqn(serviceFqn);
|
||||||
|
if (!service) {
|
||||||
|
throw new Error('Service not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const deleted = await storage.deleteService(service.id, username);
|
||||||
|
if (!deleted) {
|
||||||
|
throw new Error('Service not found or not owned by this username');
|
||||||
|
}
|
||||||
|
|
||||||
|
return { success: true };
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Answer an offer
|
||||||
|
*/
|
||||||
|
async answerOffer(params, message, signature, publicKey, storage, config) {
|
||||||
|
const { serviceFqn, offerId, sdp } = params;
|
||||||
|
const username = extractUsername(message);
|
||||||
|
|
||||||
|
if (!username) {
|
||||||
|
throw new Error('Username required');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify authentication
|
||||||
|
const auth = await verifyAuth(username, message, signature, publicKey, storage);
|
||||||
|
if (!auth.valid) {
|
||||||
|
throw new Error(auth.error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!sdp || typeof sdp !== 'string' || sdp.length === 0) {
|
||||||
|
throw new Error('Invalid SDP');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (sdp.length > 64 * 1024) {
|
||||||
|
throw new Error('SDP too large (max 64KB)');
|
||||||
|
}
|
||||||
|
|
||||||
|
const offer = await storage.getOfferById(offerId);
|
||||||
|
if (!offer) {
|
||||||
|
throw new Error('Offer not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (offer.answererUsername) {
|
||||||
|
throw new Error('Offer already answered');
|
||||||
|
}
|
||||||
|
|
||||||
|
await storage.answerOffer(offerId, username, sdp);
|
||||||
|
|
||||||
|
return { success: true, offerId };
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get answer for an offer
|
||||||
|
*/
|
||||||
|
async getOfferAnswer(params, message, signature, publicKey, storage, config) {
|
||||||
|
const { serviceFqn, offerId } = params;
|
||||||
|
const username = extractUsername(message);
|
||||||
|
|
||||||
|
if (!username) {
|
||||||
|
throw new Error('Username required');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify authentication
|
||||||
|
const auth = await verifyAuth(username, message, signature, publicKey, storage);
|
||||||
|
if (!auth.valid) {
|
||||||
|
throw new Error(auth.error);
|
||||||
|
}
|
||||||
|
|
||||||
|
const offer = await storage.getOfferById(offerId);
|
||||||
|
if (!offer) {
|
||||||
|
throw new Error('Offer not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (offer.username !== username) {
|
||||||
|
throw new Error('Not authorized to access this offer');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!offer.answererUsername || !offer.answerSdp) {
|
||||||
|
throw new Error('Offer not yet answered');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
sdp: offer.answerSdp,
|
||||||
|
offerId: offer.id,
|
||||||
|
answererId: offer.answererUsername,
|
||||||
|
answeredAt: offer.answeredAt,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Combined polling for answers and ICE candidates
|
||||||
|
*/
|
||||||
|
async poll(params, message, signature, publicKey, storage, config) {
|
||||||
|
const { since } = params;
|
||||||
|
const username = extractUsername(message);
|
||||||
|
|
||||||
|
if (!username) {
|
||||||
|
throw new Error('Username required');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify authentication
|
||||||
|
const auth = await verifyAuth(username, message, signature, publicKey, storage);
|
||||||
|
if (!auth.valid) {
|
||||||
|
throw new Error(auth.error);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sinceTimestamp = since || 0;
|
||||||
|
|
||||||
|
// Get all answered offers
|
||||||
|
const answeredOffers = await storage.getAnsweredOffers(username);
|
||||||
|
const filteredAnswers = answeredOffers.filter(
|
||||||
|
(offer) => offer.answeredAt && offer.answeredAt > sinceTimestamp
|
||||||
|
);
|
||||||
|
|
||||||
|
// Get all user's offers
|
||||||
|
const allOffers = await storage.getOffersByUsername(username);
|
||||||
|
|
||||||
|
// For each offer, get ICE candidates from both sides
|
||||||
|
const iceCandidatesByOffer: Record<string, any[]> = {};
|
||||||
|
|
||||||
|
for (const offer of allOffers) {
|
||||||
|
const offererCandidates = await storage.getIceCandidates(
|
||||||
|
offer.id,
|
||||||
|
'offerer',
|
||||||
|
sinceTimestamp
|
||||||
|
);
|
||||||
|
const answererCandidates = await storage.getIceCandidates(
|
||||||
|
offer.id,
|
||||||
|
'answerer',
|
||||||
|
sinceTimestamp
|
||||||
|
);
|
||||||
|
|
||||||
|
const allCandidates = [
|
||||||
|
...offererCandidates.map((c: any) => ({
|
||||||
|
...c,
|
||||||
|
role: 'offerer' as const,
|
||||||
|
})),
|
||||||
|
...answererCandidates.map((c: any) => ({
|
||||||
|
...c,
|
||||||
|
role: 'answerer' as const,
|
||||||
|
})),
|
||||||
|
];
|
||||||
|
|
||||||
|
if (allCandidates.length > 0) {
|
||||||
|
const isOfferer = offer.username === username;
|
||||||
|
const filtered = allCandidates.filter((c) =>
|
||||||
|
isOfferer ? c.role === 'answerer' : c.role === 'offerer'
|
||||||
|
);
|
||||||
|
|
||||||
|
if (filtered.length > 0) {
|
||||||
|
iceCandidatesByOffer[offer.id] = filtered;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
answers: filteredAnswers.map((offer) => ({
|
||||||
|
offerId: offer.id,
|
||||||
|
serviceId: offer.serviceId,
|
||||||
|
answererId: offer.answererUsername,
|
||||||
|
sdp: offer.answerSdp,
|
||||||
|
answeredAt: offer.answeredAt,
|
||||||
|
})),
|
||||||
|
iceCandidates: iceCandidatesByOffer,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Add ICE candidates
|
||||||
|
*/
|
||||||
|
async addIceCandidates(params, message, signature, publicKey, storage, config) {
|
||||||
|
const { serviceFqn, offerId, candidates } = params;
|
||||||
|
const username = extractUsername(message);
|
||||||
|
|
||||||
|
if (!username) {
|
||||||
|
throw new Error('Username required');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify authentication
|
||||||
|
const auth = await verifyAuth(username, message, signature, publicKey, storage);
|
||||||
|
if (!auth.valid) {
|
||||||
|
throw new Error(auth.error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Array.isArray(candidates) || candidates.length === 0) {
|
||||||
|
throw new Error('Missing or invalid required parameter: candidates');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate each candidate is an object (don't enforce structure per CLAUDE.md)
|
||||||
|
candidates.forEach((candidate, index) => {
|
||||||
|
if (!candidate || typeof candidate !== 'object') {
|
||||||
|
throw new Error(`Invalid candidate at index ${index}: must be an object`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const offer = await storage.getOfferById(offerId);
|
||||||
|
if (!offer) {
|
||||||
|
throw new Error('Offer not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const role = offer.username === username ? 'offerer' : 'answerer';
|
||||||
|
const count = await storage.addIceCandidates(
|
||||||
|
offerId,
|
||||||
|
username,
|
||||||
|
role,
|
||||||
|
candidates
|
||||||
|
);
|
||||||
|
|
||||||
|
return { count, offerId };
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Get ICE candidates
|
||||||
|
*/
|
||||||
|
async getIceCandidates(params, message, signature, publicKey, storage, config) {
|
||||||
|
const { serviceFqn, offerId, since } = params;
|
||||||
|
const username = extractUsername(message);
|
||||||
|
|
||||||
|
if (!username) {
|
||||||
|
throw new Error('Username required');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Verify authentication
|
||||||
|
const auth = await verifyAuth(username, message, signature, publicKey, storage);
|
||||||
|
if (!auth.valid) {
|
||||||
|
throw new Error(auth.error);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sinceTimestamp = since || 0;
|
||||||
|
|
||||||
|
const offer = await storage.getOfferById(offerId);
|
||||||
|
if (!offer) {
|
||||||
|
throw new Error('Offer not found');
|
||||||
|
}
|
||||||
|
|
||||||
|
const isOfferer = offer.username === username;
|
||||||
|
const role = isOfferer ? 'answerer' : 'offerer';
|
||||||
|
|
||||||
|
const candidates = await storage.getIceCandidates(
|
||||||
|
offerId,
|
||||||
|
role,
|
||||||
|
sinceTimestamp
|
||||||
|
);
|
||||||
|
|
||||||
|
return {
|
||||||
|
candidates: candidates.map((c: any) => ({
|
||||||
|
candidate: c.candidate,
|
||||||
|
createdAt: c.createdAt,
|
||||||
|
})),
|
||||||
|
offerId,
|
||||||
|
};
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Handle RPC batch request
|
||||||
|
*/
|
||||||
|
export async function handleRpc(
|
||||||
|
requests: RpcRequest[],
|
||||||
|
storage: Storage,
|
||||||
|
config: Config
|
||||||
|
): Promise<RpcResponse[]> {
|
||||||
|
const responses: RpcResponse[] = [];
|
||||||
|
|
||||||
|
for (const request of requests) {
|
||||||
|
try {
|
||||||
|
const { method, message, signature, publicKey, params } = request;
|
||||||
|
|
||||||
|
// Validate request
|
||||||
|
if (!method || typeof method !== 'string') {
|
||||||
|
responses.push({
|
||||||
|
success: false,
|
||||||
|
error: 'Missing or invalid method',
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!message || typeof message !== 'string') {
|
||||||
|
responses.push({
|
||||||
|
success: false,
|
||||||
|
error: 'Missing or invalid message',
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!signature || typeof signature !== 'string') {
|
||||||
|
responses.push({
|
||||||
|
success: false,
|
||||||
|
error: 'Missing or invalid signature',
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get handler
|
||||||
|
const handler = handlers[method];
|
||||||
|
if (!handler) {
|
||||||
|
responses.push({
|
||||||
|
success: false,
|
||||||
|
error: `Unknown method: ${method}`,
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Execute handler
|
||||||
|
const result = await handler(
|
||||||
|
params || {},
|
||||||
|
message,
|
||||||
|
signature,
|
||||||
|
publicKey,
|
||||||
|
storage,
|
||||||
|
config
|
||||||
|
);
|
||||||
|
|
||||||
|
responses.push({
|
||||||
|
success: true,
|
||||||
|
result,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
responses.push({
|
||||||
|
success: false,
|
||||||
|
error: (err as Error).message || 'Internal server error',
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return responses;
|
||||||
|
}
|
||||||
@@ -1,9 +1,21 @@
|
|||||||
import { Storage, Offer, IceCandidate, CreateOfferRequest, TopicInfo } from './types.ts';
|
// Use Web Crypto API (available globally in Cloudflare Workers)
|
||||||
|
import {
|
||||||
|
Storage,
|
||||||
|
Offer,
|
||||||
|
IceCandidate,
|
||||||
|
CreateOfferRequest,
|
||||||
|
Username,
|
||||||
|
ClaimUsernameRequest,
|
||||||
|
Service,
|
||||||
|
CreateServiceRequest,
|
||||||
|
} from './types.ts';
|
||||||
import { generateOfferHash } from './hash-id.ts';
|
import { generateOfferHash } from './hash-id.ts';
|
||||||
|
import { parseServiceFqn } from '../crypto.ts';
|
||||||
|
|
||||||
|
const YEAR_IN_MS = 365 * 24 * 60 * 60 * 1000; // 365 days
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* D1 storage adapter for topic-based offer management using Cloudflare D1
|
* D1 storage adapter for rondevu DNS-like system using Cloudflare D1
|
||||||
* NOTE: This implementation is a placeholder and needs to be fully tested
|
|
||||||
*/
|
*/
|
||||||
export class D1Storage implements Storage {
|
export class D1Storage implements Storage {
|
||||||
private db: D1Database;
|
private db: D1Database;
|
||||||
@@ -17,131 +29,122 @@ export class D1Storage implements Storage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initializes database schema with new topic-based structure
|
* Initializes database schema with username and service-based structure
|
||||||
* This should be run once during setup, not on every request
|
* This should be run once during setup, not on every request
|
||||||
*/
|
*/
|
||||||
async initializeDatabase(): Promise<void> {
|
async initializeDatabase(): Promise<void> {
|
||||||
await this.db.exec(`
|
await this.db.exec(`
|
||||||
|
-- WebRTC signaling offers
|
||||||
CREATE TABLE IF NOT EXISTS offers (
|
CREATE TABLE IF NOT EXISTS offers (
|
||||||
id TEXT PRIMARY KEY,
|
id TEXT PRIMARY KEY,
|
||||||
peer_id TEXT NOT NULL,
|
username TEXT NOT NULL,
|
||||||
|
service_id TEXT,
|
||||||
sdp TEXT NOT NULL,
|
sdp TEXT NOT NULL,
|
||||||
created_at INTEGER NOT NULL,
|
created_at INTEGER NOT NULL,
|
||||||
expires_at INTEGER NOT NULL,
|
expires_at INTEGER NOT NULL,
|
||||||
last_seen INTEGER NOT NULL,
|
last_seen INTEGER NOT NULL,
|
||||||
secret TEXT,
|
answerer_username TEXT,
|
||||||
answerer_peer_id TEXT,
|
|
||||||
answer_sdp TEXT,
|
answer_sdp TEXT,
|
||||||
answered_at INTEGER
|
answered_at INTEGER
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_offers_peer ON offers(peer_id);
|
CREATE INDEX IF NOT EXISTS idx_offers_username ON offers(username);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_offers_service ON offers(service_id);
|
||||||
CREATE INDEX IF NOT EXISTS idx_offers_expires ON offers(expires_at);
|
CREATE INDEX IF NOT EXISTS idx_offers_expires ON offers(expires_at);
|
||||||
CREATE INDEX IF NOT EXISTS idx_offers_last_seen ON offers(last_seen);
|
CREATE INDEX IF NOT EXISTS idx_offers_last_seen ON offers(last_seen);
|
||||||
CREATE INDEX IF NOT EXISTS idx_offers_answerer ON offers(answerer_peer_id);
|
CREATE INDEX IF NOT EXISTS idx_offers_answerer ON offers(answerer_username);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS offer_topics (
|
|
||||||
offer_id TEXT NOT NULL,
|
|
||||||
topic TEXT NOT NULL,
|
|
||||||
PRIMARY KEY (offer_id, topic),
|
|
||||||
FOREIGN KEY (offer_id) REFERENCES offers(id) ON DELETE CASCADE
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_topics_topic ON offer_topics(topic);
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_topics_offer ON offer_topics(offer_id);
|
|
||||||
|
|
||||||
|
-- ICE candidates table
|
||||||
CREATE TABLE IF NOT EXISTS ice_candidates (
|
CREATE TABLE IF NOT EXISTS ice_candidates (
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
offer_id TEXT NOT NULL,
|
offer_id TEXT NOT NULL,
|
||||||
peer_id TEXT NOT NULL,
|
username TEXT NOT NULL,
|
||||||
role TEXT NOT NULL CHECK(role IN ('offerer', 'answerer')),
|
role TEXT NOT NULL CHECK(role IN ('offerer', 'answerer')),
|
||||||
candidate TEXT NOT NULL, -- JSON: RTCIceCandidateInit object
|
candidate TEXT NOT NULL,
|
||||||
created_at INTEGER NOT NULL,
|
created_at INTEGER NOT NULL,
|
||||||
FOREIGN KEY (offer_id) REFERENCES offers(id) ON DELETE CASCADE
|
FOREIGN KEY (offer_id) REFERENCES offers(id) ON DELETE CASCADE
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_ice_offer ON ice_candidates(offer_id);
|
CREATE INDEX IF NOT EXISTS idx_ice_offer ON ice_candidates(offer_id);
|
||||||
CREATE INDEX IF NOT EXISTS idx_ice_peer ON ice_candidates(peer_id);
|
CREATE INDEX IF NOT EXISTS idx_ice_username ON ice_candidates(username);
|
||||||
CREATE INDEX IF NOT EXISTS idx_ice_created ON ice_candidates(created_at);
|
CREATE INDEX IF NOT EXISTS idx_ice_created ON ice_candidates(created_at);
|
||||||
|
|
||||||
|
-- Usernames table
|
||||||
|
CREATE TABLE IF NOT EXISTS usernames (
|
||||||
|
username TEXT PRIMARY KEY,
|
||||||
|
public_key TEXT NOT NULL UNIQUE,
|
||||||
|
claimed_at INTEGER NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL,
|
||||||
|
last_used INTEGER NOT NULL,
|
||||||
|
metadata TEXT,
|
||||||
|
CHECK(length(username) >= 3 AND length(username) <= 32)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_usernames_expires ON usernames(expires_at);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_usernames_public_key ON usernames(public_key);
|
||||||
|
|
||||||
|
-- Services table (new schema with extracted fields for discovery)
|
||||||
|
CREATE TABLE IF NOT EXISTS services (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
service_fqn TEXT NOT NULL,
|
||||||
|
service_name TEXT NOT NULL,
|
||||||
|
version TEXT NOT NULL,
|
||||||
|
username TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL,
|
||||||
|
FOREIGN KEY (username) REFERENCES usernames(username) ON DELETE CASCADE,
|
||||||
|
UNIQUE(service_fqn)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_services_fqn ON services(service_fqn);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_services_discovery ON services(service_name, version);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_services_username ON services(username);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_services_expires ON services(expires_at);
|
||||||
`);
|
`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ===== Offer Management =====
|
||||||
|
|
||||||
async createOffers(offers: CreateOfferRequest[]): Promise<Offer[]> {
|
async createOffers(offers: CreateOfferRequest[]): Promise<Offer[]> {
|
||||||
const created: Offer[] = [];
|
const created: Offer[] = [];
|
||||||
|
|
||||||
// D1 doesn't support true transactions yet, so we do this sequentially
|
// D1 doesn't support true transactions yet, so we do this sequentially
|
||||||
for (const offer of offers) {
|
for (const offer of offers) {
|
||||||
const id = offer.id || await generateOfferHash(offer.sdp, offer.topics);
|
const id = offer.id || await generateOfferHash(offer.sdp);
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
|
|
||||||
// Insert offer
|
|
||||||
await this.db.prepare(`
|
await this.db.prepare(`
|
||||||
INSERT INTO offers (id, peer_id, sdp, created_at, expires_at, last_seen, secret)
|
INSERT INTO offers (id, username, service_id, sdp, created_at, expires_at, last_seen)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||||
`).bind(id, offer.peerId, offer.sdp, now, offer.expiresAt, now, offer.secret || null).run();
|
`).bind(id, offer.username, offer.serviceId || null, offer.sdp, now, offer.expiresAt, now).run();
|
||||||
|
|
||||||
// Insert topics
|
|
||||||
for (const topic of offer.topics) {
|
|
||||||
await this.db.prepare(`
|
|
||||||
INSERT INTO offer_topics (offer_id, topic)
|
|
||||||
VALUES (?, ?)
|
|
||||||
`).bind(id, topic).run();
|
|
||||||
}
|
|
||||||
|
|
||||||
created.push({
|
created.push({
|
||||||
id,
|
id,
|
||||||
peerId: offer.peerId,
|
username: offer.username,
|
||||||
|
serviceId: offer.serviceId,
|
||||||
|
serviceFqn: offer.serviceFqn,
|
||||||
sdp: offer.sdp,
|
sdp: offer.sdp,
|
||||||
topics: offer.topics,
|
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
expiresAt: offer.expiresAt,
|
expiresAt: offer.expiresAt,
|
||||||
lastSeen: now,
|
lastSeen: now,
|
||||||
secret: offer.secret,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
return created;
|
return created;
|
||||||
}
|
}
|
||||||
|
|
||||||
async getOffersByTopic(topic: string, excludePeerIds?: string[]): Promise<Offer[]> {
|
async getOffersByUsername(username: string): Promise<Offer[]> {
|
||||||
let query = `
|
|
||||||
SELECT DISTINCT o.*
|
|
||||||
FROM offers o
|
|
||||||
INNER JOIN offer_topics ot ON o.id = ot.offer_id
|
|
||||||
WHERE ot.topic = ? AND o.expires_at > ?
|
|
||||||
`;
|
|
||||||
|
|
||||||
const params: any[] = [topic, Date.now()];
|
|
||||||
|
|
||||||
if (excludePeerIds && excludePeerIds.length > 0) {
|
|
||||||
const placeholders = excludePeerIds.map(() => '?').join(',');
|
|
||||||
query += ` AND o.peer_id NOT IN (${placeholders})`;
|
|
||||||
params.push(...excludePeerIds);
|
|
||||||
}
|
|
||||||
|
|
||||||
query += ' ORDER BY o.last_seen DESC';
|
|
||||||
|
|
||||||
const result = await this.db.prepare(query).bind(...params).all();
|
|
||||||
|
|
||||||
if (!result.results) {
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
return Promise.all(result.results.map(row => this.rowToOffer(row as any)));
|
|
||||||
}
|
|
||||||
|
|
||||||
async getOffersByPeerId(peerId: string): Promise<Offer[]> {
|
|
||||||
const result = await this.db.prepare(`
|
const result = await this.db.prepare(`
|
||||||
SELECT * FROM offers
|
SELECT * FROM offers
|
||||||
WHERE peer_id = ? AND expires_at > ?
|
WHERE username = ? AND expires_at > ?
|
||||||
ORDER BY last_seen DESC
|
ORDER BY last_seen DESC
|
||||||
`).bind(peerId, Date.now()).all();
|
`).bind(username, Date.now()).all();
|
||||||
|
|
||||||
if (!result.results) {
|
if (!result.results) {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
return Promise.all(result.results.map(row => this.rowToOffer(row as any)));
|
return result.results.map(row => this.rowToOffer(row as any));
|
||||||
}
|
}
|
||||||
|
|
||||||
async getOfferById(offerId: string): Promise<Offer | null> {
|
async getOfferById(offerId: string): Promise<Offer | null> {
|
||||||
@@ -157,11 +160,11 @@ export class D1Storage implements Storage {
|
|||||||
return this.rowToOffer(result as any);
|
return this.rowToOffer(result as any);
|
||||||
}
|
}
|
||||||
|
|
||||||
async deleteOffer(offerId: string, ownerPeerId: string): Promise<boolean> {
|
async deleteOffer(offerId: string, ownerUsername: string): Promise<boolean> {
|
||||||
const result = await this.db.prepare(`
|
const result = await this.db.prepare(`
|
||||||
DELETE FROM offers
|
DELETE FROM offers
|
||||||
WHERE id = ? AND peer_id = ?
|
WHERE id = ? AND username = ?
|
||||||
`).bind(offerId, ownerPeerId).run();
|
`).bind(offerId, ownerUsername).run();
|
||||||
|
|
||||||
return (result.meta.changes || 0) > 0;
|
return (result.meta.changes || 0) > 0;
|
||||||
}
|
}
|
||||||
@@ -176,9 +179,8 @@ export class D1Storage implements Storage {
|
|||||||
|
|
||||||
async answerOffer(
|
async answerOffer(
|
||||||
offerId: string,
|
offerId: string,
|
||||||
answererPeerId: string,
|
answererUsername: string,
|
||||||
answerSdp: string,
|
answerSdp: string
|
||||||
secret?: string
|
|
||||||
): Promise<{ success: boolean; error?: string }> {
|
): Promise<{ success: boolean; error?: string }> {
|
||||||
// Check if offer exists and is not expired
|
// Check if offer exists and is not expired
|
||||||
const offer = await this.getOfferById(offerId);
|
const offer = await this.getOfferById(offerId);
|
||||||
@@ -190,16 +192,8 @@ export class D1Storage implements Storage {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify secret if offer is protected
|
|
||||||
if (offer.secret && offer.secret !== secret) {
|
|
||||||
return {
|
|
||||||
success: false,
|
|
||||||
error: 'Invalid or missing secret'
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if offer already has an answerer
|
// Check if offer already has an answerer
|
||||||
if (offer.answererPeerId) {
|
if (offer.answererUsername) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: 'Offer already answered'
|
error: 'Offer already answered'
|
||||||
@@ -209,9 +203,9 @@ export class D1Storage implements Storage {
|
|||||||
// Update offer with answer
|
// Update offer with answer
|
||||||
const result = await this.db.prepare(`
|
const result = await this.db.prepare(`
|
||||||
UPDATE offers
|
UPDATE offers
|
||||||
SET answerer_peer_id = ?, answer_sdp = ?, answered_at = ?
|
SET answerer_username = ?, answer_sdp = ?, answered_at = ?
|
||||||
WHERE id = ? AND answerer_peer_id IS NULL
|
WHERE id = ? AND answerer_username IS NULL
|
||||||
`).bind(answererPeerId, answerSdp, Date.now(), offerId).run();
|
`).bind(answererUsername, answerSdp, Date.now(), offerId).run();
|
||||||
|
|
||||||
if ((result.meta.changes || 0) === 0) {
|
if ((result.meta.changes || 0) === 0) {
|
||||||
return {
|
return {
|
||||||
@@ -223,40 +217,39 @@ export class D1Storage implements Storage {
|
|||||||
return { success: true };
|
return { success: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
async getAnsweredOffers(offererPeerId: string): Promise<Offer[]> {
|
async getAnsweredOffers(offererUsername: string): Promise<Offer[]> {
|
||||||
const result = await this.db.prepare(`
|
const result = await this.db.prepare(`
|
||||||
SELECT * FROM offers
|
SELECT * FROM offers
|
||||||
WHERE peer_id = ? AND answerer_peer_id IS NOT NULL AND expires_at > ?
|
WHERE username = ? AND answerer_username IS NOT NULL AND expires_at > ?
|
||||||
ORDER BY answered_at DESC
|
ORDER BY answered_at DESC
|
||||||
`).bind(offererPeerId, Date.now()).all();
|
`).bind(offererUsername, Date.now()).all();
|
||||||
|
|
||||||
if (!result.results) {
|
if (!result.results) {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
return Promise.all(result.results.map(row => this.rowToOffer(row as any)));
|
return result.results.map(row => this.rowToOffer(row as any));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ===== ICE Candidate Management =====
|
||||||
|
|
||||||
async addIceCandidates(
|
async addIceCandidates(
|
||||||
offerId: string,
|
offerId: string,
|
||||||
peerId: string,
|
username: string,
|
||||||
role: 'offerer' | 'answerer',
|
role: 'offerer' | 'answerer',
|
||||||
candidates: any[]
|
candidates: any[]
|
||||||
): Promise<number> {
|
): Promise<number> {
|
||||||
console.log(`[D1] addIceCandidates: offerId=${offerId}, peerId=${peerId}, role=${role}, count=${candidates.length}`);
|
|
||||||
|
|
||||||
// Give each candidate a unique timestamp to avoid "since" filtering issues
|
|
||||||
// D1 doesn't have transactions, so insert one by one
|
// D1 doesn't have transactions, so insert one by one
|
||||||
for (let i = 0; i < candidates.length; i++) {
|
for (let i = 0; i < candidates.length; i++) {
|
||||||
const timestamp = Date.now() + i; // Ensure unique timestamps
|
const timestamp = Date.now() + i;
|
||||||
await this.db.prepare(`
|
await this.db.prepare(`
|
||||||
INSERT INTO ice_candidates (offer_id, peer_id, role, candidate, created_at)
|
INSERT INTO ice_candidates (offer_id, username, role, candidate, created_at)
|
||||||
VALUES (?, ?, ?, ?, ?)
|
VALUES (?, ?, ?, ?, ?)
|
||||||
`).bind(
|
`).bind(
|
||||||
offerId,
|
offerId,
|
||||||
peerId,
|
username,
|
||||||
role,
|
role,
|
||||||
JSON.stringify(candidates[i]), // Store full object as JSON
|
JSON.stringify(candidates[i]),
|
||||||
timestamp
|
timestamp
|
||||||
).run();
|
).run();
|
||||||
}
|
}
|
||||||
@@ -283,82 +276,289 @@ export class D1Storage implements Storage {
|
|||||||
|
|
||||||
query += ' ORDER BY created_at ASC';
|
query += ' ORDER BY created_at ASC';
|
||||||
|
|
||||||
console.log(`[D1] getIceCandidates query: offerId=${offerId}, targetRole=${targetRole}, since=${since}`);
|
|
||||||
const result = await this.db.prepare(query).bind(...params).all();
|
const result = await this.db.prepare(query).bind(...params).all();
|
||||||
console.log(`[D1] getIceCandidates result: ${result.results?.length || 0} rows`);
|
|
||||||
|
|
||||||
if (!result.results) {
|
if (!result.results) {
|
||||||
return [];
|
return [];
|
||||||
}
|
}
|
||||||
|
|
||||||
const candidates = result.results.map((row: any) => ({
|
return result.results.map((row: any) => ({
|
||||||
id: row.id,
|
id: row.id,
|
||||||
offerId: row.offer_id,
|
offerId: row.offer_id,
|
||||||
peerId: row.peer_id,
|
username: row.username,
|
||||||
role: row.role,
|
role: row.role,
|
||||||
candidate: JSON.parse(row.candidate), // Parse JSON back to object
|
candidate: JSON.parse(row.candidate),
|
||||||
createdAt: row.created_at,
|
createdAt: row.created_at,
|
||||||
}));
|
}));
|
||||||
|
|
||||||
if (candidates.length > 0) {
|
|
||||||
console.log(`[D1] First candidate createdAt: ${candidates[0].createdAt}, since: ${since}`);
|
|
||||||
}
|
|
||||||
|
|
||||||
return candidates;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
async getTopics(limit: number, offset: number, startsWith?: string): Promise<{
|
// ===== Username Management =====
|
||||||
topics: TopicInfo[];
|
|
||||||
total: number;
|
async claimUsername(request: ClaimUsernameRequest): Promise<Username> {
|
||||||
|
const now = Date.now();
|
||||||
|
const expiresAt = now + YEAR_IN_MS;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// Try to insert or update
|
||||||
|
const result = await this.db.prepare(`
|
||||||
|
INSERT INTO usernames (username, public_key, claimed_at, expires_at, last_used, metadata)
|
||||||
|
VALUES (?, ?, ?, ?, ?, NULL)
|
||||||
|
ON CONFLICT(username) DO UPDATE SET
|
||||||
|
expires_at = ?,
|
||||||
|
last_used = ?
|
||||||
|
WHERE public_key = ?
|
||||||
|
`).bind(
|
||||||
|
request.username,
|
||||||
|
request.publicKey,
|
||||||
|
now,
|
||||||
|
expiresAt,
|
||||||
|
now,
|
||||||
|
expiresAt,
|
||||||
|
now,
|
||||||
|
request.publicKey
|
||||||
|
).run();
|
||||||
|
|
||||||
|
if ((result.meta.changes || 0) === 0) {
|
||||||
|
throw new Error('Username already claimed by different public key');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
username: request.username,
|
||||||
|
publicKey: request.publicKey,
|
||||||
|
claimedAt: now,
|
||||||
|
expiresAt,
|
||||||
|
lastUsed: now,
|
||||||
|
};
|
||||||
|
} catch (err: any) {
|
||||||
|
// Handle UNIQUE constraint on public_key
|
||||||
|
if (err.message?.includes('UNIQUE constraint failed: usernames.public_key')) {
|
||||||
|
throw new Error('This public key has already claimed a different username');
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async getUsername(username: string): Promise<Username | null> {
|
||||||
|
const result = await this.db.prepare(`
|
||||||
|
SELECT * FROM usernames
|
||||||
|
WHERE username = ? AND expires_at > ?
|
||||||
|
`).bind(username, Date.now()).first();
|
||||||
|
|
||||||
|
if (!result) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const row = result as any;
|
||||||
|
|
||||||
|
return {
|
||||||
|
username: row.username,
|
||||||
|
publicKey: row.public_key,
|
||||||
|
claimedAt: row.claimed_at,
|
||||||
|
expiresAt: row.expires_at,
|
||||||
|
lastUsed: row.last_used,
|
||||||
|
metadata: row.metadata || undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async deleteExpiredUsernames(now: number): Promise<number> {
|
||||||
|
const result = await this.db.prepare(`
|
||||||
|
DELETE FROM usernames WHERE expires_at < ?
|
||||||
|
`).bind(now).run();
|
||||||
|
|
||||||
|
return result.meta.changes || 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== Service Management =====
|
||||||
|
|
||||||
|
async createService(request: CreateServiceRequest): Promise<{
|
||||||
|
service: Service;
|
||||||
|
offers: Offer[];
|
||||||
}> {
|
}> {
|
||||||
|
const serviceId = crypto.randomUUID();
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
|
|
||||||
// Build WHERE clause for startsWith filter
|
// Parse FQN to extract components
|
||||||
const whereClause = startsWith
|
const parsed = parseServiceFqn(request.serviceFqn);
|
||||||
? 'o.expires_at > ? AND ot.topic LIKE ?'
|
if (!parsed) {
|
||||||
: 'o.expires_at > ?';
|
throw new Error(`Invalid service FQN: ${request.serviceFqn}`);
|
||||||
|
}
|
||||||
|
if (!parsed.username) {
|
||||||
|
throw new Error(`Service FQN must include username: ${request.serviceFqn}`);
|
||||||
|
}
|
||||||
|
|
||||||
const startsWithPattern = startsWith ? `${startsWith}%` : null;
|
const { serviceName, version, username } = parsed;
|
||||||
|
|
||||||
// Get total count of topics with active offers
|
// Delete existing service with same (service_name, version, username) and its related offers (upsert behavior)
|
||||||
const countQuery = `
|
// First get the existing service
|
||||||
SELECT COUNT(DISTINCT ot.topic) as count
|
const existingService = await this.db.prepare(`
|
||||||
FROM offer_topics ot
|
SELECT id FROM services
|
||||||
INNER JOIN offers o ON ot.offer_id = o.id
|
WHERE service_name = ? AND version = ? AND username = ?
|
||||||
WHERE ${whereClause}
|
`).bind(serviceName, version, username).first();
|
||||||
`;
|
|
||||||
|
|
||||||
const countStmt = this.db.prepare(countQuery);
|
if (existingService) {
|
||||||
const countResult = startsWith
|
// Delete related offers first (no FK cascade from offers to services)
|
||||||
? await countStmt.bind(now, startsWithPattern).first()
|
await this.db.prepare(`
|
||||||
: await countStmt.bind(now).first();
|
DELETE FROM offers WHERE service_id = ?
|
||||||
|
`).bind(existingService.id).run();
|
||||||
|
|
||||||
const total = (countResult as any)?.count || 0;
|
// Delete the service
|
||||||
|
await this.db.prepare(`
|
||||||
|
DELETE FROM services WHERE id = ?
|
||||||
|
`).bind(existingService.id).run();
|
||||||
|
}
|
||||||
|
|
||||||
// Get topics with peer counts (paginated)
|
// Insert new service with extracted fields
|
||||||
const topicsQuery = `
|
await this.db.prepare(`
|
||||||
SELECT
|
INSERT INTO services (id, service_fqn, service_name, version, username, created_at, expires_at)
|
||||||
ot.topic,
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||||
COUNT(DISTINCT o.peer_id) as active_peers
|
`).bind(
|
||||||
FROM offer_topics ot
|
serviceId,
|
||||||
INNER JOIN offers o ON ot.offer_id = o.id
|
request.serviceFqn,
|
||||||
WHERE ${whereClause}
|
serviceName,
|
||||||
GROUP BY ot.topic
|
version,
|
||||||
ORDER BY active_peers DESC, ot.topic ASC
|
username,
|
||||||
LIMIT ? OFFSET ?
|
now,
|
||||||
`;
|
request.expiresAt
|
||||||
|
).run();
|
||||||
|
|
||||||
const topicsStmt = this.db.prepare(topicsQuery);
|
// Create offers with serviceId
|
||||||
const topicsResult = startsWith
|
const offerRequests = request.offers.map(offer => ({
|
||||||
? await topicsStmt.bind(now, startsWithPattern, limit, offset).all()
|
...offer,
|
||||||
: await topicsStmt.bind(now, limit, offset).all();
|
serviceId,
|
||||||
|
|
||||||
const topics = (topicsResult.results || []).map((row: any) => ({
|
|
||||||
topic: row.topic,
|
|
||||||
activePeers: row.active_peers,
|
|
||||||
}));
|
}));
|
||||||
|
const offers = await this.createOffers(offerRequests);
|
||||||
|
|
||||||
return { topics, total };
|
// Touch username to extend expiry (inline logic)
|
||||||
|
const expiresAt = now + YEAR_IN_MS;
|
||||||
|
await this.db.prepare(`
|
||||||
|
UPDATE usernames
|
||||||
|
SET last_used = ?, expires_at = ?
|
||||||
|
WHERE username = ? AND expires_at > ?
|
||||||
|
`).bind(now, expiresAt, username, now).run();
|
||||||
|
|
||||||
|
return {
|
||||||
|
service: {
|
||||||
|
id: serviceId,
|
||||||
|
serviceFqn: request.serviceFqn,
|
||||||
|
serviceName,
|
||||||
|
version,
|
||||||
|
username,
|
||||||
|
createdAt: now,
|
||||||
|
expiresAt: request.expiresAt,
|
||||||
|
},
|
||||||
|
offers,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async getOffersForService(serviceId: string): Promise<Offer[]> {
|
||||||
|
const result = await this.db.prepare(`
|
||||||
|
SELECT * FROM offers
|
||||||
|
WHERE service_id = ? AND expires_at > ?
|
||||||
|
ORDER BY created_at ASC
|
||||||
|
`).bind(serviceId, Date.now()).all();
|
||||||
|
|
||||||
|
if (!result.results) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.results.map(row => this.rowToOffer(row as any));
|
||||||
|
}
|
||||||
|
|
||||||
|
async getServiceById(serviceId: string): Promise<Service | null> {
|
||||||
|
const result = await this.db.prepare(`
|
||||||
|
SELECT * FROM services
|
||||||
|
WHERE id = ? AND expires_at > ?
|
||||||
|
`).bind(serviceId, Date.now()).first();
|
||||||
|
|
||||||
|
if (!result) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.rowToService(result as any);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getServiceByFqn(serviceFqn: string): Promise<Service | null> {
|
||||||
|
const result = await this.db.prepare(`
|
||||||
|
SELECT * FROM services
|
||||||
|
WHERE service_fqn = ? AND expires_at > ?
|
||||||
|
`).bind(serviceFqn, Date.now()).first();
|
||||||
|
|
||||||
|
if (!result) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.rowToService(result as any);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
async discoverServices(
|
||||||
|
serviceName: string,
|
||||||
|
version: string,
|
||||||
|
limit: number,
|
||||||
|
offset: number
|
||||||
|
): Promise<Service[]> {
|
||||||
|
// Query for unique services with available offers
|
||||||
|
// We join with offers and filter for available ones (answerer_username IS NULL)
|
||||||
|
const result = await this.db.prepare(`
|
||||||
|
SELECT DISTINCT s.* FROM services s
|
||||||
|
INNER JOIN offers o ON o.service_id = s.id
|
||||||
|
WHERE s.service_name = ?
|
||||||
|
AND s.version = ?
|
||||||
|
AND s.expires_at > ?
|
||||||
|
AND o.answerer_username IS NULL
|
||||||
|
AND o.expires_at > ?
|
||||||
|
ORDER BY s.created_at DESC
|
||||||
|
LIMIT ? OFFSET ?
|
||||||
|
`).bind(serviceName, version, Date.now(), Date.now(), limit, offset).all();
|
||||||
|
|
||||||
|
if (!result.results) {
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
|
||||||
|
return result.results.map(row => this.rowToService(row as any));
|
||||||
|
}
|
||||||
|
|
||||||
|
async getRandomService(serviceName: string, version: string): Promise<Service | null> {
|
||||||
|
// Get a random service with an available offer
|
||||||
|
const result = await this.db.prepare(`
|
||||||
|
SELECT s.* FROM services s
|
||||||
|
INNER JOIN offers o ON o.service_id = s.id
|
||||||
|
WHERE s.service_name = ?
|
||||||
|
AND s.version = ?
|
||||||
|
AND s.expires_at > ?
|
||||||
|
AND o.answerer_username IS NULL
|
||||||
|
AND o.expires_at > ?
|
||||||
|
ORDER BY RANDOM()
|
||||||
|
LIMIT 1
|
||||||
|
`).bind(serviceName, version, Date.now(), Date.now()).first();
|
||||||
|
|
||||||
|
if (!result) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.rowToService(result as any);
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteService(serviceId: string, username: string): Promise<boolean> {
|
||||||
|
const result = await this.db.prepare(`
|
||||||
|
DELETE FROM services
|
||||||
|
WHERE id = ? AND username = ?
|
||||||
|
`).bind(serviceId, username).run();
|
||||||
|
|
||||||
|
return (result.meta.changes || 0) > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteExpiredServices(now: number): Promise<number> {
|
||||||
|
const result = await this.db.prepare(`
|
||||||
|
DELETE FROM services WHERE expires_at < ?
|
||||||
|
`).bind(now).run();
|
||||||
|
|
||||||
|
return result.meta.changes || 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
async close(): Promise<void> {
|
async close(): Promise<void> {
|
||||||
@@ -366,29 +566,39 @@ export class D1Storage implements Storage {
|
|||||||
// Connections are managed by the Cloudflare Workers runtime
|
// Connections are managed by the Cloudflare Workers runtime
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ===== Helper Methods =====
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Helper method to convert database row to Offer object with topics
|
* Helper method to convert database row to Offer object
|
||||||
*/
|
*/
|
||||||
private async rowToOffer(row: any): Promise<Offer> {
|
private rowToOffer(row: any): Offer {
|
||||||
// Get topics for this offer
|
|
||||||
const topicResult = await this.db.prepare(`
|
|
||||||
SELECT topic FROM offer_topics WHERE offer_id = ?
|
|
||||||
`).bind(row.id).all();
|
|
||||||
|
|
||||||
const topics = topicResult.results?.map((t: any) => t.topic) || [];
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: row.id,
|
id: row.id,
|
||||||
peerId: row.peer_id,
|
username: row.username,
|
||||||
|
serviceId: row.service_id || undefined,
|
||||||
|
serviceFqn: row.service_fqn || undefined,
|
||||||
sdp: row.sdp,
|
sdp: row.sdp,
|
||||||
topics,
|
|
||||||
createdAt: row.created_at,
|
createdAt: row.created_at,
|
||||||
expiresAt: row.expires_at,
|
expiresAt: row.expires_at,
|
||||||
lastSeen: row.last_seen,
|
lastSeen: row.last_seen,
|
||||||
secret: row.secret || undefined,
|
answererUsername: row.answerer_username || undefined,
|
||||||
answererPeerId: row.answerer_peer_id || undefined,
|
|
||||||
answerSdp: row.answer_sdp || undefined,
|
answerSdp: row.answer_sdp || undefined,
|
||||||
answeredAt: row.answered_at || undefined,
|
answeredAt: row.answered_at || undefined,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper method to convert database row to Service object
|
||||||
|
*/
|
||||||
|
private rowToService(row: any): Service {
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
serviceFqn: row.service_fqn,
|
||||||
|
serviceName: row.service_name,
|
||||||
|
version: row.version,
|
||||||
|
username: row.username,
|
||||||
|
createdAt: row.created_at,
|
||||||
|
expiresAt: row.expires_at,
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,22 +1,17 @@
|
|||||||
/**
|
/**
|
||||||
* Generates a content-based offer ID using SHA-256 hash
|
* Generates a content-based offer ID using SHA-256 hash
|
||||||
* Creates deterministic IDs based on offer content (sdp, topics)
|
* Creates deterministic IDs based on offer SDP content
|
||||||
* PeerID is not included as it's inferred from authentication
|
* PeerID is not included as it's inferred from authentication
|
||||||
* Uses Web Crypto API for compatibility with both Node.js and Cloudflare Workers
|
* Uses Web Crypto API for compatibility with both Node.js and Cloudflare Workers
|
||||||
*
|
*
|
||||||
* @param sdp - The WebRTC SDP offer
|
* @param sdp - The WebRTC SDP offer
|
||||||
* @param topics - Array of topic strings
|
* @returns SHA-256 hash of the SDP content
|
||||||
* @returns SHA-256 hash of the sanitized offer content
|
|
||||||
*/
|
*/
|
||||||
export async function generateOfferHash(
|
export async function generateOfferHash(sdp: string): Promise<string> {
|
||||||
sdp: string,
|
|
||||||
topics: string[]
|
|
||||||
): Promise<string> {
|
|
||||||
// Sanitize and normalize the offer content
|
// Sanitize and normalize the offer content
|
||||||
// Only include core offer content (not peerId - that's inferred from auth)
|
// Only include core offer content (not peerId - that's inferred from auth)
|
||||||
const sanitizedOffer = {
|
const sanitizedOffer = {
|
||||||
sdp,
|
sdp
|
||||||
topics: [...topics].sort(), // Sort topics for consistency
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Create non-prettified JSON string
|
// Create non-prettified JSON string
|
||||||
|
|||||||
@@ -1,9 +1,22 @@
|
|||||||
import Database from 'better-sqlite3';
|
import Database from 'better-sqlite3';
|
||||||
import { Storage, Offer, IceCandidate, CreateOfferRequest, TopicInfo } from './types.ts';
|
import { randomUUID } from 'node:crypto';
|
||||||
|
import {
|
||||||
|
Storage,
|
||||||
|
Offer,
|
||||||
|
IceCandidate,
|
||||||
|
CreateOfferRequest,
|
||||||
|
Username,
|
||||||
|
ClaimUsernameRequest,
|
||||||
|
Service,
|
||||||
|
CreateServiceRequest,
|
||||||
|
} from './types.ts';
|
||||||
import { generateOfferHash } from './hash-id.ts';
|
import { generateOfferHash } from './hash-id.ts';
|
||||||
|
import { parseServiceFqn } from '../crypto.ts';
|
||||||
|
|
||||||
|
const YEAR_IN_MS = 365 * 24 * 60 * 60 * 1000; // 365 days
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* SQLite storage adapter for topic-based offer management
|
* SQLite storage adapter for rondevu DNS-like system
|
||||||
* Supports both file-based and in-memory databases
|
* Supports both file-based and in-memory databases
|
||||||
*/
|
*/
|
||||||
export class SQLiteStorage implements Storage {
|
export class SQLiteStorage implements Storage {
|
||||||
@@ -19,57 +32,85 @@ export class SQLiteStorage implements Storage {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Initializes database schema with new topic-based structure
|
* Initializes database schema with username and service-based structure
|
||||||
*/
|
*/
|
||||||
private initializeDatabase(): void {
|
private initializeDatabase(): void {
|
||||||
this.db.exec(`
|
this.db.exec(`
|
||||||
|
-- WebRTC signaling offers
|
||||||
CREATE TABLE IF NOT EXISTS offers (
|
CREATE TABLE IF NOT EXISTS offers (
|
||||||
id TEXT PRIMARY KEY,
|
id TEXT PRIMARY KEY,
|
||||||
peer_id TEXT NOT NULL,
|
username TEXT NOT NULL,
|
||||||
|
service_id TEXT,
|
||||||
sdp TEXT NOT NULL,
|
sdp TEXT NOT NULL,
|
||||||
created_at INTEGER NOT NULL,
|
created_at INTEGER NOT NULL,
|
||||||
expires_at INTEGER NOT NULL,
|
expires_at INTEGER NOT NULL,
|
||||||
last_seen INTEGER NOT NULL,
|
last_seen INTEGER NOT NULL,
|
||||||
secret TEXT,
|
answerer_username TEXT,
|
||||||
answerer_peer_id TEXT,
|
|
||||||
answer_sdp TEXT,
|
answer_sdp TEXT,
|
||||||
answered_at INTEGER
|
answered_at INTEGER,
|
||||||
|
FOREIGN KEY (service_id) REFERENCES services(id) ON DELETE CASCADE
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_offers_peer ON offers(peer_id);
|
CREATE INDEX IF NOT EXISTS idx_offers_username ON offers(username);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_offers_service ON offers(service_id);
|
||||||
CREATE INDEX IF NOT EXISTS idx_offers_expires ON offers(expires_at);
|
CREATE INDEX IF NOT EXISTS idx_offers_expires ON offers(expires_at);
|
||||||
CREATE INDEX IF NOT EXISTS idx_offers_last_seen ON offers(last_seen);
|
CREATE INDEX IF NOT EXISTS idx_offers_last_seen ON offers(last_seen);
|
||||||
CREATE INDEX IF NOT EXISTS idx_offers_answerer ON offers(answerer_peer_id);
|
CREATE INDEX IF NOT EXISTS idx_offers_answerer ON offers(answerer_username);
|
||||||
|
|
||||||
CREATE TABLE IF NOT EXISTS offer_topics (
|
|
||||||
offer_id TEXT NOT NULL,
|
|
||||||
topic TEXT NOT NULL,
|
|
||||||
PRIMARY KEY (offer_id, topic),
|
|
||||||
FOREIGN KEY (offer_id) REFERENCES offers(id) ON DELETE CASCADE
|
|
||||||
);
|
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_topics_topic ON offer_topics(topic);
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_topics_offer ON offer_topics(offer_id);
|
|
||||||
|
|
||||||
|
-- ICE candidates table
|
||||||
CREATE TABLE IF NOT EXISTS ice_candidates (
|
CREATE TABLE IF NOT EXISTS ice_candidates (
|
||||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||||
offer_id TEXT NOT NULL,
|
offer_id TEXT NOT NULL,
|
||||||
peer_id TEXT NOT NULL,
|
username TEXT NOT NULL,
|
||||||
role TEXT NOT NULL CHECK(role IN ('offerer', 'answerer')),
|
role TEXT NOT NULL CHECK(role IN ('offerer', 'answerer')),
|
||||||
candidate TEXT NOT NULL, -- JSON: RTCIceCandidateInit object
|
candidate TEXT NOT NULL,
|
||||||
created_at INTEGER NOT NULL,
|
created_at INTEGER NOT NULL,
|
||||||
FOREIGN KEY (offer_id) REFERENCES offers(id) ON DELETE CASCADE
|
FOREIGN KEY (offer_id) REFERENCES offers(id) ON DELETE CASCADE
|
||||||
);
|
);
|
||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_ice_offer ON ice_candidates(offer_id);
|
CREATE INDEX IF NOT EXISTS idx_ice_offer ON ice_candidates(offer_id);
|
||||||
CREATE INDEX IF NOT EXISTS idx_ice_peer ON ice_candidates(peer_id);
|
CREATE INDEX IF NOT EXISTS idx_ice_username ON ice_candidates(username);
|
||||||
CREATE INDEX IF NOT EXISTS idx_ice_created ON ice_candidates(created_at);
|
CREATE INDEX IF NOT EXISTS idx_ice_created ON ice_candidates(created_at);
|
||||||
|
|
||||||
|
-- Usernames table
|
||||||
|
CREATE TABLE IF NOT EXISTS usernames (
|
||||||
|
username TEXT PRIMARY KEY,
|
||||||
|
public_key TEXT NOT NULL UNIQUE,
|
||||||
|
claimed_at INTEGER NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL,
|
||||||
|
last_used INTEGER NOT NULL,
|
||||||
|
metadata TEXT,
|
||||||
|
CHECK(length(username) >= 3 AND length(username) <= 32)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_usernames_expires ON usernames(expires_at);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_usernames_public_key ON usernames(public_key);
|
||||||
|
|
||||||
|
-- Services table (new schema with extracted fields for discovery)
|
||||||
|
CREATE TABLE IF NOT EXISTS services (
|
||||||
|
id TEXT PRIMARY KEY,
|
||||||
|
service_fqn TEXT NOT NULL,
|
||||||
|
service_name TEXT NOT NULL,
|
||||||
|
version TEXT NOT NULL,
|
||||||
|
username TEXT NOT NULL,
|
||||||
|
created_at INTEGER NOT NULL,
|
||||||
|
expires_at INTEGER NOT NULL,
|
||||||
|
FOREIGN KEY (username) REFERENCES usernames(username) ON DELETE CASCADE,
|
||||||
|
UNIQUE(service_fqn)
|
||||||
|
);
|
||||||
|
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_services_fqn ON services(service_fqn);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_services_discovery ON services(service_name, version);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_services_username ON services(username);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_services_expires ON services(expires_at);
|
||||||
`);
|
`);
|
||||||
|
|
||||||
// Enable foreign keys
|
// Enable foreign keys
|
||||||
this.db.pragma('foreign_keys = ON');
|
this.db.pragma('foreign_keys = ON');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ===== Offer Management =====
|
||||||
|
|
||||||
async createOffers(offers: CreateOfferRequest[]): Promise<Offer[]> {
|
async createOffers(offers: CreateOfferRequest[]): Promise<Offer[]> {
|
||||||
const created: Offer[] = [];
|
const created: Offer[] = [];
|
||||||
|
|
||||||
@@ -77,50 +118,40 @@ export class SQLiteStorage implements Storage {
|
|||||||
const offersWithIds = await Promise.all(
|
const offersWithIds = await Promise.all(
|
||||||
offers.map(async (offer) => ({
|
offers.map(async (offer) => ({
|
||||||
...offer,
|
...offer,
|
||||||
id: offer.id || await generateOfferHash(offer.sdp, offer.topics),
|
id: offer.id || await generateOfferHash(offer.sdp),
|
||||||
}))
|
}))
|
||||||
);
|
);
|
||||||
|
|
||||||
// Use transaction for atomic creation
|
// Use transaction for atomic creation
|
||||||
const transaction = this.db.transaction((offersWithIds: (CreateOfferRequest & { id: string })[]) => {
|
const transaction = this.db.transaction((offersWithIds: (CreateOfferRequest & { id: string })[]) => {
|
||||||
const offerStmt = this.db.prepare(`
|
const offerStmt = this.db.prepare(`
|
||||||
INSERT INTO offers (id, peer_id, sdp, created_at, expires_at, last_seen, secret)
|
INSERT INTO offers (id, username, service_id, sdp, created_at, expires_at, last_seen)
|
||||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||||
`);
|
`);
|
||||||
|
|
||||||
const topicStmt = this.db.prepare(`
|
|
||||||
INSERT INTO offer_topics (offer_id, topic)
|
|
||||||
VALUES (?, ?)
|
|
||||||
`);
|
|
||||||
|
|
||||||
for (const offer of offersWithIds) {
|
for (const offer of offersWithIds) {
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
|
|
||||||
// Insert offer
|
// Insert offer
|
||||||
offerStmt.run(
|
offerStmt.run(
|
||||||
offer.id,
|
offer.id,
|
||||||
offer.peerId,
|
offer.username,
|
||||||
|
offer.serviceId || null,
|
||||||
offer.sdp,
|
offer.sdp,
|
||||||
now,
|
now,
|
||||||
offer.expiresAt,
|
offer.expiresAt,
|
||||||
now,
|
now
|
||||||
offer.secret || null
|
|
||||||
);
|
);
|
||||||
|
|
||||||
// Insert topics
|
|
||||||
for (const topic of offer.topics) {
|
|
||||||
topicStmt.run(offer.id, topic);
|
|
||||||
}
|
|
||||||
|
|
||||||
created.push({
|
created.push({
|
||||||
id: offer.id,
|
id: offer.id,
|
||||||
peerId: offer.peerId,
|
username: offer.username,
|
||||||
|
serviceId: offer.serviceId || undefined,
|
||||||
|
serviceFqn: offer.serviceFqn,
|
||||||
sdp: offer.sdp,
|
sdp: offer.sdp,
|
||||||
topics: offer.topics,
|
|
||||||
createdAt: now,
|
createdAt: now,
|
||||||
expiresAt: offer.expiresAt,
|
expiresAt: offer.expiresAt,
|
||||||
lastSeen: now,
|
lastSeen: now,
|
||||||
secret: offer.secret,
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -129,39 +160,15 @@ export class SQLiteStorage implements Storage {
|
|||||||
return created;
|
return created;
|
||||||
}
|
}
|
||||||
|
|
||||||
async getOffersByTopic(topic: string, excludePeerIds?: string[]): Promise<Offer[]> {
|
async getOffersByUsername(username: string): Promise<Offer[]> {
|
||||||
let query = `
|
|
||||||
SELECT DISTINCT o.*
|
|
||||||
FROM offers o
|
|
||||||
INNER JOIN offer_topics ot ON o.id = ot.offer_id
|
|
||||||
WHERE ot.topic = ? AND o.expires_at > ?
|
|
||||||
`;
|
|
||||||
|
|
||||||
const params: any[] = [topic, Date.now()];
|
|
||||||
|
|
||||||
if (excludePeerIds && excludePeerIds.length > 0) {
|
|
||||||
const placeholders = excludePeerIds.map(() => '?').join(',');
|
|
||||||
query += ` AND o.peer_id NOT IN (${placeholders})`;
|
|
||||||
params.push(...excludePeerIds);
|
|
||||||
}
|
|
||||||
|
|
||||||
query += ' ORDER BY o.last_seen DESC';
|
|
||||||
|
|
||||||
const stmt = this.db.prepare(query);
|
|
||||||
const rows = stmt.all(...params) as any[];
|
|
||||||
|
|
||||||
return Promise.all(rows.map(row => this.rowToOffer(row)));
|
|
||||||
}
|
|
||||||
|
|
||||||
async getOffersByPeerId(peerId: string): Promise<Offer[]> {
|
|
||||||
const stmt = this.db.prepare(`
|
const stmt = this.db.prepare(`
|
||||||
SELECT * FROM offers
|
SELECT * FROM offers
|
||||||
WHERE peer_id = ? AND expires_at > ?
|
WHERE username = ? AND expires_at > ?
|
||||||
ORDER BY last_seen DESC
|
ORDER BY last_seen DESC
|
||||||
`);
|
`);
|
||||||
|
|
||||||
const rows = stmt.all(peerId, Date.now()) as any[];
|
const rows = stmt.all(username, Date.now()) as any[];
|
||||||
return Promise.all(rows.map(row => this.rowToOffer(row)));
|
return rows.map(row => this.rowToOffer(row));
|
||||||
}
|
}
|
||||||
|
|
||||||
async getOfferById(offerId: string): Promise<Offer | null> {
|
async getOfferById(offerId: string): Promise<Offer | null> {
|
||||||
@@ -179,13 +186,13 @@ export class SQLiteStorage implements Storage {
|
|||||||
return this.rowToOffer(row);
|
return this.rowToOffer(row);
|
||||||
}
|
}
|
||||||
|
|
||||||
async deleteOffer(offerId: string, ownerPeerId: string): Promise<boolean> {
|
async deleteOffer(offerId: string, ownerUsername: string): Promise<boolean> {
|
||||||
const stmt = this.db.prepare(`
|
const stmt = this.db.prepare(`
|
||||||
DELETE FROM offers
|
DELETE FROM offers
|
||||||
WHERE id = ? AND peer_id = ?
|
WHERE id = ? AND username = ?
|
||||||
`);
|
`);
|
||||||
|
|
||||||
const result = stmt.run(offerId, ownerPeerId);
|
const result = stmt.run(offerId, ownerUsername);
|
||||||
return result.changes > 0;
|
return result.changes > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -197,9 +204,8 @@ export class SQLiteStorage implements Storage {
|
|||||||
|
|
||||||
async answerOffer(
|
async answerOffer(
|
||||||
offerId: string,
|
offerId: string,
|
||||||
answererPeerId: string,
|
answererUsername: string,
|
||||||
answerSdp: string,
|
answerSdp: string
|
||||||
secret?: string
|
|
||||||
): Promise<{ success: boolean; error?: string }> {
|
): Promise<{ success: boolean; error?: string }> {
|
||||||
// Check if offer exists and is not expired
|
// Check if offer exists and is not expired
|
||||||
const offer = await this.getOfferById(offerId);
|
const offer = await this.getOfferById(offerId);
|
||||||
@@ -211,16 +217,8 @@ export class SQLiteStorage implements Storage {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
// Verify secret if offer is protected
|
|
||||||
if (offer.secret && offer.secret !== secret) {
|
|
||||||
return {
|
|
||||||
success: false,
|
|
||||||
error: 'Invalid or missing secret'
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
// Check if offer already has an answerer
|
// Check if offer already has an answerer
|
||||||
if (offer.answererPeerId) {
|
if (offer.answererUsername) {
|
||||||
return {
|
return {
|
||||||
success: false,
|
success: false,
|
||||||
error: 'Offer already answered'
|
error: 'Offer already answered'
|
||||||
@@ -230,11 +228,11 @@ export class SQLiteStorage implements Storage {
|
|||||||
// Update offer with answer
|
// Update offer with answer
|
||||||
const stmt = this.db.prepare(`
|
const stmt = this.db.prepare(`
|
||||||
UPDATE offers
|
UPDATE offers
|
||||||
SET answerer_peer_id = ?, answer_sdp = ?, answered_at = ?
|
SET answerer_username = ?, answer_sdp = ?, answered_at = ?
|
||||||
WHERE id = ? AND answerer_peer_id IS NULL
|
WHERE id = ? AND answerer_username IS NULL
|
||||||
`);
|
`);
|
||||||
|
|
||||||
const result = stmt.run(answererPeerId, answerSdp, Date.now(), offerId);
|
const result = stmt.run(answererUsername, answerSdp, Date.now(), offerId);
|
||||||
|
|
||||||
if (result.changes === 0) {
|
if (result.changes === 0) {
|
||||||
return {
|
return {
|
||||||
@@ -246,25 +244,27 @@ export class SQLiteStorage implements Storage {
|
|||||||
return { success: true };
|
return { success: true };
|
||||||
}
|
}
|
||||||
|
|
||||||
async getAnsweredOffers(offererPeerId: string): Promise<Offer[]> {
|
async getAnsweredOffers(offererUsername: string): Promise<Offer[]> {
|
||||||
const stmt = this.db.prepare(`
|
const stmt = this.db.prepare(`
|
||||||
SELECT * FROM offers
|
SELECT * FROM offers
|
||||||
WHERE peer_id = ? AND answerer_peer_id IS NOT NULL AND expires_at > ?
|
WHERE username = ? AND answerer_username IS NOT NULL AND expires_at > ?
|
||||||
ORDER BY answered_at DESC
|
ORDER BY answered_at DESC
|
||||||
`);
|
`);
|
||||||
|
|
||||||
const rows = stmt.all(offererPeerId, Date.now()) as any[];
|
const rows = stmt.all(offererUsername, Date.now()) as any[];
|
||||||
return Promise.all(rows.map(row => this.rowToOffer(row)));
|
return rows.map(row => this.rowToOffer(row));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ===== ICE Candidate Management =====
|
||||||
|
|
||||||
async addIceCandidates(
|
async addIceCandidates(
|
||||||
offerId: string,
|
offerId: string,
|
||||||
peerId: string,
|
username: string,
|
||||||
role: 'offerer' | 'answerer',
|
role: 'offerer' | 'answerer',
|
||||||
candidates: any[]
|
candidates: any[]
|
||||||
): Promise<number> {
|
): Promise<number> {
|
||||||
const stmt = this.db.prepare(`
|
const stmt = this.db.prepare(`
|
||||||
INSERT INTO ice_candidates (offer_id, peer_id, role, candidate, created_at)
|
INSERT INTO ice_candidates (offer_id, username, role, candidate, created_at)
|
||||||
VALUES (?, ?, ?, ?, ?)
|
VALUES (?, ?, ?, ?, ?)
|
||||||
`);
|
`);
|
||||||
|
|
||||||
@@ -273,10 +273,10 @@ export class SQLiteStorage implements Storage {
|
|||||||
for (let i = 0; i < candidates.length; i++) {
|
for (let i = 0; i < candidates.length; i++) {
|
||||||
stmt.run(
|
stmt.run(
|
||||||
offerId,
|
offerId,
|
||||||
peerId,
|
username,
|
||||||
role,
|
role,
|
||||||
JSON.stringify(candidates[i]), // Store full object as JSON
|
JSON.stringify(candidates[i]),
|
||||||
baseTimestamp + i // Ensure unique timestamps to avoid "since" filtering issues
|
baseTimestamp + i
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@@ -310,94 +310,321 @@ export class SQLiteStorage implements Storage {
|
|||||||
return rows.map(row => ({
|
return rows.map(row => ({
|
||||||
id: row.id,
|
id: row.id,
|
||||||
offerId: row.offer_id,
|
offerId: row.offer_id,
|
||||||
peerId: row.peer_id,
|
username: row.username,
|
||||||
role: row.role,
|
role: row.role,
|
||||||
candidate: JSON.parse(row.candidate), // Parse JSON back to object
|
candidate: JSON.parse(row.candidate),
|
||||||
createdAt: row.created_at,
|
createdAt: row.created_at,
|
||||||
}));
|
}));
|
||||||
}
|
}
|
||||||
|
|
||||||
async getTopics(limit: number, offset: number, startsWith?: string): Promise<{
|
// ===== Username Management =====
|
||||||
topics: TopicInfo[];
|
|
||||||
total: number;
|
async claimUsername(request: ClaimUsernameRequest): Promise<Username> {
|
||||||
|
const now = Date.now();
|
||||||
|
const expiresAt = now + YEAR_IN_MS;
|
||||||
|
|
||||||
|
// Try to insert or update
|
||||||
|
const stmt = this.db.prepare(`
|
||||||
|
INSERT INTO usernames (username, public_key, claimed_at, expires_at, last_used, metadata)
|
||||||
|
VALUES (?, ?, ?, ?, ?, NULL)
|
||||||
|
ON CONFLICT(username) DO UPDATE SET
|
||||||
|
expires_at = ?,
|
||||||
|
last_used = ?
|
||||||
|
WHERE public_key = ?
|
||||||
|
`);
|
||||||
|
|
||||||
|
const result = stmt.run(
|
||||||
|
request.username,
|
||||||
|
request.publicKey,
|
||||||
|
now,
|
||||||
|
expiresAt,
|
||||||
|
now,
|
||||||
|
expiresAt,
|
||||||
|
now,
|
||||||
|
request.publicKey
|
||||||
|
);
|
||||||
|
|
||||||
|
if (result.changes === 0) {
|
||||||
|
throw new Error('Username already claimed by different public key');
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
username: request.username,
|
||||||
|
publicKey: request.publicKey,
|
||||||
|
claimedAt: now,
|
||||||
|
expiresAt,
|
||||||
|
lastUsed: now,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async getUsername(username: string): Promise<Username | null> {
|
||||||
|
const stmt = this.db.prepare(`
|
||||||
|
SELECT * FROM usernames
|
||||||
|
WHERE username = ? AND expires_at > ?
|
||||||
|
`);
|
||||||
|
|
||||||
|
const row = stmt.get(username, Date.now()) as any;
|
||||||
|
|
||||||
|
if (!row) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
username: row.username,
|
||||||
|
publicKey: row.public_key,
|
||||||
|
claimedAt: row.claimed_at,
|
||||||
|
expiresAt: row.expires_at,
|
||||||
|
lastUsed: row.last_used,
|
||||||
|
metadata: row.metadata || undefined,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async touchUsername(username: string): Promise<boolean> {
|
||||||
|
const now = Date.now();
|
||||||
|
const expiresAt = now + YEAR_IN_MS;
|
||||||
|
|
||||||
|
const stmt = this.db.prepare(`
|
||||||
|
UPDATE usernames
|
||||||
|
SET last_used = ?, expires_at = ?
|
||||||
|
WHERE username = ? AND expires_at > ?
|
||||||
|
`);
|
||||||
|
|
||||||
|
const result = stmt.run(now, expiresAt, username, now);
|
||||||
|
return result.changes > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteExpiredUsernames(now: number): Promise<number> {
|
||||||
|
const stmt = this.db.prepare('DELETE FROM usernames WHERE expires_at < ?');
|
||||||
|
const result = stmt.run(now);
|
||||||
|
return result.changes;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ===== Service Management =====
|
||||||
|
|
||||||
|
async createService(request: CreateServiceRequest): Promise<{
|
||||||
|
service: Service;
|
||||||
|
offers: Offer[];
|
||||||
}> {
|
}> {
|
||||||
|
const serviceId = randomUUID();
|
||||||
const now = Date.now();
|
const now = Date.now();
|
||||||
|
|
||||||
// Build WHERE clause for startsWith filter
|
// Parse FQN to extract components
|
||||||
const whereClause = startsWith
|
const parsed = parseServiceFqn(request.serviceFqn);
|
||||||
? 'o.expires_at > ? AND ot.topic LIKE ?'
|
if (!parsed) {
|
||||||
: 'o.expires_at > ?';
|
throw new Error(`Invalid service FQN: ${request.serviceFqn}`);
|
||||||
|
}
|
||||||
|
if (!parsed.username) {
|
||||||
|
throw new Error(`Service FQN must include username: ${request.serviceFqn}`);
|
||||||
|
}
|
||||||
|
|
||||||
const startsWithPattern = startsWith ? `${startsWith}%` : null;
|
const { serviceName, version, username } = parsed;
|
||||||
|
|
||||||
// Get total count of topics with active offers
|
const transaction = this.db.transaction(() => {
|
||||||
const countQuery = `
|
// Delete existing service with same (service_name, version, username) and its related offers (upsert behavior)
|
||||||
SELECT COUNT(DISTINCT ot.topic) as count
|
const existingService = this.db.prepare(`
|
||||||
FROM offer_topics ot
|
SELECT id FROM services
|
||||||
INNER JOIN offers o ON ot.offer_id = o.id
|
WHERE service_name = ? AND version = ? AND username = ?
|
||||||
WHERE ${whereClause}
|
`).get(serviceName, version, username) as any;
|
||||||
`;
|
|
||||||
|
|
||||||
const countStmt = this.db.prepare(countQuery);
|
if (existingService) {
|
||||||
const countParams = startsWith ? [now, startsWithPattern] : [now];
|
// Delete related offers first (no FK cascade from offers to services)
|
||||||
const countRow = countStmt.get(...countParams) as any;
|
this.db.prepare(`
|
||||||
const total = countRow.count;
|
DELETE FROM offers WHERE service_id = ?
|
||||||
|
`).run(existingService.id);
|
||||||
|
|
||||||
// Get topics with peer counts (paginated)
|
// Delete the service
|
||||||
const topicsQuery = `
|
this.db.prepare(`
|
||||||
SELECT
|
DELETE FROM services WHERE id = ?
|
||||||
ot.topic,
|
`).run(existingService.id);
|
||||||
COUNT(DISTINCT o.peer_id) as active_peers
|
}
|
||||||
FROM offer_topics ot
|
|
||||||
INNER JOIN offers o ON ot.offer_id = o.id
|
|
||||||
WHERE ${whereClause}
|
|
||||||
GROUP BY ot.topic
|
|
||||||
ORDER BY active_peers DESC, ot.topic ASC
|
|
||||||
LIMIT ? OFFSET ?
|
|
||||||
`;
|
|
||||||
|
|
||||||
const topicsStmt = this.db.prepare(topicsQuery);
|
// Insert new service with extracted fields
|
||||||
const topicsParams = startsWith
|
this.db.prepare(`
|
||||||
? [now, startsWithPattern, limit, offset]
|
INSERT INTO services (id, service_fqn, service_name, version, username, created_at, expires_at)
|
||||||
: [now, limit, offset];
|
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||||
const rows = topicsStmt.all(...topicsParams) as any[];
|
`).run(
|
||||||
|
serviceId,
|
||||||
|
request.serviceFqn,
|
||||||
|
serviceName,
|
||||||
|
version,
|
||||||
|
username,
|
||||||
|
now,
|
||||||
|
request.expiresAt
|
||||||
|
);
|
||||||
|
|
||||||
const topics = rows.map(row => ({
|
// Touch username to extend expiry (inline logic)
|
||||||
topic: row.topic,
|
const expiresAt = now + YEAR_IN_MS;
|
||||||
activePeers: row.active_peers,
|
this.db.prepare(`
|
||||||
|
UPDATE usernames
|
||||||
|
SET last_used = ?, expires_at = ?
|
||||||
|
WHERE username = ? AND expires_at > ?
|
||||||
|
`).run(now, expiresAt, username, now);
|
||||||
|
});
|
||||||
|
|
||||||
|
transaction();
|
||||||
|
|
||||||
|
// Create offers with serviceId (after transaction)
|
||||||
|
const offerRequests = request.offers.map(offer => ({
|
||||||
|
...offer,
|
||||||
|
serviceId,
|
||||||
}));
|
}));
|
||||||
|
const offers = await this.createOffers(offerRequests);
|
||||||
|
|
||||||
return { topics, total };
|
return {
|
||||||
|
service: {
|
||||||
|
id: serviceId,
|
||||||
|
serviceFqn: request.serviceFqn,
|
||||||
|
serviceName,
|
||||||
|
version,
|
||||||
|
username,
|
||||||
|
createdAt: now,
|
||||||
|
expiresAt: request.expiresAt,
|
||||||
|
},
|
||||||
|
offers,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async getOffersForService(serviceId: string): Promise<Offer[]> {
|
||||||
|
const stmt = this.db.prepare(`
|
||||||
|
SELECT * FROM offers
|
||||||
|
WHERE service_id = ? AND expires_at > ?
|
||||||
|
ORDER BY created_at ASC
|
||||||
|
`);
|
||||||
|
|
||||||
|
const rows = stmt.all(serviceId, Date.now()) as any[];
|
||||||
|
return rows.map(row => this.rowToOffer(row));
|
||||||
|
}
|
||||||
|
|
||||||
|
async getServiceById(serviceId: string): Promise<Service | null> {
|
||||||
|
const stmt = this.db.prepare(`
|
||||||
|
SELECT * FROM services
|
||||||
|
WHERE id = ? AND expires_at > ?
|
||||||
|
`);
|
||||||
|
|
||||||
|
const row = stmt.get(serviceId, Date.now()) as any;
|
||||||
|
|
||||||
|
if (!row) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.rowToService(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
async getServiceByFqn(serviceFqn: string): Promise<Service | null> {
|
||||||
|
const stmt = this.db.prepare(`
|
||||||
|
SELECT * FROM services
|
||||||
|
WHERE service_fqn = ? AND expires_at > ?
|
||||||
|
`);
|
||||||
|
|
||||||
|
const row = stmt.get(serviceFqn, Date.now()) as any;
|
||||||
|
|
||||||
|
if (!row) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.rowToService(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
async discoverServices(
|
||||||
|
serviceName: string,
|
||||||
|
version: string,
|
||||||
|
limit: number,
|
||||||
|
offset: number
|
||||||
|
): Promise<Service[]> {
|
||||||
|
// Query for unique services with available offers
|
||||||
|
// We join with offers and filter for available ones (answerer_username IS NULL)
|
||||||
|
const stmt = this.db.prepare(`
|
||||||
|
SELECT DISTINCT s.* FROM services s
|
||||||
|
INNER JOIN offers o ON o.service_id = s.id
|
||||||
|
WHERE s.service_name = ?
|
||||||
|
AND s.version = ?
|
||||||
|
AND s.expires_at > ?
|
||||||
|
AND o.answerer_username IS NULL
|
||||||
|
AND o.expires_at > ?
|
||||||
|
ORDER BY s.created_at DESC
|
||||||
|
LIMIT ? OFFSET ?
|
||||||
|
`);
|
||||||
|
|
||||||
|
const rows = stmt.all(serviceName, version, Date.now(), Date.now(), limit, offset) as any[];
|
||||||
|
return rows.map(row => this.rowToService(row));
|
||||||
|
}
|
||||||
|
|
||||||
|
async getRandomService(serviceName: string, version: string): Promise<Service | null> {
|
||||||
|
// Get a random service with an available offer
|
||||||
|
const stmt = this.db.prepare(`
|
||||||
|
SELECT s.* FROM services s
|
||||||
|
INNER JOIN offers o ON o.service_id = s.id
|
||||||
|
WHERE s.service_name = ?
|
||||||
|
AND s.version = ?
|
||||||
|
AND s.expires_at > ?
|
||||||
|
AND o.answerer_username IS NULL
|
||||||
|
AND o.expires_at > ?
|
||||||
|
ORDER BY RANDOM()
|
||||||
|
LIMIT 1
|
||||||
|
`);
|
||||||
|
|
||||||
|
const row = stmt.get(serviceName, version, Date.now(), Date.now()) as any;
|
||||||
|
|
||||||
|
if (!row) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return this.rowToService(row);
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteService(serviceId: string, username: string): Promise<boolean> {
|
||||||
|
const stmt = this.db.prepare(`
|
||||||
|
DELETE FROM services
|
||||||
|
WHERE id = ? AND username = ?
|
||||||
|
`);
|
||||||
|
|
||||||
|
const result = stmt.run(serviceId, username);
|
||||||
|
return result.changes > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
async deleteExpiredServices(now: number): Promise<number> {
|
||||||
|
const stmt = this.db.prepare('DELETE FROM services WHERE expires_at < ?');
|
||||||
|
const result = stmt.run(now);
|
||||||
|
return result.changes;
|
||||||
}
|
}
|
||||||
|
|
||||||
async close(): Promise<void> {
|
async close(): Promise<void> {
|
||||||
this.db.close();
|
this.db.close();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ===== Helper Methods =====
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Helper method to convert database row to Offer object with topics
|
* Helper method to convert database row to Offer object
|
||||||
*/
|
*/
|
||||||
private async rowToOffer(row: any): Promise<Offer> {
|
private rowToOffer(row: any): Offer {
|
||||||
// Get topics for this offer
|
|
||||||
const topicStmt = this.db.prepare(`
|
|
||||||
SELECT topic FROM offer_topics WHERE offer_id = ?
|
|
||||||
`);
|
|
||||||
|
|
||||||
const topicRows = topicStmt.all(row.id) as any[];
|
|
||||||
const topics = topicRows.map(t => t.topic);
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: row.id,
|
id: row.id,
|
||||||
peerId: row.peer_id,
|
username: row.username,
|
||||||
|
serviceId: row.service_id || undefined,
|
||||||
|
serviceFqn: row.service_fqn || undefined,
|
||||||
sdp: row.sdp,
|
sdp: row.sdp,
|
||||||
topics,
|
|
||||||
createdAt: row.created_at,
|
createdAt: row.created_at,
|
||||||
expiresAt: row.expires_at,
|
expiresAt: row.expires_at,
|
||||||
lastSeen: row.last_seen,
|
lastSeen: row.last_seen,
|
||||||
secret: row.secret || undefined,
|
answererUsername: row.answerer_username || undefined,
|
||||||
answererPeerId: row.answerer_peer_id || undefined,
|
|
||||||
answerSdp: row.answer_sdp || undefined,
|
answerSdp: row.answer_sdp || undefined,
|
||||||
answeredAt: row.answered_at || undefined,
|
answeredAt: row.answered_at || undefined,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Helper method to convert database row to Service object
|
||||||
|
*/
|
||||||
|
private rowToService(row: any): Service {
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
serviceFqn: row.service_fqn,
|
||||||
|
serviceName: row.service_name,
|
||||||
|
version: row.version,
|
||||||
|
username: row.username,
|
||||||
|
createdAt: row.created_at,
|
||||||
|
expiresAt: row.expires_at,
|
||||||
|
};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,16 +1,16 @@
|
|||||||
/**
|
/**
|
||||||
* Represents a WebRTC signaling offer with topic-based discovery
|
* Represents a WebRTC signaling offer
|
||||||
*/
|
*/
|
||||||
export interface Offer {
|
export interface Offer {
|
||||||
id: string;
|
id: string;
|
||||||
peerId: string;
|
username: string;
|
||||||
|
serviceId?: string; // Optional link to service (null for standalone offers)
|
||||||
|
serviceFqn?: string; // Denormalized service FQN for easier queries
|
||||||
sdp: string;
|
sdp: string;
|
||||||
topics: string[];
|
|
||||||
createdAt: number;
|
createdAt: number;
|
||||||
expiresAt: number;
|
expiresAt: number;
|
||||||
lastSeen: number;
|
lastSeen: number;
|
||||||
secret?: string;
|
answererUsername?: string;
|
||||||
answererPeerId?: string;
|
|
||||||
answerSdp?: string;
|
answerSdp?: string;
|
||||||
answeredAt?: number;
|
answeredAt?: number;
|
||||||
}
|
}
|
||||||
@@ -22,37 +22,76 @@ export interface Offer {
|
|||||||
export interface IceCandidate {
|
export interface IceCandidate {
|
||||||
id: number;
|
id: number;
|
||||||
offerId: string;
|
offerId: string;
|
||||||
peerId: string;
|
username: string;
|
||||||
role: 'offerer' | 'answerer';
|
role: 'offerer' | 'answerer';
|
||||||
candidate: any; // Full candidate object as JSON - don't enforce structure
|
candidate: any; // Full candidate object as JSON - don't enforce structure
|
||||||
createdAt: number;
|
createdAt: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Represents a topic with active peer count
|
|
||||||
*/
|
|
||||||
export interface TopicInfo {
|
|
||||||
topic: string;
|
|
||||||
activePeers: number;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Request to create a new offer
|
* Request to create a new offer
|
||||||
*/
|
*/
|
||||||
export interface CreateOfferRequest {
|
export interface CreateOfferRequest {
|
||||||
id?: string;
|
id?: string;
|
||||||
peerId: string;
|
username: string;
|
||||||
|
serviceId?: string; // Optional link to service
|
||||||
|
serviceFqn?: string; // Optional service FQN
|
||||||
sdp: string;
|
sdp: string;
|
||||||
topics: string[];
|
|
||||||
expiresAt: number;
|
expiresAt: number;
|
||||||
secret?: string;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Storage interface for offer management with topic-based discovery
|
* Represents a claimed username with cryptographic proof
|
||||||
* Implementations can use different backends (SQLite, D1, Memory, etc.)
|
*/
|
||||||
|
export interface Username {
|
||||||
|
username: string;
|
||||||
|
publicKey: string; // Base64-encoded Ed25519 public key
|
||||||
|
claimedAt: number;
|
||||||
|
expiresAt: number; // 365 days from claim/last use
|
||||||
|
lastUsed: number;
|
||||||
|
metadata?: string; // JSON optional user metadata
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Request to claim a username
|
||||||
|
*/
|
||||||
|
export interface ClaimUsernameRequest {
|
||||||
|
username: string;
|
||||||
|
publicKey: string;
|
||||||
|
signature: string;
|
||||||
|
message: string; // "claim:{username}:{timestamp}"
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents a published service (can have multiple offers)
|
||||||
|
* New format: service:version@username (e.g., chat:1.0.0@alice)
|
||||||
|
*/
|
||||||
|
export interface Service {
|
||||||
|
id: string; // UUID v4
|
||||||
|
serviceFqn: string; // Full FQN: chat:1.0.0@alice
|
||||||
|
serviceName: string; // Extracted: chat
|
||||||
|
version: string; // Extracted: 1.0.0
|
||||||
|
username: string; // Extracted: alice
|
||||||
|
createdAt: number;
|
||||||
|
expiresAt: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Request to create a single service
|
||||||
|
*/
|
||||||
|
export interface CreateServiceRequest {
|
||||||
|
serviceFqn: string; // Full FQN with username: chat:1.0.0@alice
|
||||||
|
expiresAt: number;
|
||||||
|
offers: CreateOfferRequest[]; // Multiple offers per service
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Storage interface for rondevu DNS-like system
|
||||||
|
* Implementations can use different backends (SQLite, D1, etc.)
|
||||||
*/
|
*/
|
||||||
export interface Storage {
|
export interface Storage {
|
||||||
|
// ===== Offer Management =====
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Creates one or more offers
|
* Creates one or more offers
|
||||||
* @param offers Array of offer creation requests
|
* @param offers Array of offer creation requests
|
||||||
@@ -61,19 +100,11 @@ export interface Storage {
|
|||||||
createOffers(offers: CreateOfferRequest[]): Promise<Offer[]>;
|
createOffers(offers: CreateOfferRequest[]): Promise<Offer[]>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieves offers by topic with optional peer ID exclusion
|
* Retrieves all offers from a specific user
|
||||||
* @param topic Topic to search for
|
* @param username Username identifier
|
||||||
* @param excludePeerIds Optional array of peer IDs to exclude
|
* @returns Array of offers from the user
|
||||||
* @returns Array of offers matching the topic
|
|
||||||
*/
|
*/
|
||||||
getOffersByTopic(topic: string, excludePeerIds?: string[]): Promise<Offer[]>;
|
getOffersByUsername(username: string): Promise<Offer[]>;
|
||||||
|
|
||||||
/**
|
|
||||||
* Retrieves all offers from a specific peer
|
|
||||||
* @param peerId Peer identifier
|
|
||||||
* @returns Array of offers from the peer
|
|
||||||
*/
|
|
||||||
getOffersByPeerId(peerId: string): Promise<Offer[]>;
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieves a specific offer by ID
|
* Retrieves a specific offer by ID
|
||||||
@@ -85,10 +116,10 @@ export interface Storage {
|
|||||||
/**
|
/**
|
||||||
* Deletes an offer (with ownership verification)
|
* Deletes an offer (with ownership verification)
|
||||||
* @param offerId Offer identifier
|
* @param offerId Offer identifier
|
||||||
* @param ownerPeerId Peer ID of the owner (for verification)
|
* @param ownerUsername Username of the owner (for verification)
|
||||||
* @returns true if deleted, false if not found or not owned
|
* @returns true if deleted, false if not found or not owned
|
||||||
*/
|
*/
|
||||||
deleteOffer(offerId: string, ownerPeerId: string): Promise<boolean>;
|
deleteOffer(offerId: string, ownerUsername: string): Promise<boolean>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Deletes all expired offers
|
* Deletes all expired offers
|
||||||
@@ -100,34 +131,35 @@ export interface Storage {
|
|||||||
/**
|
/**
|
||||||
* Answers an offer (locks it to the answerer)
|
* Answers an offer (locks it to the answerer)
|
||||||
* @param offerId Offer identifier
|
* @param offerId Offer identifier
|
||||||
* @param answererPeerId Answerer's peer ID
|
* @param answererUsername Answerer's username
|
||||||
* @param answerSdp WebRTC answer SDP
|
* @param answerSdp WebRTC answer SDP
|
||||||
* @param secret Optional secret for protected offers
|
|
||||||
* @returns Success status and optional error message
|
* @returns Success status and optional error message
|
||||||
*/
|
*/
|
||||||
answerOffer(offerId: string, answererPeerId: string, answerSdp: string, secret?: string): Promise<{
|
answerOffer(offerId: string, answererUsername: string, answerSdp: string): Promise<{
|
||||||
success: boolean;
|
success: boolean;
|
||||||
error?: string;
|
error?: string;
|
||||||
}>;
|
}>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieves all answered offers for a specific offerer
|
* Retrieves all answered offers for a specific offerer
|
||||||
* @param offererPeerId Offerer's peer ID
|
* @param offererUsername Offerer's username
|
||||||
* @returns Array of answered offers
|
* @returns Array of answered offers
|
||||||
*/
|
*/
|
||||||
getAnsweredOffers(offererPeerId: string): Promise<Offer[]>;
|
getAnsweredOffers(offererUsername: string): Promise<Offer[]>;
|
||||||
|
|
||||||
|
// ===== ICE Candidate Management =====
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Adds ICE candidates for an offer
|
* Adds ICE candidates for an offer
|
||||||
* @param offerId Offer identifier
|
* @param offerId Offer identifier
|
||||||
* @param peerId Peer ID posting the candidates
|
* @param username Username posting the candidates
|
||||||
* @param role Role of the peer (offerer or answerer)
|
* @param role Role of the user (offerer or answerer)
|
||||||
* @param candidates Array of candidate objects (stored as plain JSON)
|
* @param candidates Array of candidate objects (stored as plain JSON)
|
||||||
* @returns Number of candidates added
|
* @returns Number of candidates added
|
||||||
*/
|
*/
|
||||||
addIceCandidates(
|
addIceCandidates(
|
||||||
offerId: string,
|
offerId: string,
|
||||||
peerId: string,
|
username: string,
|
||||||
role: 'offerer' | 'answerer',
|
role: 'offerer' | 'answerer',
|
||||||
candidates: any[]
|
candidates: any[]
|
||||||
): Promise<number>;
|
): Promise<number>;
|
||||||
@@ -145,18 +177,107 @@ export interface Storage {
|
|||||||
since?: number
|
since?: number
|
||||||
): Promise<IceCandidate[]>;
|
): Promise<IceCandidate[]>;
|
||||||
|
|
||||||
|
// ===== Username Management =====
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Retrieves topics with active peer counts (paginated)
|
* Claims a username (or refreshes expiry if already owned)
|
||||||
* @param limit Maximum number of topics to return
|
* @param request Username claim request with signature
|
||||||
* @param offset Number of topics to skip
|
* @returns Created/updated username record
|
||||||
* @param startsWith Optional prefix filter - only return topics starting with this string
|
|
||||||
* @returns Object with topics array and total count
|
|
||||||
*/
|
*/
|
||||||
getTopics(limit: number, offset: number, startsWith?: string): Promise<{
|
claimUsername(request: ClaimUsernameRequest): Promise<Username>;
|
||||||
topics: TopicInfo[];
|
|
||||||
total: number;
|
/**
|
||||||
|
* Gets a username record
|
||||||
|
* @param username Username to look up
|
||||||
|
* @returns Username record if claimed, null otherwise
|
||||||
|
*/
|
||||||
|
getUsername(username: string): Promise<Username | null>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deletes all expired usernames
|
||||||
|
* @param now Current timestamp
|
||||||
|
* @returns Number of usernames deleted
|
||||||
|
*/
|
||||||
|
deleteExpiredUsernames(now: number): Promise<number>;
|
||||||
|
|
||||||
|
// ===== Service Management =====
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new service with offers
|
||||||
|
* @param request Service creation request (includes offers)
|
||||||
|
* @returns Created service with generated ID and created offers
|
||||||
|
*/
|
||||||
|
createService(request: CreateServiceRequest): Promise<{
|
||||||
|
service: Service;
|
||||||
|
offers: Offer[];
|
||||||
}>;
|
}>;
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets all offers for a service
|
||||||
|
* @param serviceId Service ID
|
||||||
|
* @returns Array of offers for the service
|
||||||
|
*/
|
||||||
|
getOffersForService(serviceId: string): Promise<Offer[]>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets a service by its service ID
|
||||||
|
* @param serviceId Service ID
|
||||||
|
* @returns Service if found, null otherwise
|
||||||
|
*/
|
||||||
|
getServiceById(serviceId: string): Promise<Service | null>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets a service by its fully qualified name (FQN)
|
||||||
|
* @param serviceFqn Full service FQN (e.g., "chat:1.0.0@alice")
|
||||||
|
* @returns Service if found, null otherwise
|
||||||
|
*/
|
||||||
|
getServiceByFqn(serviceFqn: string): Promise<Service | null>;
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Discovers services by name and version with pagination
|
||||||
|
* Returns unique available offers (where answerer_peer_id IS NULL)
|
||||||
|
* @param serviceName Service name (e.g., 'chat')
|
||||||
|
* @param version Version string for semver matching (e.g., '1.0.0')
|
||||||
|
* @param limit Maximum number of unique services to return
|
||||||
|
* @param offset Number of services to skip
|
||||||
|
* @returns Array of services with available offers
|
||||||
|
*/
|
||||||
|
discoverServices(
|
||||||
|
serviceName: string,
|
||||||
|
version: string,
|
||||||
|
limit: number,
|
||||||
|
offset: number
|
||||||
|
): Promise<Service[]>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets a random available service by name and version
|
||||||
|
* Returns a single random offer that is available (answerer_peer_id IS NULL)
|
||||||
|
* @param serviceName Service name (e.g., 'chat')
|
||||||
|
* @param version Version string for semver matching (e.g., '1.0.0')
|
||||||
|
* @returns Random service with available offer, or null if none found
|
||||||
|
*/
|
||||||
|
getRandomService(serviceName: string, version: string): Promise<Service | null>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deletes a service (with ownership verification)
|
||||||
|
* @param serviceId Service ID
|
||||||
|
* @param username Owner username (for verification)
|
||||||
|
* @returns true if deleted, false if not found or not owned
|
||||||
|
*/
|
||||||
|
deleteService(serviceId: string, username: string): Promise<boolean>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Deletes all expired services
|
||||||
|
* @param now Current timestamp
|
||||||
|
* @returns Number of services deleted
|
||||||
|
*/
|
||||||
|
deleteExpiredServices(now: number): Promise<number>;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Closes the storage connection and releases resources
|
* Closes the storage connection and releases resources
|
||||||
*/
|
*/
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
import { createApp } from './app.ts';
|
import { createApp } from './app.ts';
|
||||||
import { D1Storage } from './storage/d1.ts';
|
import { D1Storage } from './storage/d1.ts';
|
||||||
import { generateSecretKey } from './crypto.ts';
|
|
||||||
import { Config } from './config.ts';
|
import { Config } from './config.ts';
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -8,12 +7,10 @@ import { Config } from './config.ts';
|
|||||||
*/
|
*/
|
||||||
export interface Env {
|
export interface Env {
|
||||||
DB: D1Database;
|
DB: D1Database;
|
||||||
AUTH_SECRET?: string;
|
|
||||||
OFFER_DEFAULT_TTL?: string;
|
OFFER_DEFAULT_TTL?: string;
|
||||||
OFFER_MAX_TTL?: string;
|
OFFER_MAX_TTL?: string;
|
||||||
OFFER_MIN_TTL?: string;
|
OFFER_MIN_TTL?: string;
|
||||||
MAX_OFFERS_PER_REQUEST?: string;
|
MAX_OFFERS_PER_REQUEST?: string;
|
||||||
MAX_TOPICS_PER_OFFER?: string;
|
|
||||||
CORS_ORIGINS?: string;
|
CORS_ORIGINS?: string;
|
||||||
VERSION?: string;
|
VERSION?: string;
|
||||||
}
|
}
|
||||||
@@ -26,9 +23,6 @@ export default {
|
|||||||
// Initialize D1 storage
|
// Initialize D1 storage
|
||||||
const storage = new D1Storage(env.DB);
|
const storage = new D1Storage(env.DB);
|
||||||
|
|
||||||
// Generate or use provided auth secret
|
|
||||||
const authSecret = env.AUTH_SECRET || generateSecretKey();
|
|
||||||
|
|
||||||
// Build config from environment
|
// Build config from environment
|
||||||
const config: Config = {
|
const config: Config = {
|
||||||
port: 0, // Not used in Workers
|
port: 0, // Not used in Workers
|
||||||
@@ -38,13 +32,11 @@ export default {
|
|||||||
? env.CORS_ORIGINS.split(',').map(o => o.trim())
|
? env.CORS_ORIGINS.split(',').map(o => o.trim())
|
||||||
: ['*'],
|
: ['*'],
|
||||||
version: env.VERSION || 'unknown',
|
version: env.VERSION || 'unknown',
|
||||||
authSecret,
|
|
||||||
offerDefaultTtl: env.OFFER_DEFAULT_TTL ? parseInt(env.OFFER_DEFAULT_TTL, 10) : 60000,
|
offerDefaultTtl: env.OFFER_DEFAULT_TTL ? parseInt(env.OFFER_DEFAULT_TTL, 10) : 60000,
|
||||||
offerMaxTtl: env.OFFER_MAX_TTL ? parseInt(env.OFFER_MAX_TTL, 10) : 86400000,
|
offerMaxTtl: env.OFFER_MAX_TTL ? parseInt(env.OFFER_MAX_TTL, 10) : 86400000,
|
||||||
offerMinTtl: env.OFFER_MIN_TTL ? parseInt(env.OFFER_MIN_TTL, 10) : 60000,
|
offerMinTtl: env.OFFER_MIN_TTL ? parseInt(env.OFFER_MIN_TTL, 10) : 60000,
|
||||||
cleanupInterval: 60000, // Not used in Workers (scheduled handler instead)
|
cleanupInterval: 60000, // Not used in Workers (scheduled handler instead)
|
||||||
maxOffersPerRequest: env.MAX_OFFERS_PER_REQUEST ? parseInt(env.MAX_OFFERS_PER_REQUEST, 10) : 100,
|
maxOffersPerRequest: env.MAX_OFFERS_PER_REQUEST ? parseInt(env.MAX_OFFERS_PER_REQUEST, 10) : 100
|
||||||
maxTopicsPerOffer: env.MAX_TOPICS_PER_OFFER ? parseInt(env.MAX_TOPICS_PER_OFFER, 10) : 50,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Create Hono app
|
// Create Hono app
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ compatibility_flags = ["nodejs_compat"]
|
|||||||
[[d1_databases]]
|
[[d1_databases]]
|
||||||
binding = "DB"
|
binding = "DB"
|
||||||
database_name = "rondevu-offers"
|
database_name = "rondevu-offers"
|
||||||
database_id = "b94e3f71-816d-455b-a89d-927fa49532d0"
|
database_id = "3d469855-d37f-477b-b139-fa58843a54ff"
|
||||||
|
|
||||||
# Environment variables
|
# Environment variables
|
||||||
[vars]
|
[vars]
|
||||||
@@ -17,7 +17,7 @@ OFFER_MIN_TTL = "60000" # Min offer TTL: 1 minute
|
|||||||
MAX_OFFERS_PER_REQUEST = "100" # Max offers per request
|
MAX_OFFERS_PER_REQUEST = "100" # Max offers per request
|
||||||
MAX_TOPICS_PER_OFFER = "50" # Max topics per offer
|
MAX_TOPICS_PER_OFFER = "50" # Max topics per offer
|
||||||
CORS_ORIGINS = "*" # Comma-separated list of allowed origins
|
CORS_ORIGINS = "*" # Comma-separated list of allowed origins
|
||||||
VERSION = "0.1.0" # Semantic version
|
VERSION = "0.4.0" # Semantic version
|
||||||
|
|
||||||
# AUTH_SECRET should be set as a secret, not a var
|
# AUTH_SECRET should be set as a secret, not a var
|
||||||
# Run: npx wrangler secret put AUTH_SECRET
|
# Run: npx wrangler secret put AUTH_SECRET
|
||||||
@@ -39,7 +39,7 @@ command = ""
|
|||||||
|
|
||||||
[observability]
|
[observability]
|
||||||
[observability.logs]
|
[observability.logs]
|
||||||
enabled = false
|
enabled = true
|
||||||
head_sampling_rate = 1
|
head_sampling_rate = 1
|
||||||
invocation_logs = true
|
invocation_logs = true
|
||||||
persist = true
|
persist = true
|
||||||
|
|||||||
Reference in New Issue
Block a user