1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
|
/// HTTP Server Module
///
/// Provides hyper HTTP server with WebSocket upgrade support for the Nostr relay.
pub mod landing;
pub mod nip11;
use std::future::Future;
use std::net::SocketAddr;
use std::pin::Pin;
use std::sync::Arc;
use base64::Engine;
use http_body_util::{BodyExt, Full};
use hyper::body::{Bytes, Incoming};
use hyper::header::{CONNECTION, SEC_WEBSOCKET_ACCEPT, UPGRADE};
use hyper::server::conn::http1;
use hyper::service::Service;
use hyper::{Method, Request, Response};
use hyper_util::rt::TokioIo;
use nostr_relay_builder::LocalRelay;
use nostr_sdk::hashes::sha1::Hash as Sha1Hash;
use nostr_sdk::hashes::{Hash, HashEngine};
use nostr_sdk::PublicKey;
use tokio::net::TcpListener;
use crate::config::Config;
use crate::git;
use crate::metrics::Metrics;
use crate::nostr::builder::{Nip34WritePolicy, SharedDatabase};
use crate::purgatory::Purgatory;
use crate::sync::rejected_index::RejectedEventsIndex;
/// CORS headers required by GRASP-01 specification (lines 40-47)
const CORS_ALLOW_ORIGIN: &str = "*";
const CORS_ALLOW_METHODS: &str = "GET, POST";
const CORS_ALLOW_HEADERS: &str = "Content-Type";
/// Embedded icon image (Grasp logo)
const ICON_PNG: &[u8] = include_bytes!("../../static/icon.png");
/// Extract npub and identifier from a repository URL path (no git subpath required)
///
/// Parses paths like `/<npub>/<identifier>.git` (for repository webpage/404)
///
/// Returns (npub, identifier) if the path matches a repository URL pattern
fn parse_repo_url(path: &str) -> Option<(&str, &str)> {
// Remove leading slash
let path = path.strip_prefix('/').unwrap_or(path);
// Split into components
let parts: Vec<&str> = path.split('/').collect();
// Must be exactly 2 parts: npub and repo.git (no subpath)
if parts.len() != 2 {
return None;
}
let npub = parts[0];
let repo_part = parts[1];
// The repo part must end with .git
if !repo_part.ends_with(".git") {
return None;
}
// Must have an npub that looks valid (starts with npub1)
if !npub.starts_with("npub1") {
return None;
}
// Extract identifier (remove .git suffix)
let identifier = repo_part.strip_suffix(".git").unwrap_or(repo_part);
// Identifier must not be empty
if identifier.is_empty() {
return None;
}
Some((npub, identifier))
}
/// Add CORS headers to a response builder
fn add_cors_headers(builder: hyper::http::response::Builder) -> hyper::http::response::Builder {
builder
.header("Access-Control-Allow-Origin", CORS_ALLOW_ORIGIN)
.header("Access-Control-Allow-Methods", CORS_ALLOW_METHODS)
.header("Access-Control-Allow-Headers", CORS_ALLOW_HEADERS)
}
/// HTTP Service that serves both WebSocket (relay) and HTML landing page
struct HttpService {
relay: LocalRelay,
config: Config,
remote: SocketAddr,
/// Database reference for direct queries (e.g., push authorization)
database: SharedDatabase,
/// Optional metrics for Prometheus endpoint
metrics: Option<Arc<Metrics>>,
/// Purgatory for event/git coordination
purgatory: Arc<Purgatory>,
/// Write policy for re-processing hot-cache events after git push promotion
write_policy: Arc<Nip34WritePolicy>,
/// Rejected events index for hot-cache re-processing after git push promotion
rejected_events_index: Arc<RejectedEventsIndex>,
}
impl HttpService {
fn new(
relay: LocalRelay,
config: Config,
remote: SocketAddr,
database: SharedDatabase,
metrics: Option<Arc<Metrics>>,
purgatory: Arc<Purgatory>,
write_policy: Arc<Nip34WritePolicy>,
rejected_events_index: Arc<RejectedEventsIndex>,
) -> Self {
Self {
relay,
config,
remote,
database,
metrics,
purgatory,
write_policy,
rejected_events_index,
}
}
}
impl Service<Request<Incoming>> for HttpService {
type Response = Response<Full<Bytes>>;
type Error = String;
type Future = Pin<Box<dyn Future<Output = Result<Self::Response, Self::Error>> + Send>>;
fn call(&self, req: Request<Incoming>) -> Self::Future {
let base = add_cors_headers(Response::builder().header("server", "ngit-grasp"));
let path = req.uri().path().to_string();
let query = req.uri().query().map(|s| s.to_string());
let method = req.method().clone();
let git_data_path = self.config.effective_git_data_path();
let database = self.database.clone();
let purgatory = self.purgatory.clone();
let write_policy = self.write_policy.clone();
let rejected_events_index = self.rejected_events_index.clone();
// Handle OPTIONS preflight requests (CORS)
// GRASP-01 spec line 47: Respond to OPTIONS with 204 No Content
if method == Method::OPTIONS {
return Box::pin(async move {
Ok(
add_cors_headers(Response::builder().header("server", "ngit-grasp"))
.status(204)
.body(Full::new(Bytes::new()))
.unwrap(),
)
});
}
// Check for Git HTTP requests first
if let Some((npub, identifier, subpath)) = git::parse_git_url(&path) {
let npub = npub.to_string();
let identifier = identifier.to_string();
let subpath = subpath.to_string();
// Extract Git-Protocol header for protocol v2 support
let git_protocol = req
.headers()
.get("git-protocol")
.and_then(|v| v.to_str().ok())
.map(|s| s.to_string());
// Extract Content-Encoding header to handle gzip-compressed request bodies
// Modern git clients send gzip-compressed POST bodies for efficiency
let content_encoding = req
.headers()
.get("content-encoding")
.and_then(|v| v.to_str().ok())
.map(|s| s.to_lowercase());
tracing::debug!(
"Git request: {} {} (npub={}, id={}, subpath={}, protocol={:?}, encoding={:?})",
method,
path,
npub,
identifier,
subpath,
git_protocol,
content_encoding
);
let repo_path = git::resolve_repo_path(&git_data_path, &npub, &identifier);
let metrics_clone = self.metrics.clone();
let relay = self.relay.clone();
return Box::pin(async move {
// Collect request body once before the match statement
let raw_body = req
.collect()
.await
.map(|collected| collected.to_bytes())
.unwrap_or_else(|_| Bytes::new());
// Decompress gzip-encoded request bodies
// Git clients send Content-Encoding: gzip for POST requests
let body_bytes = if content_encoding.as_deref() == Some("gzip") {
use flate2::read::GzDecoder;
use std::io::Read;
let mut decoder = GzDecoder::new(&raw_body[..]);
let mut decompressed = Vec::new();
match decoder.read_to_end(&mut decompressed) {
Ok(_) => {
tracing::debug!(
"Decompressed gzip body: {} -> {} bytes",
raw_body.len(),
decompressed.len()
);
Bytes::from(decompressed)
}
Err(e) => {
tracing::warn!("Failed to decompress gzip body: {}", e);
// Fall back to raw body (might work if not actually gzip)
raw_body
}
}
} else {
raw_body
};
let result = match (method.as_ref(), subpath.as_str()) {
// GET /info/refs?service=git-upload-pack or git-receive-pack
(m, sp) if m == Method::GET && sp.starts_with("info/refs") => {
// Parse query string for service parameter
let service = query
.as_deref()
.unwrap_or("")
.strip_prefix("service=")
.and_then(git::protocol::GitService::from_query_param);
match service {
Some(svc) => {
let result = git::handlers::handle_info_refs(
repo_path,
svc,
git_protocol.as_deref(),
)
.await;
// Track operation
if let Some(ref m) = metrics_clone {
let status = if result.is_ok() { "success" } else { "error" };
let operation = match svc {
git::protocol::GitService::UploadPack => "fetch",
git::protocol::GitService::ReceivePack => "push",
};
m.record_git_operation(operation, status);
}
result
}
None => Err(git::handlers::GitError::RepositoryNotFound),
}
}
// POST /git-upload-pack (clone/fetch)
(m, "git-upload-pack") if m == Method::POST => {
let result = git::handlers::handle_upload_pack(
repo_path,
body_bytes,
git_protocol.as_deref(),
)
.await;
if let Some(ref m) = metrics_clone {
let status = if result.is_ok() { "success" } else { "error" };
m.record_git_operation("clone", status);
}
result
}
// POST /git-receive-pack (push) - with GRASP authorization via database
(m, "git-receive-pack") if m == Method::POST => {
// Convert npub (bech32) to hex pubkey for authorization
let owner_pubkey_hex = match PublicKey::parse(&npub) {
Ok(pk) => pk.to_hex(),
Err(e) => {
tracing::warn!("Invalid npub in URL {}: {}", npub, e);
// Track failed push due to invalid npub
if let Some(ref m) = metrics_clone {
m.record_git_operation("push", "error");
}
return Ok(add_cors_headers(Response::builder())
.status(hyper::StatusCode::BAD_REQUEST)
.body(Full::new(Bytes::from(format!("Invalid npub: {}", e))))
.unwrap());
}
};
let result = git::handlers::handle_receive_pack(
repo_path,
body_bytes.clone(),
database.clone(),
relay.clone(),
&identifier,
&owner_pubkey_hex,
purgatory.clone(),
&git_data_path,
git_protocol.as_deref(),
write_policy.clone(),
rejected_events_index.clone(),
)
.await;
if let Some(ref m) = metrics_clone {
let status = if result.is_ok() { "success" } else { "error" };
m.record_git_operation("push", status);
}
result
}
_ => Err(git::handlers::GitError::RepositoryNotFound),
};
match result {
Ok(response) => {
// Add CORS headers to successful Git responses
let (parts, body) = response.into_parts();
Ok(add_cors_headers(Response::builder().status(parts.status))
.header(
"content-type",
parts
.headers
.get("content-type")
.and_then(|v| v.to_str().ok())
.unwrap_or("application/octet-stream"),
)
.header(
"cache-control",
parts
.headers
.get("cache-control")
.and_then(|v| v.to_str().ok())
.unwrap_or("no-cache"),
)
.body(body)
.unwrap())
}
Err(e) => {
tracing::error!("Git handler error: {}", e);
let error_msg = format!("Git error: {}", e);
Ok(add_cors_headers(Response::builder())
.status(e.status_code())
.body(Full::new(Bytes::from(error_msg)))
.unwrap())
}
}
});
}
// Check for NIP-11 relay information request (Accept: application/nostr+json)
if let Some(accept) = req.headers().get("accept") {
if accept
.to_str()
.map(|s| s.contains("application/nostr+json"))
.unwrap_or(false)
{
let doc = nip11::RelayInformationDocument::from_config(&self.config);
let json = doc.to_json().unwrap_or_else(|e| {
tracing::error!("Failed to serialize NIP-11 document: {}", e);
"{}".to_string()
});
tracing::debug!(
"Serving NIP-11 relay information document to {}",
self.remote
);
return Box::pin(async move {
Ok(
add_cors_headers(Response::builder().header("server", "ngit-grasp"))
.status(200)
.header("content-type", "application/nostr+json")
.body(Full::new(Bytes::from(json)))
.unwrap(),
)
});
}
}
// Check for repository URL pattern (e.g., /npub/repo.git without subpath)
// GRASP-01: "SHOULD serve a webpage at the same endpoint linking to git nostr client(s)
// to browse the repository and a 404 page for repositories it doesn't host"
if let Some((npub, identifier)) = parse_repo_url(&path) {
let npub = npub.to_string();
let identifier = identifier.to_string();
let config = self.config.clone();
let repo_path = git::resolve_repo_path(&git_data_path, &npub, &identifier);
tracing::debug!(
"Repository URL request: {} (npub={}, id={}, path={:?})",
path,
npub,
identifier,
repo_path
);
return Box::pin(async move {
// Check if repository exists
if repo_path.exists() {
// Serve repository webpage
let html = landing::get_repo_html(&config, &npub, &identifier);
Ok(
add_cors_headers(Response::builder().header("server", "ngit-grasp"))
.status(200)
.header("content-type", "text/html; charset=utf-8")
.body(Full::new(Bytes::from(html)))
.unwrap(),
)
} else {
// Serve 404 page for non-existent repository
let html = landing::get_404_html(&config, &npub, &identifier);
Ok(
add_cors_headers(Response::builder().header("server", "ngit-grasp"))
.status(404)
.header("content-type", "text/html; charset=utf-8")
.body(Full::new(Bytes::from(html)))
.unwrap(),
)
}
});
}
// Check if this is a WebSocket upgrade request
if let (Some(c), Some(w)) = (
req.headers().get("connection"),
req.headers().get("upgrade"),
) {
if c.to_str()
.map(|s| s.to_lowercase() == "upgrade")
.unwrap_or(false)
&& w.to_str()
.map(|s| s.to_lowercase() == "websocket")
.unwrap_or(false)
{
let key = req.headers().get("sec-websocket-key");
let derived = key.map(|k| derive_accept_key(k.as_bytes()));
let addr = self.remote;
let relay = self.relay.clone();
let metrics_clone = self.metrics.clone();
tokio::spawn(async move {
match hyper::upgrade::on(req).await {
Ok(upgraded) => {
tracing::info!("WebSocket connection established from {}", addr);
// Track connection
if let Some(ref m) = metrics_clone {
m.connection_tracker().on_connect(addr.ip());
m.record_websocket_connection();
}
if let Err(e) =
relay.take_connection(TokioIo::new(upgraded), addr).await
{
tracing::error!("Relay error for {}: {}", addr, e);
}
tracing::info!("WebSocket connection closed for {}", addr);
// Untrack connection
if let Some(ref m) = metrics_clone {
m.connection_tracker().on_disconnect(addr.ip());
}
}
Err(e) => tracing::error!("Upgrade error: {}", e),
}
});
return Box::pin(async move {
Ok(base
.status(101)
.header(CONNECTION, "upgrade")
.header(UPGRADE, "websocket")
.header(SEC_WEBSOCKET_ACCEPT, derived.unwrap())
.body(Full::new(Bytes::new()))
.unwrap())
});
}
}
// Serve Prometheus metrics if enabled
if path == "/metrics" {
if let Some(ref metrics) = self.metrics {
let metrics = metrics.clone();
return Box::pin(async move {
let output = metrics.render();
Ok(
add_cors_headers(Response::builder().header("server", "ngit-grasp"))
.status(200)
.header("content-type", "text/plain; version=0.0.4; charset=utf-8")
.body(Full::new(Bytes::from(output)))
.unwrap(),
)
});
} else {
// Metrics disabled
return Box::pin(async move {
Ok(
add_cors_headers(Response::builder().header("server", "ngit-grasp"))
.status(404)
.body(Full::new(Bytes::from("Metrics disabled")))
.unwrap(),
)
});
}
}
// Serve static icon at /icon.png
if path == "/icon.png" {
return Box::pin(async move {
Ok(
add_cors_headers(Response::builder().header("server", "ngit-grasp"))
.status(200)
.header("content-type", "image/png")
.header("cache-control", "public, max-age=86400")
.body(Full::new(Bytes::from_static(ICON_PNG)))
.unwrap(),
)
});
}
// Only serve landing page for root path "/", 404 for everything else
let config = self.config.clone();
Box::pin(async move {
if path == "/" {
// Serve landing page for root
let html = landing::get_html(&config);
Ok(
add_cors_headers(Response::builder().header("server", "ngit-grasp"))
.status(200)
.header("content-type", "text/html; charset=utf-8")
.body(Full::new(Bytes::from(html)))
.unwrap(),
)
} else {
// Serve generic 404 for unknown paths
let html = landing::get_generic_404_html(&config, &path);
Ok(
add_cors_headers(Response::builder().header("server", "ngit-grasp"))
.status(404)
.header("content-type", "text/html; charset=utf-8")
.body(Full::new(Bytes::from(html)))
.unwrap(),
)
}
})
}
}
/// Derive the `Sec-WebSocket-Accept` response header from a `Sec-WebSocket-Key` request header
fn derive_accept_key(request_key: &[u8]) -> String {
const WS_GUID: &[u8] = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
let mut engine = Sha1Hash::engine();
engine.input(request_key);
engine.input(WS_GUID);
let hash: Sha1Hash = Sha1Hash::from_engine(engine);
base64::prelude::BASE64_STANDARD.encode(hash)
}
/// Start the HTTP server with integrated Nostr relay
///
/// # Arguments
/// * `config` - Server configuration
/// * `relay` - The LocalRelay for WebSocket connections
/// * `database` - The database for direct queries (e.g., push authorization)
/// * `metrics` - Optional metrics for Prometheus endpoint
/// * `purgatory` - Purgatory for event/git coordination
/// * `write_policy` - Write policy for re-processing hot-cache events after git push promotion
/// * `rejected_events_index` - Rejected events index for hot-cache re-processing
pub async fn run_server(
config: Config,
relay: LocalRelay,
database: SharedDatabase,
metrics: Option<Arc<Metrics>>,
purgatory: Arc<Purgatory>,
write_policy: Arc<Nip34WritePolicy>,
rejected_events_index: Arc<RejectedEventsIndex>,
) -> anyhow::Result<()> {
let bind_addr: SocketAddr = config.bind_address.parse()?;
tracing::info!("Starting HTTP server on {}", bind_addr);
tracing::info!("Relay name: {}", config.relay_name());
tracing::info!("Domain: {}", config.domain);
let listener = TcpListener::bind(&bind_addr).await?;
loop {
let (socket, addr) = listener.accept().await?;
let io = TokioIo::new(socket);
let service = HttpService::new(
relay.clone(),
config.clone(),
addr,
database.clone(),
metrics.clone(),
purgatory.clone(),
write_policy.clone(),
rejected_events_index.clone(),
);
tokio::spawn(async move {
if let Err(e) = http1::Builder::new()
.serve_connection(io, service)
.with_upgrades()
.await
{
tracing::error!("Failed to handle request from {}: {}", addr, e);
}
});
}
}
|