mirror of
https://github.com/xtr-dev/rondevu-server.git
synced 2025-12-10 02:43:24 +00:00
Compare commits
8 Commits
3efed6e9d2
...
163e1f73d4
| Author | SHA1 | Date | |
|---|---|---|---|
| 163e1f73d4 | |||
| 1d47d47ef7 | |||
| 1d70cd79e8 | |||
| 2aa1fee4d6 | |||
| d564e2250f | |||
| 06ec5020f7 | |||
| 5c71f66a26 | |||
| ca3db47009 |
237
README.md
237
README.md
@@ -30,11 +30,11 @@ Username Claiming → Service Publishing → Service Discovery → WebRTC Connec
|
||||
|
||||
alice claims "alice" with Ed25519 signature
|
||||
↓
|
||||
alice publishes com.example.chat@1.0.0 → receives UUID abc123
|
||||
alice publishes com.example.chat@1.0.0 with multiple offers → receives UUID abc123
|
||||
↓
|
||||
bob queries alice's services → gets UUID abc123
|
||||
bob requests alice/com.example.chat@1.0.0 → gets compatible service with available offer
|
||||
↓
|
||||
bob connects to UUID abc123 → WebRTC connection established
|
||||
WebRTC connection established via offer/answer exchange
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
@@ -77,15 +77,28 @@ Generates a cryptographically random 128-bit peer ID.
|
||||
}
|
||||
```
|
||||
|
||||
### Username Management
|
||||
### User Management (RESTful)
|
||||
|
||||
#### `POST /usernames/claim`
|
||||
#### `GET /users/:username`
|
||||
Check username availability and claim status
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"username": "alice",
|
||||
"available": false,
|
||||
"claimedAt": 1733404800000,
|
||||
"expiresAt": 1765027200000,
|
||||
"publicKey": "..."
|
||||
}
|
||||
```
|
||||
|
||||
#### `POST /users/:username`
|
||||
Claim a username with cryptographic proof
|
||||
|
||||
**Request:**
|
||||
```json
|
||||
{
|
||||
"username": "alice",
|
||||
"publicKey": "base64-encoded-ed25519-public-key",
|
||||
"signature": "base64-encoded-signature",
|
||||
"message": "claim:alice:1733404800000"
|
||||
@@ -107,46 +120,37 @@ Claim a username with cryptographic proof
|
||||
- Timestamp must be within 5 minutes (replay protection)
|
||||
- Expires after 365 days, auto-renewed on use
|
||||
|
||||
#### `GET /usernames/:username`
|
||||
Check username availability and claim status
|
||||
#### `GET /users/:username/services/:fqn`
|
||||
Get service by username and FQN with semver-compatible matching
|
||||
|
||||
**Semver Matching:**
|
||||
- Requesting `chat@1.0.0` matches any `1.x.x` version
|
||||
- Major version must match exactly (`chat@1.0.0` will NOT match `chat@2.0.0`)
|
||||
- For major version 0, minor must also match (`0.1.0` will NOT match `0.2.0`)
|
||||
- Returns the most recently published compatible version
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"username": "alice",
|
||||
"available": false,
|
||||
"claimedAt": 1733404800000,
|
||||
"expiresAt": 1765027200000,
|
||||
"publicKey": "..."
|
||||
}
|
||||
```
|
||||
|
||||
#### `GET /usernames/:username/services`
|
||||
List all services for a username (privacy-preserving)
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"username": "alice",
|
||||
"services": [
|
||||
{
|
||||
"uuid": "abc123",
|
||||
"isPublic": false
|
||||
},
|
||||
{
|
||||
"uuid": "def456",
|
||||
"serviceId": "service-id",
|
||||
"username": "alice",
|
||||
"serviceFqn": "chat.app@1.0.0",
|
||||
"offerId": "offer-hash",
|
||||
"sdp": "v=0...",
|
||||
"isPublic": true,
|
||||
"serviceFqn": "com.example.public@1.0.0",
|
||||
"metadata": { "description": "Public service" }
|
||||
}
|
||||
]
|
||||
"metadata": {},
|
||||
"createdAt": 1733404800000,
|
||||
"expiresAt": 1733405100000
|
||||
}
|
||||
```
|
||||
|
||||
### Service Management
|
||||
**Note:** Returns a single available offer from the service. If all offers are in use, returns 503.
|
||||
|
||||
#### `POST /services`
|
||||
Publish a service (requires authentication and username signature)
|
||||
### Service Management (RESTful)
|
||||
|
||||
#### `POST /users/:username/services`
|
||||
Publish a service with multiple offers (requires authentication and username signature)
|
||||
|
||||
**Headers:**
|
||||
- `Authorization: Bearer {peerId}:{secret}`
|
||||
@@ -154,9 +158,11 @@ Publish a service (requires authentication and username signature)
|
||||
**Request:**
|
||||
```json
|
||||
{
|
||||
"username": "alice",
|
||||
"serviceFqn": "com.example.chat@1.0.0",
|
||||
"sdp": "v=0...",
|
||||
"offers": [
|
||||
{ "sdp": "v=0..." },
|
||||
{ "sdp": "v=0..." }
|
||||
],
|
||||
"ttl": 300000,
|
||||
"isPublic": false,
|
||||
"metadata": { "description": "Chat service" },
|
||||
@@ -165,12 +171,30 @@ Publish a service (requires authentication and username signature)
|
||||
}
|
||||
```
|
||||
|
||||
**Response:**
|
||||
**Response (Full service details):**
|
||||
```json
|
||||
{
|
||||
"serviceId": "uuid-v4",
|
||||
"uuid": "uuid-v4-for-index",
|
||||
"offerId": "offer-hash-id",
|
||||
"serviceId": "uuid-v4",
|
||||
"username": "alice",
|
||||
"serviceFqn": "com.example.chat@1.0.0",
|
||||
"offers": [
|
||||
{
|
||||
"offerId": "offer-hash-1",
|
||||
"sdp": "v=0...",
|
||||
"createdAt": 1733404800000,
|
||||
"expiresAt": 1733405100000
|
||||
},
|
||||
{
|
||||
"offerId": "offer-hash-2",
|
||||
"sdp": "v=0...",
|
||||
"createdAt": 1733404800000,
|
||||
"expiresAt": 1733405100000
|
||||
}
|
||||
],
|
||||
"isPublic": false,
|
||||
"metadata": { "description": "Chat service" },
|
||||
"createdAt": 1733404800000,
|
||||
"expiresAt": 1733405100000
|
||||
}
|
||||
```
|
||||
@@ -203,7 +227,7 @@ Get service details by UUID
|
||||
}
|
||||
```
|
||||
|
||||
#### `DELETE /services/:serviceId`
|
||||
#### `DELETE /users/:username/services/:fqn`
|
||||
Unpublish a service (requires authentication and ownership)
|
||||
|
||||
**Headers:**
|
||||
@@ -216,58 +240,14 @@ Unpublish a service (requires authentication and ownership)
|
||||
}
|
||||
```
|
||||
|
||||
### Service Discovery
|
||||
### WebRTC Signaling (Service-Based)
|
||||
|
||||
#### `POST /index/:username/query`
|
||||
Query a service by FQN
|
||||
|
||||
**Request:**
|
||||
```json
|
||||
{
|
||||
"serviceFqn": "com.example.chat@1.0.0"
|
||||
}
|
||||
```
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"uuid": "abc123",
|
||||
"allowed": true
|
||||
}
|
||||
```
|
||||
|
||||
### Offer Management (Low-level)
|
||||
|
||||
#### `POST /offers`
|
||||
Create one or more offers (requires authentication)
|
||||
#### `POST /services/:uuid/answer`
|
||||
Answer a service offer (requires authentication)
|
||||
|
||||
**Headers:**
|
||||
- `Authorization: Bearer {peerId}:{secret}`
|
||||
|
||||
**Request:**
|
||||
```json
|
||||
{
|
||||
"offers": [
|
||||
{
|
||||
"sdp": "v=0...",
|
||||
"ttl": 300000
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
#### `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
|
||||
{
|
||||
@@ -275,21 +255,76 @@ Answer an offer (locks it to answerer)
|
||||
}
|
||||
```
|
||||
|
||||
#### `GET /offers/answers`
|
||||
Poll for answers to your offers
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"offerId": "offer-hash"
|
||||
}
|
||||
```
|
||||
|
||||
#### `POST /offers/:offerId/ice-candidates`
|
||||
Post ICE candidates for an offer
|
||||
#### `GET /services/:uuid/answer`
|
||||
Get answer for a service (offerer polls this)
|
||||
|
||||
**Headers:**
|
||||
- `Authorization: Bearer {peerId}:{secret}`
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"offerId": "offer-hash",
|
||||
"answererId": "answerer-peer-id",
|
||||
"sdp": "v=0...",
|
||||
"answeredAt": 1733404800000
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** Returns 404 if not yet answered
|
||||
|
||||
#### `POST /services/:uuid/ice-candidates`
|
||||
Post ICE candidates for a service (requires authentication)
|
||||
|
||||
**Headers:**
|
||||
- `Authorization: Bearer {peerId}:{secret}`
|
||||
|
||||
**Request:**
|
||||
```json
|
||||
{
|
||||
"candidates": ["candidate:1 1 UDP..."]
|
||||
"candidates": ["candidate:1 1 UDP..."],
|
||||
"offerId": "optional-offer-id"
|
||||
}
|
||||
```
|
||||
|
||||
#### `GET /offers/:offerId/ice-candidates?since=1234567890`
|
||||
Get ICE candidates from the other peer
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"count": 1,
|
||||
"offerId": "offer-hash"
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** If `offerId` is omitted, the server will auto-detect the peer's offer
|
||||
|
||||
#### `GET /services/:uuid/ice-candidates?since=1234567890&offerId=optional-offer-id`
|
||||
Get ICE candidates from the other peer (requires authentication)
|
||||
|
||||
**Headers:**
|
||||
- `Authorization: Bearer {peerId}:{secret}`
|
||||
|
||||
**Response:**
|
||||
```json
|
||||
{
|
||||
"candidates": [
|
||||
{
|
||||
"candidate": "candidate:1 1 UDP...",
|
||||
"createdAt": 1733404800000
|
||||
}
|
||||
],
|
||||
"offerId": "offer-hash"
|
||||
}
|
||||
```
|
||||
|
||||
**Note:** Returns candidates from the opposite role (offerer gets answerer candidates and vice versa)
|
||||
|
||||
## Configuration
|
||||
|
||||
@@ -321,11 +356,19 @@ Environment variables:
|
||||
- `id` (PK): Service ID (UUID)
|
||||
- `username` (FK): Owner username
|
||||
- `service_fqn`: Fully qualified name (com.example.chat@1.0.0)
|
||||
- `offer_id` (FK): WebRTC offer ID
|
||||
- `is_public`: Public/private flag
|
||||
- `metadata`: JSON metadata
|
||||
- `created_at`, `expires_at`: Timestamps
|
||||
|
||||
### offers
|
||||
- `id` (PK): Offer ID (hash of SDP)
|
||||
- `peer_id` (FK): Owner peer ID
|
||||
- `service_id` (FK): Optional link to service (null for standalone offers)
|
||||
- `sdp`: WebRTC offer SDP
|
||||
- `answerer_peer_id`: Peer ID of answerer (null until answered)
|
||||
- `answer_sdp`: WebRTC answer SDP (null until answered)
|
||||
- `created_at`, `expires_at`, `last_seen`: Timestamps
|
||||
|
||||
### service_index (privacy layer)
|
||||
- `uuid` (PK): Random UUID for discovery
|
||||
- `service_id` (FK): Links to service
|
||||
|
||||
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
|
||||
4
package-lock.json
generated
4
package-lock.json
generated
@@ -1,12 +1,12 @@
|
||||
{
|
||||
"name": "@xtr-dev/rondevu-server",
|
||||
"version": "0.1.5",
|
||||
"version": "0.4.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@xtr-dev/rondevu-server",
|
||||
"version": "0.1.5",
|
||||
"version": "0.4.0",
|
||||
"dependencies": {
|
||||
"@hono/node-server": "^1.19.6",
|
||||
"@noble/ed25519": "^3.0.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@xtr-dev/rondevu-server",
|
||||
"version": "0.2.4",
|
||||
"version": "0.4.0",
|
||||
"description": "DNS-like WebRTC signaling server with username claiming and service discovery",
|
||||
"main": "dist/index.js",
|
||||
"scripts": {
|
||||
|
||||
632
src/app.ts
632
src/app.ts
@@ -3,11 +3,12 @@ import { cors } from 'hono/cors';
|
||||
import { Storage } from './storage/types.ts';
|
||||
import { Config } from './config.ts';
|
||||
import { createAuthMiddleware, getAuthenticatedPeerId } from './middleware/auth.ts';
|
||||
import { generatePeerId, encryptPeerId, validateUsernameClaim, validateServicePublish, validateServiceFqn } from './crypto.ts';
|
||||
import { generatePeerId, encryptPeerId, validateUsernameClaim, validateServicePublish, validateServiceFqn, parseServiceFqn, isVersionCompatible } from './crypto.ts';
|
||||
import type { Context } from 'hono';
|
||||
|
||||
/**
|
||||
* Creates the Hono application with username and service-based WebRTC signaling
|
||||
* RESTful API design - v0.11.0
|
||||
*/
|
||||
export function createApp(storage: Storage, config: Config) {
|
||||
const app = new Hono();
|
||||
@@ -78,58 +79,13 @@ export function createApp(storage: Storage, config: Config) {
|
||||
}
|
||||
});
|
||||
|
||||
// ===== Username Management =====
|
||||
// ===== User Management (RESTful) =====
|
||||
|
||||
/**
|
||||
* POST /usernames/claim
|
||||
* Claim a username with cryptographic proof
|
||||
*/
|
||||
app.post('/usernames/claim', async (c) => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const { username, publicKey, signature, message } = body;
|
||||
|
||||
if (!username || !publicKey || !signature || !message) {
|
||||
return c.json({ error: 'Missing required parameters: username, publicKey, signature, message' }, 400);
|
||||
}
|
||||
|
||||
// Validate claim
|
||||
const validation = await validateUsernameClaim(username, publicKey, signature, message);
|
||||
if (!validation.valid) {
|
||||
return c.json({ error: validation.error }, 400);
|
||||
}
|
||||
|
||||
// Attempt to claim username
|
||||
try {
|
||||
const claimed = await storage.claimUsername({
|
||||
username,
|
||||
publicKey,
|
||||
signature,
|
||||
message
|
||||
});
|
||||
|
||||
return c.json({
|
||||
username: claimed.username,
|
||||
claimedAt: claimed.claimedAt,
|
||||
expiresAt: claimed.expiresAt
|
||||
}, 200);
|
||||
} catch (err: any) {
|
||||
if (err.message?.includes('already claimed')) {
|
||||
return c.json({ error: 'Username already claimed by different public key' }, 409);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error claiming username:', err);
|
||||
return c.json({ error: 'Internal server error' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /usernames/:username
|
||||
* GET /users/:username
|
||||
* Check if username is available or get claim info
|
||||
*/
|
||||
app.get('/usernames/:username', async (c) => {
|
||||
app.get('/users/:username', async (c) => {
|
||||
try {
|
||||
const username = c.req.param('username');
|
||||
|
||||
@@ -156,43 +112,150 @@ export function createApp(storage: Storage, config: Config) {
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /usernames/:username/services
|
||||
* List services for a username (privacy-preserving)
|
||||
* POST /users/:username
|
||||
* Claim a username with cryptographic proof
|
||||
*/
|
||||
app.get('/usernames/:username/services', async (c) => {
|
||||
app.post('/users/:username', async (c) => {
|
||||
try {
|
||||
const username = c.req.param('username');
|
||||
const body = await c.req.json();
|
||||
const { publicKey, signature, message } = body;
|
||||
|
||||
const services = await storage.listServicesForUsername(username);
|
||||
if (!publicKey || !signature || !message) {
|
||||
return c.json({ error: 'Missing required parameters: publicKey, signature, message' }, 400);
|
||||
}
|
||||
|
||||
// Validate claim
|
||||
const validation = await validateUsernameClaim(username, publicKey, signature, message);
|
||||
if (!validation.valid) {
|
||||
return c.json({ error: validation.error }, 400);
|
||||
}
|
||||
|
||||
// Attempt to claim username
|
||||
try {
|
||||
const claimed = await storage.claimUsername({
|
||||
username,
|
||||
publicKey,
|
||||
signature,
|
||||
message
|
||||
});
|
||||
|
||||
return c.json({
|
||||
username,
|
||||
services
|
||||
}, 200);
|
||||
username: claimed.username,
|
||||
claimedAt: claimed.claimedAt,
|
||||
expiresAt: claimed.expiresAt
|
||||
}, 201);
|
||||
} catch (err: any) {
|
||||
if (err.message?.includes('already claimed')) {
|
||||
return c.json({ error: 'Username already claimed by different public key' }, 409);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Error listing services:', err);
|
||||
console.error('Error claiming username:', err);
|
||||
return c.json({ error: 'Internal server error' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// ===== Service Management =====
|
||||
/**
|
||||
* GET /users/:username/services/:fqn
|
||||
* Get service by username and FQN with semver-compatible matching
|
||||
*/
|
||||
app.get('/users/:username/services/:fqn', async (c) => {
|
||||
try {
|
||||
const username = c.req.param('username');
|
||||
const serviceFqn = decodeURIComponent(c.req.param('fqn'));
|
||||
|
||||
// Parse the requested FQN
|
||||
const parsed = parseServiceFqn(serviceFqn);
|
||||
if (!parsed) {
|
||||
return c.json({ error: 'Invalid service FQN format' }, 400);
|
||||
}
|
||||
|
||||
const { serviceName, version: requestedVersion } = parsed;
|
||||
|
||||
// Find all services with matching service name
|
||||
const matchingServices = await storage.findServicesByName(username, serviceName);
|
||||
|
||||
if (matchingServices.length === 0) {
|
||||
return c.json({ error: 'Service not found' }, 404);
|
||||
}
|
||||
|
||||
// Filter to compatible versions
|
||||
const compatibleServices = matchingServices.filter(service => {
|
||||
const serviceParsed = parseServiceFqn(service.serviceFqn);
|
||||
if (!serviceParsed) return false;
|
||||
return isVersionCompatible(requestedVersion, serviceParsed.version);
|
||||
});
|
||||
|
||||
if (compatibleServices.length === 0) {
|
||||
return c.json({
|
||||
error: 'No compatible version found',
|
||||
message: `Requested ${serviceFqn}, but no compatible versions available`
|
||||
}, 404);
|
||||
}
|
||||
|
||||
// Use the first compatible service (most recently created)
|
||||
const service = compatibleServices[0];
|
||||
|
||||
// Get the UUID for this service
|
||||
const uuid = await storage.queryService(username, service.serviceFqn);
|
||||
|
||||
if (!uuid) {
|
||||
return c.json({ error: 'Service index not found' }, 500);
|
||||
}
|
||||
|
||||
// Get all offers for this service
|
||||
const serviceOffers = await storage.getOffersForService(service.id);
|
||||
|
||||
if (serviceOffers.length === 0) {
|
||||
return c.json({ error: 'No offers found for this service' }, 404);
|
||||
}
|
||||
|
||||
// Find an unanswered offer
|
||||
const availableOffer = serviceOffers.find(offer => !offer.answererPeerId);
|
||||
|
||||
if (!availableOffer) {
|
||||
return c.json({
|
||||
error: 'No available offers',
|
||||
message: 'All offers from this service are currently in use. Please try again later.'
|
||||
}, 503);
|
||||
}
|
||||
|
||||
return c.json({
|
||||
uuid: uuid,
|
||||
serviceId: service.id,
|
||||
username: service.username,
|
||||
serviceFqn: service.serviceFqn,
|
||||
offerId: availableOffer.id,
|
||||
sdp: availableOffer.sdp,
|
||||
isPublic: service.isPublic,
|
||||
metadata: service.metadata ? JSON.parse(service.metadata) : undefined,
|
||||
createdAt: service.createdAt,
|
||||
expiresAt: service.expiresAt
|
||||
}, 200);
|
||||
} catch (err) {
|
||||
console.error('Error getting service:', err);
|
||||
return c.json({ error: 'Internal server error' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /services
|
||||
* Publish a service
|
||||
* POST /users/:username/services
|
||||
* Publish a service with one or more offers (RESTful endpoint)
|
||||
*/
|
||||
app.post('/services', authMiddleware, async (c) => {
|
||||
let username: string | undefined;
|
||||
app.post('/users/:username/services', authMiddleware, async (c) => {
|
||||
let serviceFqn: string | undefined;
|
||||
let offers: any[] = [];
|
||||
let createdOffers: any[] = [];
|
||||
|
||||
try {
|
||||
const username = c.req.param('username');
|
||||
const body = await c.req.json();
|
||||
({ username, serviceFqn } = body);
|
||||
const { sdp, ttl, isPublic, metadata, signature, message } = body;
|
||||
serviceFqn = body.serviceFqn;
|
||||
const { offers, ttl, isPublic, metadata, signature, message } = body;
|
||||
|
||||
if (!username || !serviceFqn || !sdp) {
|
||||
return c.json({ error: 'Missing required parameters: username, serviceFqn, sdp' }, 400);
|
||||
if (!serviceFqn || !offers || !Array.isArray(offers) || offers.length === 0) {
|
||||
return c.json({ error: 'Missing required parameters: serviceFqn, offers (must be non-empty array)' }, 400);
|
||||
}
|
||||
|
||||
// Validate service FQN
|
||||
@@ -226,14 +289,16 @@ export function createApp(storage: Storage, config: Config) {
|
||||
}
|
||||
}
|
||||
|
||||
// Validate SDP
|
||||
if (typeof sdp !== 'string' || sdp.length === 0) {
|
||||
return c.json({ error: 'Invalid SDP' }, 400);
|
||||
// Validate all offers
|
||||
for (const offer of offers) {
|
||||
if (!offer.sdp || typeof offer.sdp !== 'string' || offer.sdp.length === 0) {
|
||||
return c.json({ error: 'Invalid SDP in offers array' }, 400);
|
||||
}
|
||||
|
||||
if (sdp.length > 64 * 1024) {
|
||||
if (offer.sdp.length > 64 * 1024) {
|
||||
return c.json({ error: 'SDP too large (max 64KB)' }, 400);
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate expiry
|
||||
const peerId = getAuthenticatedPeerId(c);
|
||||
@@ -243,33 +308,40 @@ export function createApp(storage: Storage, config: Config) {
|
||||
);
|
||||
const expiresAt = Date.now() + offerTtl;
|
||||
|
||||
// Create offer first
|
||||
offers = await storage.createOffers([{
|
||||
// Prepare offer requests
|
||||
const offerRequests = offers.map(offer => ({
|
||||
peerId,
|
||||
sdp,
|
||||
sdp: offer.sdp,
|
||||
expiresAt
|
||||
}]);
|
||||
}));
|
||||
|
||||
if (offers.length === 0) {
|
||||
return c.json({ error: 'Failed to create offer' }, 500);
|
||||
}
|
||||
|
||||
const offer = offers[0];
|
||||
|
||||
// Create service
|
||||
// Create service with offers
|
||||
const result = await storage.createService({
|
||||
username,
|
||||
serviceFqn,
|
||||
offerId: offer.id,
|
||||
expiresAt,
|
||||
isPublic: isPublic || false,
|
||||
metadata: metadata ? JSON.stringify(metadata) : undefined
|
||||
metadata: metadata ? JSON.stringify(metadata) : undefined,
|
||||
offers: offerRequests
|
||||
});
|
||||
|
||||
createdOffers = result.offers;
|
||||
|
||||
// Return full service details with all offers
|
||||
return c.json({
|
||||
serviceId: result.service.id,
|
||||
uuid: result.indexUuid,
|
||||
offerId: offer.id,
|
||||
serviceFqn: serviceFqn,
|
||||
username: username,
|
||||
serviceId: result.service.id,
|
||||
offers: result.offers.map(o => ({
|
||||
offerId: o.id,
|
||||
sdp: o.sdp,
|
||||
createdAt: o.createdAt,
|
||||
expiresAt: o.expiresAt
|
||||
})),
|
||||
isPublic: result.service.isPublic,
|
||||
metadata: metadata,
|
||||
createdAt: result.service.createdAt,
|
||||
expiresAt: result.service.expiresAt
|
||||
}, 201);
|
||||
} catch (err) {
|
||||
@@ -277,9 +349,9 @@ export function createApp(storage: Storage, config: Config) {
|
||||
console.error('Error details:', {
|
||||
message: (err as Error).message,
|
||||
stack: (err as Error).stack,
|
||||
username,
|
||||
username: c.req.param('username'),
|
||||
serviceFqn,
|
||||
offerId: offers[0]?.id
|
||||
offerIds: createdOffers.map(o => o.id)
|
||||
});
|
||||
return c.json({
|
||||
error: 'Internal server error',
|
||||
@@ -288,10 +360,44 @@ export function createApp(storage: Storage, config: Config) {
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* DELETE /users/:username/services/:fqn
|
||||
* Delete a service by username and FQN (RESTful)
|
||||
*/
|
||||
app.delete('/users/:username/services/:fqn', authMiddleware, async (c) => {
|
||||
try {
|
||||
const username = c.req.param('username');
|
||||
const serviceFqn = decodeURIComponent(c.req.param('fqn'));
|
||||
|
||||
// Find service by username and FQN
|
||||
const uuid = await storage.queryService(username, serviceFqn);
|
||||
if (!uuid) {
|
||||
return c.json({ error: 'Service not found' }, 404);
|
||||
}
|
||||
|
||||
const service = await storage.getServiceByUuid(uuid);
|
||||
if (!service) {
|
||||
return c.json({ error: 'Service not found' }, 404);
|
||||
}
|
||||
|
||||
const deleted = await storage.deleteService(service.id, username);
|
||||
|
||||
if (!deleted) {
|
||||
return c.json({ error: 'Service not found or not owned by this username' }, 404);
|
||||
}
|
||||
|
||||
return c.json({ success: true }, 200);
|
||||
} catch (err) {
|
||||
console.error('Error deleting service:', err);
|
||||
return c.json({ error: 'Internal server error' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// ===== Service Management (Legacy - for UUID-based access) =====
|
||||
|
||||
/**
|
||||
* GET /services/:uuid
|
||||
* Get service details by index UUID
|
||||
* Returns an available (unanswered) offer from the service's pool
|
||||
* Get service details by index UUID (kept for privacy)
|
||||
*/
|
||||
app.get('/services/:uuid', async (c) => {
|
||||
try {
|
||||
@@ -303,18 +409,15 @@ export function createApp(storage: Storage, config: Config) {
|
||||
return c.json({ error: 'Service not found' }, 404);
|
||||
}
|
||||
|
||||
// Get the initial offer to find the peer ID
|
||||
const initialOffer = await storage.getOfferById(service.offerId);
|
||||
// Get all offers for this service
|
||||
const serviceOffers = await storage.getOffersForService(service.id);
|
||||
|
||||
if (!initialOffer) {
|
||||
return c.json({ error: 'Associated offer not found' }, 404);
|
||||
if (serviceOffers.length === 0) {
|
||||
return c.json({ error: 'No offers found for this service' }, 404);
|
||||
}
|
||||
|
||||
// Get all offers from this peer
|
||||
const peerOffers = await storage.getOffersByPeerId(initialOffer.peerId);
|
||||
|
||||
// Find an unanswered offer
|
||||
const availableOffer = peerOffers.find(offer => !offer.answererPeerId);
|
||||
const availableOffer = serviceOffers.find(offer => !offer.answererPeerId);
|
||||
|
||||
if (!availableOffer) {
|
||||
return c.json({
|
||||
@@ -324,6 +427,7 @@ export function createApp(storage: Storage, config: Config) {
|
||||
}
|
||||
|
||||
return c.json({
|
||||
uuid: uuid,
|
||||
serviceId: service.id,
|
||||
username: service.username,
|
||||
serviceFqn: service.serviceFqn,
|
||||
@@ -340,184 +444,17 @@ export function createApp(storage: Storage, config: Config) {
|
||||
}
|
||||
});
|
||||
|
||||
// ===== Service-Based WebRTC Signaling =====
|
||||
|
||||
/**
|
||||
* DELETE /services/:serviceId
|
||||
* Delete a service (requires ownership)
|
||||
* POST /services/:uuid/answer
|
||||
* Answer a service offer
|
||||
*/
|
||||
app.delete('/services/:serviceId', authMiddleware, async (c) => {
|
||||
app.post('/services/:uuid/answer', authMiddleware, async (c) => {
|
||||
try {
|
||||
const serviceId = c.req.param('serviceId');
|
||||
const uuid = c.req.param('uuid');
|
||||
const body = await c.req.json();
|
||||
const { username } = body;
|
||||
|
||||
if (!username) {
|
||||
return c.json({ error: 'Missing required parameter: username' }, 400);
|
||||
}
|
||||
|
||||
const deleted = await storage.deleteService(serviceId, username);
|
||||
|
||||
if (!deleted) {
|
||||
return c.json({ error: 'Service not found or not owned by this username' }, 404);
|
||||
}
|
||||
|
||||
return c.json({ success: true }, 200);
|
||||
} catch (err) {
|
||||
console.error('Error deleting service:', err);
|
||||
return c.json({ error: 'Internal server error' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /index/:username/query
|
||||
* Query service by FQN (returns UUID)
|
||||
*/
|
||||
app.post('/index/:username/query', async (c) => {
|
||||
try {
|
||||
const username = c.req.param('username');
|
||||
const body = await c.req.json();
|
||||
const { serviceFqn } = body;
|
||||
|
||||
if (!serviceFqn) {
|
||||
return c.json({ error: 'Missing required parameter: serviceFqn' }, 400);
|
||||
}
|
||||
|
||||
const uuid = await storage.queryService(username, serviceFqn);
|
||||
|
||||
if (!uuid) {
|
||||
return c.json({ error: 'Service not found' }, 404);
|
||||
}
|
||||
|
||||
return c.json({
|
||||
uuid,
|
||||
allowed: true
|
||||
}, 200);
|
||||
} catch (err) {
|
||||
console.error('Error querying service:', err);
|
||||
return c.json({ error: 'Internal server error' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// ===== Offer Management (Core WebRTC) =====
|
||||
|
||||
/**
|
||||
* POST /offers
|
||||
* Create offers (direct, no service - for testing/advanced users)
|
||||
*/
|
||||
app.post('/offers', authMiddleware, async (c) => {
|
||||
try {
|
||||
const body = await c.req.json();
|
||||
const { offers } = body;
|
||||
|
||||
if (!Array.isArray(offers) || offers.length === 0) {
|
||||
return c.json({ error: 'Missing or invalid required parameter: offers (must be non-empty array)' }, 400);
|
||||
}
|
||||
|
||||
if (offers.length > config.maxOffersPerRequest) {
|
||||
return c.json({ error: `Too many offers (max ${config.maxOffersPerRequest})` }, 400);
|
||||
}
|
||||
|
||||
const peerId = getAuthenticatedPeerId(c);
|
||||
|
||||
// Validate and prepare offers
|
||||
const validated = offers.map((offer: any) => {
|
||||
const { sdp, ttl, secret } = offer;
|
||||
|
||||
if (typeof sdp !== 'string' || sdp.length === 0) {
|
||||
throw new Error('Invalid SDP in offer');
|
||||
}
|
||||
|
||||
if (sdp.length > 64 * 1024) {
|
||||
throw new Error('SDP too large (max 64KB)');
|
||||
}
|
||||
|
||||
const offerTtl = Math.min(
|
||||
Math.max(ttl || config.offerDefaultTtl, config.offerMinTtl),
|
||||
config.offerMaxTtl
|
||||
);
|
||||
|
||||
return {
|
||||
peerId,
|
||||
sdp,
|
||||
expiresAt: Date.now() + offerTtl,
|
||||
secret: secret ? String(secret).substring(0, 128) : undefined
|
||||
};
|
||||
});
|
||||
|
||||
const created = await storage.createOffers(validated);
|
||||
|
||||
return c.json({
|
||||
offers: created.map(offer => ({
|
||||
id: offer.id,
|
||||
peerId: offer.peerId,
|
||||
expiresAt: offer.expiresAt,
|
||||
createdAt: offer.createdAt,
|
||||
hasSecret: !!offer.secret
|
||||
}))
|
||||
}, 201);
|
||||
} catch (err: any) {
|
||||
console.error('Error creating offers:', err);
|
||||
return c.json({ error: err.message || 'Internal server error' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /offers/mine
|
||||
* Get authenticated peer's offers
|
||||
*/
|
||||
app.get('/offers/mine', authMiddleware, async (c) => {
|
||||
try {
|
||||
const peerId = getAuthenticatedPeerId(c);
|
||||
const offers = await storage.getOffersByPeerId(peerId);
|
||||
|
||||
return c.json({
|
||||
offers: offers.map(offer => ({
|
||||
id: offer.id,
|
||||
sdp: offer.sdp,
|
||||
createdAt: offer.createdAt,
|
||||
expiresAt: offer.expiresAt,
|
||||
lastSeen: offer.lastSeen,
|
||||
hasSecret: !!offer.secret,
|
||||
answererPeerId: offer.answererPeerId,
|
||||
answered: !!offer.answererPeerId
|
||||
}))
|
||||
}, 200);
|
||||
} catch (err) {
|
||||
console.error('Error getting offers:', err);
|
||||
return c.json({ error: 'Internal server error' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* DELETE /offers/:offerId
|
||||
* Delete an offer
|
||||
*/
|
||||
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 owned by this peer' }, 404);
|
||||
}
|
||||
|
||||
return c.json({ success: true }, 200);
|
||||
} catch (err) {
|
||||
console.error('Error deleting offer:', err);
|
||||
return c.json({ error: 'Internal server error' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /offers/:offerId/answer
|
||||
* Answer an offer
|
||||
*/
|
||||
app.post('/offers/:offerId/answer', authMiddleware, async (c) => {
|
||||
try {
|
||||
const offerId = c.req.param('offerId');
|
||||
const body = await c.req.json();
|
||||
const { sdp, secret } = body;
|
||||
const { sdp } = body;
|
||||
|
||||
if (!sdp) {
|
||||
return c.json({ error: 'Missing required parameter: sdp' }, 400);
|
||||
@@ -531,55 +468,82 @@ export function createApp(storage: Storage, config: Config) {
|
||||
return c.json({ error: 'SDP too large (max 64KB)' }, 400);
|
||||
}
|
||||
|
||||
// Get the service by UUID
|
||||
const service = await storage.getServiceByUuid(uuid);
|
||||
if (!service) {
|
||||
return c.json({ error: 'Service not found' }, 404);
|
||||
}
|
||||
|
||||
// Get available offer from service
|
||||
const serviceOffers = await storage.getOffersForService(service.id);
|
||||
const availableOffer = serviceOffers.find(offer => !offer.answererPeerId);
|
||||
|
||||
if (!availableOffer) {
|
||||
return c.json({ error: 'No available offers' }, 503);
|
||||
}
|
||||
|
||||
const answererPeerId = getAuthenticatedPeerId(c);
|
||||
|
||||
const result = await storage.answerOffer(offerId, answererPeerId, sdp, secret);
|
||||
const result = await storage.answerOffer(availableOffer.id, answererPeerId, sdp);
|
||||
|
||||
if (!result.success) {
|
||||
return c.json({ error: result.error }, 400);
|
||||
}
|
||||
|
||||
return c.json({ success: true }, 200);
|
||||
} catch (err) {
|
||||
console.error('Error answering offer:', err);
|
||||
return c.json({ error: 'Internal server error' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /offers/answers
|
||||
* Get answers for authenticated peer's offers
|
||||
*/
|
||||
app.get('/offers/answers', authMiddleware, async (c) => {
|
||||
try {
|
||||
const peerId = getAuthenticatedPeerId(c);
|
||||
const offers = await storage.getAnsweredOffers(peerId);
|
||||
|
||||
return c.json({
|
||||
answers: offers.map(offer => ({
|
||||
offerId: offer.id,
|
||||
answererId: offer.answererPeerId,
|
||||
sdp: offer.answerSdp,
|
||||
answeredAt: offer.answeredAt
|
||||
}))
|
||||
success: true,
|
||||
offerId: availableOffer.id
|
||||
}, 200);
|
||||
} catch (err) {
|
||||
console.error('Error getting answers:', err);
|
||||
console.error('Error answering service:', err);
|
||||
return c.json({ error: 'Internal server error' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// ===== ICE Candidate Exchange =====
|
||||
/**
|
||||
* GET /services/:uuid/answer
|
||||
* Get answer for a service (offerer polls this)
|
||||
*/
|
||||
app.get('/services/:uuid/answer', authMiddleware, async (c) => {
|
||||
try {
|
||||
const uuid = c.req.param('uuid');
|
||||
const peerId = getAuthenticatedPeerId(c);
|
||||
|
||||
// Get the service by UUID
|
||||
const service = await storage.getServiceByUuid(uuid);
|
||||
if (!service) {
|
||||
return c.json({ error: 'Service not found' }, 404);
|
||||
}
|
||||
|
||||
// Get offers for this service owned by the requesting peer
|
||||
const serviceOffers = await storage.getOffersForService(service.id);
|
||||
const myOffer = serviceOffers.find(offer => offer.peerId === peerId && offer.answererPeerId);
|
||||
|
||||
if (!myOffer || !myOffer.answerSdp) {
|
||||
return c.json({ error: 'Offer not yet answered' }, 404);
|
||||
}
|
||||
|
||||
return c.json({
|
||||
offerId: myOffer.id,
|
||||
answererId: myOffer.answererPeerId,
|
||||
sdp: myOffer.answerSdp,
|
||||
answeredAt: myOffer.answeredAt
|
||||
}, 200);
|
||||
} catch (err) {
|
||||
console.error('Error getting service answer:', err);
|
||||
return c.json({ error: 'Internal server error' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* POST /offers/:offerId/ice-candidates
|
||||
* Add ICE candidates for an offer
|
||||
* POST /services/:uuid/ice-candidates
|
||||
* Add ICE candidates for a service
|
||||
*/
|
||||
app.post('/offers/:offerId/ice-candidates', authMiddleware, async (c) => {
|
||||
app.post('/services/:uuid/ice-candidates', authMiddleware, async (c) => {
|
||||
try {
|
||||
const offerId = c.req.param('offerId');
|
||||
const uuid = c.req.param('uuid');
|
||||
const body = await c.req.json();
|
||||
const { candidates } = body;
|
||||
const { candidates, offerId } = body;
|
||||
|
||||
if (!Array.isArray(candidates) || candidates.length === 0) {
|
||||
return c.json({ error: 'Missing or invalid required parameter: candidates' }, 400);
|
||||
@@ -587,8 +551,27 @@ export function createApp(storage: Storage, config: Config) {
|
||||
|
||||
const peerId = getAuthenticatedPeerId(c);
|
||||
|
||||
// Get the service by UUID
|
||||
const service = await storage.getServiceByUuid(uuid);
|
||||
if (!service) {
|
||||
return c.json({ error: 'Service not found' }, 404);
|
||||
}
|
||||
|
||||
// If offerId is provided, use it; otherwise find the peer's offer
|
||||
let targetOfferId = offerId;
|
||||
if (!targetOfferId) {
|
||||
const serviceOffers = await storage.getOffersForService(service.id);
|
||||
const myOffer = serviceOffers.find(offer =>
|
||||
offer.peerId === peerId || offer.answererPeerId === peerId
|
||||
);
|
||||
if (!myOffer) {
|
||||
return c.json({ error: 'No offer found for this peer' }, 404);
|
||||
}
|
||||
targetOfferId = myOffer.id;
|
||||
}
|
||||
|
||||
// Get offer to determine role
|
||||
const offer = await storage.getOfferById(offerId);
|
||||
const offer = await storage.getOfferById(targetOfferId);
|
||||
if (!offer) {
|
||||
return c.json({ error: 'Offer not found' }, 404);
|
||||
}
|
||||
@@ -596,27 +579,47 @@ export function createApp(storage: Storage, config: Config) {
|
||||
// Determine role
|
||||
const role = offer.peerId === peerId ? 'offerer' : 'answerer';
|
||||
|
||||
const count = await storage.addIceCandidates(offerId, peerId, role, candidates);
|
||||
const count = await storage.addIceCandidates(targetOfferId, peerId, role, candidates);
|
||||
|
||||
return c.json({ count }, 200);
|
||||
return c.json({ count, offerId: targetOfferId }, 200);
|
||||
} catch (err) {
|
||||
console.error('Error adding ICE candidates:', err);
|
||||
console.error('Error adding ICE candidates to service:', err);
|
||||
return c.json({ error: 'Internal server error' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
/**
|
||||
* GET /offers/:offerId/ice-candidates
|
||||
* Get ICE candidates for an offer
|
||||
* GET /services/:uuid/ice-candidates
|
||||
* Get ICE candidates for a service
|
||||
*/
|
||||
app.get('/offers/:offerId/ice-candidates', authMiddleware, async (c) => {
|
||||
app.get('/services/:uuid/ice-candidates', authMiddleware, async (c) => {
|
||||
try {
|
||||
const offerId = c.req.param('offerId');
|
||||
const uuid = c.req.param('uuid');
|
||||
const since = c.req.query('since');
|
||||
const offerId = c.req.query('offerId');
|
||||
const peerId = getAuthenticatedPeerId(c);
|
||||
|
||||
// Get the service by UUID
|
||||
const service = await storage.getServiceByUuid(uuid);
|
||||
if (!service) {
|
||||
return c.json({ error: 'Service not found' }, 404);
|
||||
}
|
||||
|
||||
// If offerId is provided, use it; otherwise find the peer's offer
|
||||
let targetOfferId = offerId;
|
||||
if (!targetOfferId) {
|
||||
const serviceOffers = await storage.getOffersForService(service.id);
|
||||
const myOffer = serviceOffers.find(offer =>
|
||||
offer.peerId === peerId || offer.answererPeerId === peerId
|
||||
);
|
||||
if (!myOffer) {
|
||||
return c.json({ error: 'No offer found for this peer' }, 404);
|
||||
}
|
||||
targetOfferId = myOffer.id;
|
||||
}
|
||||
|
||||
// Get offer to determine role
|
||||
const offer = await storage.getOfferById(offerId);
|
||||
const offer = await storage.getOfferById(targetOfferId);
|
||||
if (!offer) {
|
||||
return c.json({ error: 'Offer not found' }, 404);
|
||||
}
|
||||
@@ -625,16 +628,17 @@ export function createApp(storage: Storage, config: Config) {
|
||||
const targetRole = offer.peerId === peerId ? 'answerer' : 'offerer';
|
||||
const sinceTimestamp = since ? parseInt(since, 10) : undefined;
|
||||
|
||||
const candidates = await storage.getIceCandidates(offerId, targetRole, sinceTimestamp);
|
||||
const candidates = await storage.getIceCandidates(targetOfferId, targetRole, sinceTimestamp);
|
||||
|
||||
return c.json({
|
||||
candidates: candidates.map(c => ({
|
||||
candidate: c.candidate,
|
||||
createdAt: c.createdAt
|
||||
}))
|
||||
})),
|
||||
offerId: targetOfferId
|
||||
}, 200);
|
||||
} catch (err) {
|
||||
console.error('Error getting ICE candidates:', err);
|
||||
console.error('Error getting ICE candidates for service:', err);
|
||||
return c.json({ error: 'Internal server error' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -228,6 +228,60 @@ export function validateServiceFqn(fqn: string): { valid: boolean; error?: strin
|
||||
return { valid: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse semantic version string into components
|
||||
*/
|
||||
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 service name and version
|
||||
*/
|
||||
export function parseServiceFqn(fqn: string): { serviceName: string; version: string } | null {
|
||||
const parts = fqn.split('@');
|
||||
if (parts.length !== 2) return null;
|
||||
|
||||
return {
|
||||
serviceName: parts[0],
|
||||
version: parts[1],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates timestamp is within acceptable range (prevents replay attacks)
|
||||
*/
|
||||
|
||||
@@ -38,6 +38,7 @@ export class D1Storage implements Storage {
|
||||
CREATE TABLE IF NOT EXISTS offers (
|
||||
id TEXT PRIMARY KEY,
|
||||
peer_id TEXT NOT NULL,
|
||||
service_id TEXT,
|
||||
sdp TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
@@ -49,6 +50,7 @@ export class D1Storage implements Storage {
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_offers_peer ON offers(peer_id);
|
||||
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_last_seen ON offers(last_seen);
|
||||
CREATE INDEX IF NOT EXISTS idx_offers_answerer ON offers(answerer_peer_id);
|
||||
@@ -87,20 +89,17 @@ export class D1Storage implements Storage {
|
||||
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 (
|
||||
@@ -401,6 +400,7 @@ export class D1Storage implements Storage {
|
||||
async createService(request: CreateServiceRequest): Promise<{
|
||||
service: Service;
|
||||
indexUuid: string;
|
||||
offers: Offer[];
|
||||
}> {
|
||||
const serviceId = crypto.randomUUID();
|
||||
const indexUuid = crypto.randomUUID();
|
||||
@@ -408,13 +408,12 @@ export class D1Storage implements Storage {
|
||||
|
||||
// Insert service
|
||||
await this.db.prepare(`
|
||||
INSERT INTO services (id, username, service_fqn, offer_id, created_at, expires_at, is_public, metadata)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
INSERT INTO services (id, username, service_fqn, created_at, expires_at, is_public, metadata)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
`).bind(
|
||||
serviceId,
|
||||
request.username,
|
||||
request.serviceFqn,
|
||||
request.offerId,
|
||||
now,
|
||||
request.expiresAt,
|
||||
request.isPublic ? 1 : 0,
|
||||
@@ -434,6 +433,13 @@ export class D1Storage implements Storage {
|
||||
request.expiresAt
|
||||
).run();
|
||||
|
||||
// Create offers with serviceId
|
||||
const offerRequests = request.offers.map(offer => ({
|
||||
...offer,
|
||||
serviceId,
|
||||
}));
|
||||
const offers = await this.createOffers(offerRequests);
|
||||
|
||||
// Touch username to extend expiry
|
||||
await this.touchUsername(request.username);
|
||||
|
||||
@@ -442,16 +448,43 @@ export class D1Storage implements Storage {
|
||||
id: serviceId,
|
||||
username: request.username,
|
||||
serviceFqn: request.serviceFqn,
|
||||
offerId: request.offerId,
|
||||
createdAt: now,
|
||||
expiresAt: request.expiresAt,
|
||||
isPublic: request.isPublic || false,
|
||||
metadata: request.metadata,
|
||||
},
|
||||
indexUuid,
|
||||
offers,
|
||||
};
|
||||
}
|
||||
|
||||
async batchCreateServices(requests: CreateServiceRequest[]): Promise<Array<{
|
||||
service: Service;
|
||||
indexUuid: string;
|
||||
offers: Offer[];
|
||||
}>> {
|
||||
const results = [];
|
||||
for (const request of requests) {
|
||||
const result = await this.createService(request);
|
||||
results.push(result);
|
||||
}
|
||||
return results;
|
||||
}
|
||||
|
||||
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
|
||||
@@ -510,6 +543,20 @@ export class D1Storage implements Storage {
|
||||
return result ? (result as any).uuid : null;
|
||||
}
|
||||
|
||||
async findServicesByName(username: string, serviceName: string): Promise<Service[]> {
|
||||
const result = await this.db.prepare(`
|
||||
SELECT * FROM services
|
||||
WHERE username = ? AND service_fqn LIKE ? AND expires_at > ?
|
||||
ORDER BY created_at DESC
|
||||
`).bind(username, `${serviceName}@%`, Date.now()).all();
|
||||
|
||||
if (!result.results) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return result.results.map(row => this.rowToService(row as any));
|
||||
}
|
||||
|
||||
async deleteService(serviceId: string, username: string): Promise<boolean> {
|
||||
const result = await this.db.prepare(`
|
||||
DELETE FROM services
|
||||
@@ -560,7 +607,6 @@ export class D1Storage implements Storage {
|
||||
id: row.id,
|
||||
username: row.username,
|
||||
serviceFqn: row.service_fqn,
|
||||
offerId: row.offer_id,
|
||||
createdAt: row.created_at,
|
||||
expiresAt: row.expires_at,
|
||||
isPublic: row.is_public === 1,
|
||||
|
||||
@@ -40,6 +40,7 @@ export class SQLiteStorage implements Storage {
|
||||
CREATE TABLE IF NOT EXISTS offers (
|
||||
id TEXT PRIMARY KEY,
|
||||
peer_id TEXT NOT NULL,
|
||||
service_id TEXT,
|
||||
sdp TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
expires_at INTEGER NOT NULL,
|
||||
@@ -47,10 +48,12 @@ export class SQLiteStorage implements Storage {
|
||||
secret TEXT,
|
||||
answerer_peer_id 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_service ON offers(service_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);
|
||||
@@ -84,25 +87,22 @@ export class SQLiteStorage implements Storage {
|
||||
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
|
||||
-- Services table (one service can have multiple offers)
|
||||
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 (
|
||||
@@ -139,8 +139,8 @@ export class SQLiteStorage implements Storage {
|
||||
// Use transaction for atomic creation
|
||||
const transaction = this.db.transaction((offersWithIds: (CreateOfferRequest & { id: string })[]) => {
|
||||
const offerStmt = this.db.prepare(`
|
||||
INSERT INTO offers (id, peer_id, sdp, created_at, expires_at, last_seen, secret)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
INSERT INTO offers (id, peer_id, service_id, sdp, created_at, expires_at, last_seen, secret)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
for (const offer of offersWithIds) {
|
||||
@@ -150,6 +150,7 @@ export class SQLiteStorage implements Storage {
|
||||
offerStmt.run(
|
||||
offer.id,
|
||||
offer.peerId,
|
||||
offer.serviceId || null,
|
||||
offer.sdp,
|
||||
now,
|
||||
offer.expiresAt,
|
||||
@@ -160,6 +161,7 @@ export class SQLiteStorage implements Storage {
|
||||
created.push({
|
||||
id: offer.id,
|
||||
peerId: offer.peerId,
|
||||
serviceId: offer.serviceId || undefined,
|
||||
sdp: offer.sdp,
|
||||
createdAt: now,
|
||||
expiresAt: offer.expiresAt,
|
||||
@@ -426,23 +428,31 @@ export class SQLiteStorage implements Storage {
|
||||
async createService(request: CreateServiceRequest): Promise<{
|
||||
service: Service;
|
||||
indexUuid: string;
|
||||
offers: Offer[];
|
||||
}> {
|
||||
const serviceId = randomUUID();
|
||||
const indexUuid = randomUUID();
|
||||
const now = Date.now();
|
||||
|
||||
// Create offers with serviceId
|
||||
const offerRequests: CreateOfferRequest[] = request.offers.map(offer => ({
|
||||
...offer,
|
||||
serviceId,
|
||||
}));
|
||||
|
||||
const offers = await this.createOffers(offerRequests);
|
||||
|
||||
const transaction = this.db.transaction(() => {
|
||||
// Insert service
|
||||
// Insert service (no offer_id column anymore)
|
||||
const serviceStmt = this.db.prepare(`
|
||||
INSERT INTO services (id, username, service_fqn, offer_id, created_at, expires_at, is_public, metadata)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
INSERT INTO services (id, username, service_fqn, created_at, expires_at, is_public, metadata)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
serviceStmt.run(
|
||||
serviceId,
|
||||
request.username,
|
||||
request.serviceFqn,
|
||||
request.offerId,
|
||||
now,
|
||||
request.expiresAt,
|
||||
request.isPublic ? 1 : 0,
|
||||
@@ -475,16 +485,31 @@ export class SQLiteStorage implements Storage {
|
||||
id: serviceId,
|
||||
username: request.username,
|
||||
serviceFqn: request.serviceFqn,
|
||||
offerId: request.offerId,
|
||||
createdAt: now,
|
||||
expiresAt: request.expiresAt,
|
||||
isPublic: request.isPublic || false,
|
||||
metadata: request.metadata,
|
||||
},
|
||||
indexUuid,
|
||||
offers,
|
||||
};
|
||||
}
|
||||
|
||||
async batchCreateServices(requests: CreateServiceRequest[]): Promise<Array<{
|
||||
service: Service;
|
||||
indexUuid: string;
|
||||
offers: Offer[];
|
||||
}>> {
|
||||
const results = [];
|
||||
|
||||
for (const request of requests) {
|
||||
const result = await this.createService(request);
|
||||
results.push(result);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
async getServiceById(serviceId: string): Promise<Service | null> {
|
||||
const stmt = this.db.prepare(`
|
||||
SELECT * FROM services
|
||||
@@ -547,6 +572,18 @@ export class SQLiteStorage implements Storage {
|
||||
return row ? row.uuid : null;
|
||||
}
|
||||
|
||||
async findServicesByName(username: string, serviceName: string): Promise<Service[]> {
|
||||
const stmt = this.db.prepare(`
|
||||
SELECT * FROM services
|
||||
WHERE username = ? AND service_fqn LIKE ? AND expires_at > ?
|
||||
ORDER BY created_at DESC
|
||||
`);
|
||||
|
||||
const rows = stmt.all(username, `${serviceName}@%`, Date.now()) as any[];
|
||||
|
||||
return rows.map(row => this.rowToService(row));
|
||||
}
|
||||
|
||||
async deleteService(serviceId: string, username: string): Promise<boolean> {
|
||||
const stmt = this.db.prepare(`
|
||||
DELETE FROM services
|
||||
@@ -576,6 +613,7 @@ export class SQLiteStorage implements Storage {
|
||||
return {
|
||||
id: row.id,
|
||||
peerId: row.peer_id,
|
||||
serviceId: row.service_id || undefined,
|
||||
sdp: row.sdp,
|
||||
createdAt: row.created_at,
|
||||
expiresAt: row.expires_at,
|
||||
@@ -595,11 +633,24 @@ export class SQLiteStorage implements Storage {
|
||||
id: row.id,
|
||||
username: row.username,
|
||||
serviceFqn: row.service_fqn,
|
||||
offerId: row.offer_id,
|
||||
createdAt: row.created_at,
|
||||
expiresAt: row.expires_at,
|
||||
isPublic: row.is_public === 1,
|
||||
metadata: row.metadata || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all offers for a service
|
||||
*/
|
||||
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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
export interface Offer {
|
||||
id: string;
|
||||
peerId: string;
|
||||
serviceId?: string; // Optional link to service (null for standalone offers)
|
||||
sdp: string;
|
||||
createdAt: number;
|
||||
expiresAt: number;
|
||||
@@ -33,6 +34,7 @@ export interface IceCandidate {
|
||||
export interface CreateOfferRequest {
|
||||
id?: string;
|
||||
peerId: string;
|
||||
serviceId?: string; // Optional link to service
|
||||
sdp: string;
|
||||
expiresAt: number;
|
||||
secret?: string;
|
||||
@@ -61,13 +63,12 @@ export interface ClaimUsernameRequest {
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a published service
|
||||
* Represents a published service (can have multiple offers)
|
||||
*/
|
||||
export interface Service {
|
||||
id: string; // UUID v4
|
||||
username: string;
|
||||
serviceFqn: string; // com.example.chat@1.0.0
|
||||
offerId: string; // Links to offers table
|
||||
createdAt: number;
|
||||
expiresAt: number;
|
||||
isPublic: boolean;
|
||||
@@ -75,15 +76,22 @@ export interface Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* Request to create a service
|
||||
* Request to create a single service
|
||||
*/
|
||||
export interface CreateServiceRequest {
|
||||
username: string;
|
||||
serviceFqn: string;
|
||||
offerId: string;
|
||||
expiresAt: number;
|
||||
isPublic?: boolean;
|
||||
metadata?: string;
|
||||
offers: CreateOfferRequest[]; // Multiple offers per service
|
||||
}
|
||||
|
||||
/**
|
||||
* Request to create multiple services in batch
|
||||
*/
|
||||
export interface BatchCreateServicesRequest {
|
||||
services: CreateServiceRequest[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -234,15 +242,34 @@ export interface Storage {
|
||||
// ===== Service Management =====
|
||||
|
||||
/**
|
||||
* Creates a new service
|
||||
* @param request Service creation request
|
||||
* @returns Created service with generated ID and index UUID
|
||||
* Creates a new service with offers
|
||||
* @param request Service creation request (includes offers)
|
||||
* @returns Created service with generated ID, index UUID, and created offers
|
||||
*/
|
||||
createService(request: CreateServiceRequest): Promise<{
|
||||
service: Service;
|
||||
indexUuid: string;
|
||||
offers: Offer[];
|
||||
}>;
|
||||
|
||||
/**
|
||||
* Creates multiple services with offers in batch
|
||||
* @param requests Array of service creation requests
|
||||
* @returns Array of created services with IDs, UUIDs, and offers
|
||||
*/
|
||||
batchCreateServices(requests: CreateServiceRequest[]): Promise<Array<{
|
||||
service: Service;
|
||||
indexUuid: string;
|
||||
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
|
||||
@@ -272,6 +299,14 @@ export interface Storage {
|
||||
*/
|
||||
queryService(username: string, serviceFqn: string): Promise<string | null>;
|
||||
|
||||
/**
|
||||
* Finds all services by username and service name (without version)
|
||||
* @param username Username
|
||||
* @param serviceName Service name (e.g., 'com.example.chat')
|
||||
* @returns Array of services with matching service name
|
||||
*/
|
||||
findServicesByName(username: string, serviceName: string): Promise<Service[]>;
|
||||
|
||||
/**
|
||||
* Deletes a service (with ownership verification)
|
||||
* @param serviceId Service ID
|
||||
|
||||
@@ -17,7 +17,7 @@ OFFER_MIN_TTL = "60000" # Min offer TTL: 1 minute
|
||||
MAX_OFFERS_PER_REQUEST = "100" # Max offers per request
|
||||
MAX_TOPICS_PER_OFFER = "50" # Max topics per offer
|
||||
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
|
||||
# Run: npx wrangler secret put AUTH_SECRET
|
||||
|
||||
Reference in New Issue
Block a user