mirror of
https://github.com/xtr-dev/rondevu-server.git
synced 2025-12-16 05:43:23 +00:00
feat: add V2 service publishing and username claiming APIs
- Add POST /services endpoint for publishing services with username verification - Add DELETE /services/:serviceId endpoint for unpublishing services - Add GET /services/:serviceFqn endpoint for service discovery - Add POST /usernames/claim endpoint with Ed25519 signature verification - Add POST /usernames/renew endpoint for extending username TTL - Add GET /usernames/:username endpoint for checking username availability - Add username expiry tracking and cleanup (365-day default TTL) - Add service-to-offer relationship tracking - Add signature verification for username operations - Update storage schema for usernames and services tables - Add comprehensive README documentation for V2 APIs - Update version to 0.8.0 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
@@ -1,9 +1,22 @@
|
||||
import Database from 'better-sqlite3';
|
||||
import { Storage, Offer, IceCandidate, CreateOfferRequest, TopicInfo } from './types.ts';
|
||||
import { randomUUID } from 'crypto';
|
||||
import {
|
||||
Storage,
|
||||
Offer,
|
||||
IceCandidate,
|
||||
CreateOfferRequest,
|
||||
Username,
|
||||
ClaimUsernameRequest,
|
||||
Service,
|
||||
CreateServiceRequest,
|
||||
ServiceInfo,
|
||||
} from './types.ts';
|
||||
import { generateOfferHash } from './hash-id.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
|
||||
*/
|
||||
export class SQLiteStorage implements Storage {
|
||||
@@ -19,10 +32,11 @@ 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 {
|
||||
this.db.exec(`
|
||||
-- Offers table (no topics)
|
||||
CREATE TABLE IF NOT EXISTS offers (
|
||||
id TEXT PRIMARY KEY,
|
||||
peer_id TEXT NOT NULL,
|
||||
@@ -41,22 +55,13 @@ export class SQLiteStorage implements Storage {
|
||||
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 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 (
|
||||
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, -- JSON: RTCIceCandidateInit object
|
||||
candidate TEXT NOT NULL,
|
||||
created_at INTEGER NOT NULL,
|
||||
FOREIGN KEY (offer_id) REFERENCES offers(id) ON DELETE CASCADE
|
||||
);
|
||||
@@ -64,12 +69,62 @@ export class SQLiteStorage implements Storage {
|
||||
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);
|
||||
`);
|
||||
|
||||
// Enable foreign keys
|
||||
this.db.pragma('foreign_keys = ON');
|
||||
}
|
||||
|
||||
// ===== Offer Management =====
|
||||
|
||||
async createOffers(offers: CreateOfferRequest[]): Promise<Offer[]> {
|
||||
const created: Offer[] = [];
|
||||
|
||||
@@ -77,7 +132,7 @@ export class SQLiteStorage implements Storage {
|
||||
const offersWithIds = await Promise.all(
|
||||
offers.map(async (offer) => ({
|
||||
...offer,
|
||||
id: offer.id || await generateOfferHash(offer.sdp, offer.topics),
|
||||
id: offer.id || await generateOfferHash(offer.sdp, []),
|
||||
}))
|
||||
);
|
||||
|
||||
@@ -88,11 +143,6 @@ export class SQLiteStorage implements Storage {
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
const topicStmt = this.db.prepare(`
|
||||
INSERT INTO offer_topics (offer_id, topic)
|
||||
VALUES (?, ?)
|
||||
`);
|
||||
|
||||
for (const offer of offersWithIds) {
|
||||
const now = Date.now();
|
||||
|
||||
@@ -107,16 +157,10 @@ export class SQLiteStorage implements Storage {
|
||||
offer.secret || null
|
||||
);
|
||||
|
||||
// Insert topics
|
||||
for (const topic of offer.topics) {
|
||||
topicStmt.run(offer.id, topic);
|
||||
}
|
||||
|
||||
created.push({
|
||||
id: offer.id,
|
||||
peerId: offer.peerId,
|
||||
sdp: offer.sdp,
|
||||
topics: offer.topics,
|
||||
createdAt: now,
|
||||
expiresAt: offer.expiresAt,
|
||||
lastSeen: now,
|
||||
@@ -129,30 +173,6 @@ export class SQLiteStorage implements Storage {
|
||||
return created;
|
||||
}
|
||||
|
||||
async getOffersByTopic(topic: string, excludePeerIds?: 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(`
|
||||
SELECT * FROM offers
|
||||
@@ -161,7 +181,7 @@ export class SQLiteStorage implements Storage {
|
||||
`);
|
||||
|
||||
const rows = stmt.all(peerId, 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> {
|
||||
@@ -254,9 +274,11 @@ export class SQLiteStorage implements Storage {
|
||||
`);
|
||||
|
||||
const rows = stmt.all(offererPeerId, 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(
|
||||
offerId: string,
|
||||
peerId: string,
|
||||
@@ -275,8 +297,8 @@ export class SQLiteStorage implements Storage {
|
||||
offerId,
|
||||
peerId,
|
||||
role,
|
||||
JSON.stringify(candidates[i]), // Store full object as JSON
|
||||
baseTimestamp + i // Ensure unique timestamps to avoid "since" filtering issues
|
||||
JSON.stringify(candidates[i]),
|
||||
baseTimestamp + i
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -312,85 +334,249 @@ export class SQLiteStorage implements Storage {
|
||||
offerId: row.offer_id,
|
||||
peerId: row.peer_id,
|
||||
role: row.role,
|
||||
candidate: JSON.parse(row.candidate), // Parse JSON back to object
|
||||
candidate: JSON.parse(row.candidate),
|
||||
createdAt: row.created_at,
|
||||
}));
|
||||
}
|
||||
|
||||
async getTopics(limit: number, offset: number, startsWith?: string): Promise<{
|
||||
topics: TopicInfo[];
|
||||
total: number;
|
||||
// ===== Username Management =====
|
||||
|
||||
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;
|
||||
indexUuid: string;
|
||||
}> {
|
||||
const serviceId = randomUUID();
|
||||
const indexUuid = randomUUID();
|
||||
const now = Date.now();
|
||||
|
||||
// Build WHERE clause for startsWith filter
|
||||
const whereClause = startsWith
|
||||
? 'o.expires_at > ? AND ot.topic LIKE ?'
|
||||
: 'o.expires_at > ?';
|
||||
const transaction = this.db.transaction(() => {
|
||||
// Insert service
|
||||
const serviceStmt = this.db.prepare(`
|
||||
INSERT INTO services (id, username, service_fqn, offer_id, created_at, expires_at, is_public, metadata)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
const startsWithPattern = startsWith ? `${startsWith}%` : null;
|
||||
serviceStmt.run(
|
||||
serviceId,
|
||||
request.username,
|
||||
request.serviceFqn,
|
||||
request.offerId,
|
||||
now,
|
||||
request.expiresAt,
|
||||
request.isPublic ? 1 : 0,
|
||||
request.metadata || null
|
||||
);
|
||||
|
||||
// Get total count of topics with active offers
|
||||
const countQuery = `
|
||||
SELECT COUNT(DISTINCT ot.topic) as count
|
||||
FROM offer_topics ot
|
||||
INNER JOIN offers o ON ot.offer_id = o.id
|
||||
WHERE ${whereClause}
|
||||
`;
|
||||
// Insert service index
|
||||
const indexStmt = this.db.prepare(`
|
||||
INSERT INTO service_index (uuid, service_id, username, service_fqn, created_at, expires_at)
|
||||
VALUES (?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
|
||||
const countStmt = this.db.prepare(countQuery);
|
||||
const countParams = startsWith ? [now, startsWithPattern] : [now];
|
||||
const countRow = countStmt.get(...countParams) as any;
|
||||
const total = countRow.count;
|
||||
indexStmt.run(
|
||||
indexUuid,
|
||||
serviceId,
|
||||
request.username,
|
||||
request.serviceFqn,
|
||||
now,
|
||||
request.expiresAt
|
||||
);
|
||||
|
||||
// Get topics with peer counts (paginated)
|
||||
const topicsQuery = `
|
||||
SELECT
|
||||
ot.topic,
|
||||
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 ?
|
||||
`;
|
||||
// Touch username to extend expiry
|
||||
this.touchUsername(request.username);
|
||||
});
|
||||
|
||||
const topicsStmt = this.db.prepare(topicsQuery);
|
||||
const topicsParams = startsWith
|
||||
? [now, startsWithPattern, limit, offset]
|
||||
: [now, limit, offset];
|
||||
const rows = topicsStmt.all(...topicsParams) as any[];
|
||||
transaction();
|
||||
|
||||
const topics = rows.map(row => ({
|
||||
topic: row.topic,
|
||||
activePeers: row.active_peers,
|
||||
return {
|
||||
service: {
|
||||
id: serviceId,
|
||||
username: request.username,
|
||||
serviceFqn: request.serviceFqn,
|
||||
offerId: request.offerId,
|
||||
createdAt: now,
|
||||
expiresAt: request.expiresAt,
|
||||
isPublic: request.isPublic || false,
|
||||
metadata: request.metadata,
|
||||
},
|
||||
indexUuid,
|
||||
};
|
||||
}
|
||||
|
||||
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 getServiceByUuid(uuid: string): Promise<Service | null> {
|
||||
const stmt = this.db.prepare(`
|
||||
SELECT s.* FROM services s
|
||||
INNER JOIN service_index si ON s.id = si.service_id
|
||||
WHERE si.uuid = ? AND s.expires_at > ?
|
||||
`);
|
||||
|
||||
const row = stmt.get(uuid, Date.now()) as any;
|
||||
|
||||
if (!row) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return this.rowToService(row);
|
||||
}
|
||||
|
||||
async listServicesForUsername(username: string): Promise<ServiceInfo[]> {
|
||||
const stmt = this.db.prepare(`
|
||||
SELECT si.uuid, s.is_public, s.service_fqn, s.metadata
|
||||
FROM service_index si
|
||||
INNER JOIN services s ON si.service_id = s.id
|
||||
WHERE si.username = ? AND si.expires_at > ?
|
||||
ORDER BY s.created_at DESC
|
||||
`);
|
||||
|
||||
const rows = stmt.all(username, Date.now()) as any[];
|
||||
|
||||
return rows.map(row => ({
|
||||
uuid: row.uuid,
|
||||
isPublic: row.is_public === 1,
|
||||
serviceFqn: row.is_public === 1 ? row.service_fqn : undefined,
|
||||
metadata: row.is_public === 1 ? row.metadata || undefined : undefined,
|
||||
}));
|
||||
}
|
||||
|
||||
return { topics, total };
|
||||
async queryService(username: string, serviceFqn: string): Promise<string | null> {
|
||||
const stmt = this.db.prepare(`
|
||||
SELECT si.uuid FROM service_index si
|
||||
INNER JOIN services s ON si.service_id = s.id
|
||||
WHERE si.username = ? AND si.service_fqn = ? AND si.expires_at > ?
|
||||
`);
|
||||
|
||||
const row = stmt.get(username, serviceFqn, Date.now()) as any;
|
||||
|
||||
return row ? row.uuid : null;
|
||||
}
|
||||
|
||||
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> {
|
||||
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> {
|
||||
// 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);
|
||||
|
||||
private rowToOffer(row: any): Offer {
|
||||
return {
|
||||
id: row.id,
|
||||
peerId: row.peer_id,
|
||||
sdp: row.sdp,
|
||||
topics,
|
||||
createdAt: row.created_at,
|
||||
expiresAt: row.expires_at,
|
||||
lastSeen: row.last_seen,
|
||||
@@ -400,4 +586,20 @@ export class SQLiteStorage implements Storage {
|
||||
answeredAt: row.answered_at || undefined,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Helper method to convert database row to Service object
|
||||
*/
|
||||
private rowToService(row: any): Service {
|
||||
return {
|
||||
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,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user