upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/docs/how-to/deploy.md
blob: 9117fe250b662e4810560e25461fd95057c187ec (plain)
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
# How-To: Deploy ngit-grasp to Production

**Purpose:** Deploy ngit-grasp to a production NixOS server  
**Difficulty:** Intermediate  
**Time:** 30-60 minutes

---

## Problem

You want to:
- Deploy ngit-grasp to a NixOS server
- Configure it as a systemd service
- Set up reverse proxy (Caddy)
- Ensure proper security and monitoring

---

## Prerequisites

- NixOS server with SSH access
- Flakes enabled on server and local machine
- Domain name configured (DNS pointing to server)
- Basic knowledge of NixOS configuration

---

## Solution

### Step 1: Add ngit-grasp to Your Server's Flake

In your server's `flake.nix`, add ngit-grasp as an input:

```nix
{
  inputs = {
    nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.11";
    ngit-grasp.url = "github:DanConwayDev/ngit-grasp";
    # or use a specific git repository:
    # ngit-grasp.url = "git+https://git.shakespeare.diy/npub.../ngit-grasp.git";
  };

  outputs = { self, nixpkgs, ngit-grasp, ... }@inputs: {
    nixosConfigurations.your-hostname = nixpkgs.lib.nixosSystem {
      system = "x86_64-linux";
      specialArgs = { inherit inputs; };
      modules = [
        ./configuration.nix
        # ... other modules
      ];
    };
  };
}
```

---

### Step 2: Create Service Configuration

Create a new file for your ngit-grasp service (e.g., `services/ngit-grasp.nix`):

```nix
{ inputs, ... }:

{
  imports = [ inputs.ngit-grasp.nixosModules.default ];

  services.ngit-grasp.production = {
    enable = true;
    domain = "ngit.example.com";
    
    # Network
    bindAddress = "127.0.0.1";
    port = 8082;
    
    # Storage
    dataDir = "/persistent/ngit-grasp";
    
    # Identity
    relayName = "My GRASP Relay";
    relayDescription = "A Rust GRASP implementation with proactive sync";
    relayOwnerNsecFile = "/persistent/ngit-grasp/relay-owner.nsec";
    
    # Sync - bootstrap from relay.ngit.dev
    syncBootstrapRelayUrl = "wss://relay.ngit.dev";
    
    # Metrics
    metricsEnabled = true;
    
    # Logging
    logLevel = "info";
  };

  # Caddy reverse proxy
  services.caddy.virtualHosts."ngit.example.com" = {
    extraConfig = ''
      reverse_proxy 127.0.0.1:8082 {
        header_down X-Real-IP {http.request.remote}
        header_down X-Forwarded-For {http.request.remote}
      }
    '';
  };
}
```

**Key configuration options:**

- **Instance name** (`production`): Can be any name. Used for systemd service (`ngit-grasp-production`)
- **domain**: Your relay's domain (used in GRASP validation)
- **port**: Local port (use reverse proxy for HTTPS)
- **dataDir**: Where git repos and database are stored
- **relayOwnerNsecFile**: Path to file containing relay owner's nsec
  - If file doesn't exist, ngit-grasp will auto-generate one
  - Alternative: `relayOwnerNsec = "nsec1..."` (less secure, in nix store)
- **syncBootstrapRelayUrl**: Bootstrap relay to sync from on startup

See [nix/example-configuration.nix](../../nix/example-configuration.nix) for more examples.

---

### Step 3: Import the Service

Import your service configuration in your main configuration file:

```nix
# In configuration.nix or services/default.nix
{
  imports = [
    ./services/ngit-grasp.nix
    # ... other services
  ];
}
```

---

### Step 4: Update Flake Lock

```bash
cd /path/to/server/config
nix flake update ngit-grasp
git add flake.lock
git commit -m "Add ngit-grasp and update flake.lock"
```

---

### Step 5: Validate Configuration

Before deploying, validate the configuration builds:

```bash
nix flake check
```

---

### Step 6: Deploy to Server

Deploy the new configuration to your server:

```bash
# Build and switch in one command (builds on server)
nixos-rebuild switch --flake .#your-hostname \
  --target-host user@server.example.com \
  --use-remote-sudo \
  --build-host user@server.example.com
```

**Alternative:** Build locally, then deploy:

```bash
# Build locally
nixos-rebuild build --flake .#your-hostname

# Deploy to server
nixos-rebuild switch --flake .#your-hostname \
  --target-host user@server.example.com \
  --use-remote-sudo
```

**Note:** Building locally requires your machine to trust the server's nix signing key.

---

### Step 7: Verify Deployment

SSH to the server and check the service:

```bash
ssh user@server.example.com

# Check service status
systemctl status ngit-grasp-production

# View logs
journalctl -u ngit-grasp-production -f

# Check if listening on port
ss -tlnp | grep 8082
```

---

### Step 8: Test Functionality

From your local machine, test the relay:

```bash
# Test NIP-11 relay info
curl https://ngit.example.com -H "Accept: application/nostr+json" | jq

# Test WebSocket connection
websocat wss://ngit.example.com
# Then type: ["REQ","test",{}]
# Should receive events

# Test git clone (if you have repos)
git ls-remote https://ngit.example.com/<npub>/<repo>.git
```

---

## Configuration Options

### Required
- `enable` - Enable this instance
- `domain` - Domain where relay is hosted

### Network
- `bindAddress` - IP to bind to (default: "127.0.0.1")
- `port` - Port to listen on (default: 7334)

### Storage
- `dataDir` - Base directory for data (default: /var/lib/ngit-grasp-{name})
- `databaseBackend` - "lmdb" | "memory" (default: "lmdb")

### Identity
- `relayName` - Relay name for NIP-11 (default: "{domain} grasp relay")
- `relayDescription` - Relay description
- `relayOwnerNsecFile` - Path to file with relay owner nsec (recommended)
- `relayOwnerNsec` - Inline nsec (less secure)

### Sync
- `syncBootstrapRelayUrl` - Bootstrap relay URL (optional)
- `syncDisableNegentropy` - Disable NIP-77 negentropy (default: false)
- `syncMaxBackoffSecs` - Max backoff for reconnection (default: 3600)
- `syncDisconnectCheckIntervalSecs` - Check interval (default: 60)
- `syncBaseBackoffSecs` - Base backoff time (default: 5)

### Metrics
- `metricsEnabled` - Enable /metrics endpoint (default: true)
- `metricsConnectionPerIpAbuseThreshold` - Abuse threshold (default: 10)
- `metricsTopNRepos` - Number of top repos to track (default: 10)

### Logging
- `logLevel` - "trace" | "debug" | "info" | "warn" | "error" (default: "info")

### Security
- `user` - User to run as (default: "ngit-grasp-{name}")
- `group` - Group to run as (default: "ngit-grasp")

See [nix/module.nix](../../nix/module.nix) for complete option definitions.

---

## Systemd Service

The NixOS module creates a systemd service: `ngit-grasp-{instance-name}`

```bash
# Start/stop/restart
systemctl start ngit-grasp-production
systemctl stop ngit-grasp-production
systemctl restart ngit-grasp-production

# Enable/disable autostart
systemctl enable ngit-grasp-production
systemctl disable ngit-grasp-production

# View logs
journalctl -u ngit-grasp-production -f
journalctl -u ngit-grasp-production --since "1 hour ago"

# Check status
systemctl status ngit-grasp-production
```

---

## Multiple Instances

You can run multiple instances on the same server:

```nix
services.ngit-grasp = {
  production = {
    enable = true;
    domain = "ngit.example.com";
    port = 8082;
    dataDir = "/persistent/ngit-production";
  };
  
  staging = {
    enable = true;
    domain = "ngit-staging.example.com";
    port = 8083;
    dataDir = "/persistent/ngit-staging";
    logLevel = "debug";
  };
};
```

Each instance:
- Runs as separate systemd service: `ngit-grasp-production`, `ngit-grasp-staging`
- Has its own user: `ngit-grasp-production`, `ngit-grasp-staging`
- Stores data in separate directory
- Can have different configuration

---

## Troubleshooting

### Service won't start

**Check logs:**
```bash
journalctl -u ngit-grasp-production -n 50
```

**Common issues:**
- Port already in use: Check with `ss -tlnp | grep 8082`
- Data directory permissions: Should be owned by service user
- Invalid nsec file: Check file exists and contains valid nsec

### Can't connect via WebSocket

**Check:**
- Service is running: `systemctl status ngit-grasp-production`
- Firewall allows connections: `nix-shell -p nmap --run "nmap -p 443 ngit.example.com"`
- Caddy is configured correctly: `systemctl status caddy`
- DNS resolves: `dig ngit.example.com`

### Sync not working

**Check logs for sync errors:**
```bash
journalctl -u ngit-grasp-production | grep -i sync
```

**Common issues:**
- Bootstrap relay URL incorrect or unreachable
- Network connectivity issues
- Bootstrap relay doesn't support negentropy (disable with `syncDisableNegentropy = true`)

### High memory/CPU usage

**Monitor metrics:**
```bash
curl http://localhost:8082/metrics
```

**Tune configuration:**
- Reduce `metricsTopNRepos`
- Increase `syncMaxBackoffSecs`
- Tune `syncMaxBackoffSecs` for your network conditions

---

## Rollback

If deployment fails, rollback to previous configuration:

```bash
# On the server
nixos-rebuild switch --rollback

# Or remotely
nixos-rebuild switch --rollback \
  --target-host user@server.example.com \
  --use-remote-sudo
```

---

## Upgrading

To upgrade ngit-grasp:

```bash
# Update flake input
nix flake update ngit-grasp

# Review changes
git diff flake.lock

# Commit
git add flake.lock
git commit -m "Update ngit-grasp"

# Deploy
nixos-rebuild switch --flake .#your-hostname \
  --target-host user@server.example.com \
  --use-remote-sudo \
  --build-host user@server.example.com
```

---

## Security Hardening

The NixOS module includes systemd hardening:

- `NoNewPrivileges = true` - Prevents privilege escalation
- `ProtectSystem = "strict"` - Read-only filesystem except dataDir
- `ProtectHome = true` - No access to home directories
- `PrivateTmp = true` - Private /tmp
- `RestrictAddressFamilies` - Only allow needed network families
- `SystemCallFilter` - Restrict system calls

Additional recommendations:

1. **Use nsec file instead of inline:**
   ```nix
   relayOwnerNsecFile = "/persistent/ngit-grasp/relay-owner.nsec";
   # NOT: relayOwnerNsec = "nsec1...";  # Ends up in nix store!
   ```

2. **Restrict data directory permissions:**
   ```bash
   chmod 750 /persistent/ngit-grasp
   chown ngit-grasp-production:ngit-grasp /persistent/ngit-grasp
   ```

3. **Use HTTPS (reverse proxy required):**
   - ngit-grasp binds to localhost by default
   - Use Caddy/nginx for TLS termination
   - Caddy handles certificates automatically

4. **Monitor logs regularly:**
   ```bash
   journalctl -u ngit-grasp-production --since today | grep -i error
   ```

---

## Monitoring

### Prometheus Metrics

ngit-grasp exposes Prometheus metrics at `/metrics`:

```bash
curl http://localhost:8082/metrics
```

See [Prometheus Setup](./prometheus-setup.md) for complete monitoring guide.

### Basic Health Checks

```bash
# Check if service is running
systemctl is-active ngit-grasp-production

# Check if port is listening
nc -zv localhost 8082

# Check relay info
curl https://ngit.example.com -H "Accept: application/nostr+json"

# Check disk usage
du -sh /persistent/ngit-grasp/*
```

---

## Related Documentation

- [Configuration Reference](../reference/configuration.md) - All configuration options
- [NixOS Module](../../nix/module.nix) - Module source code
- [Example Configuration](../../nix/example-configuration.nix) - More examples
- [Prometheus Setup](./prometheus-setup.md) - Monitoring guide
- [Nix Flakes How-To](./nix-flakes.md) - Nix development environment

---

*Part of the [ngit-grasp how-to guides](./)*