forked from TheCryptoDonkey/DonkeyRide
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
8718 lines (7907 loc) · 353 KB
/
Copy pathserver.js
File metadata and controls
8718 lines (7907 loc) · 353 KB
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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==========================================
// DONKEYRIDE RELAY OPERATOR SERVER
// Anyone can run this to operate a stake relay
// Operators earn 0.5% of ride value for providing infrastructure
// ==========================================
// Load environment variables
require('dotenv').config();
const express = require('express');
const cors = require('cors');
const WebSocket = require('ws');
// nostr-tools' SimplePool references a global WebSocket. Node < 21 has none,
// so without this every relay read and write silently fails and the whole
// Nostr layer becomes inert. Set it before any pool is constructed.
if (typeof globalThis.WebSocket === 'undefined') {
globalThis.WebSocket = WebSocket;
}
const Redis = require('redis');
const { PaymentProviderFactory, ResilientStakeManager } = require('./payment-providers/factory');
const reputation = require('./src/nostr/reputation');
const stakeEvents = require('./src/nostr/stake-events');
const disputeEvents = require('./src/nostr/dispute-events');
const operatorAnnounce = require('./src/nostr/operator-announce');
const pushService = require('./src/push');
const { validateNIP98Auth } = require('./middleware/nip98-auth');
const { getPublicKey: nostrGetPublicKey, nip19 } = require('nostr-tools');
const {
publicRateLimiter: enforcePublicRateLimit,
authenticatedRateLimiter: enforceAuthenticatedRateLimit,
rideCreationLimiter: enforceRideCreationLimit,
stakeLimiter: enforceStakeLimit
} = require('./middleware/rate-limit');
const {
getBitcoinPrice,
estimateTripCost,
fetchBitcoinPrices,
satsToFiat
} = require('./src/pricing/fiat-conversion');
const { RideManager, RideStatus } = require('./src/ride-manager');
const { TaskManager } = require('./src/task-manager');
const { loadProfile, listProfiles } = require('./src/domain-profiles');
const { getRoute } = require('./src/osrm-routing');
const { safeErrorMessage } = require('./src/log-redact');
const { createTaskStore } = require('./src/storage/task-store');
const {
createOperatorPolicy,
evaluateDriverAdmission,
publicOperatorPolicy,
admissionNeedsCredentials
} = require('./src/operator-policy');
const app = express();
// Behind Caddy/nginx the client IP arrives via X-Forwarded-For; without
// trust proxy every user shares the proxy's IP in one rate-limit bucket.
app.set('trust proxy', 1);
// CORS: operator switching means a PWA served by operator A must be able to
// call operator B. This API uses no cookies; participant data is protected
// by a request signature, so allowing a browser origin does not grant it an
// identity. Operators can disable federation CORS and use ALLOWED_ORIGINS.
const allowedOrigins = (process.env.ALLOWED_ORIGINS || 'capacitor://localhost,http://localhost,https://localhost,http://localhost:5173,http://localhost:3000')
.split(',').map(o => o.trim()).filter(Boolean);
const federationCorsEnabled = (process.env.FEDERATION_CORS || 'true').toLowerCase() !== 'false';
app.use(cors({
origin: (origin, callback) => {
// Non-browser clients and same-origin requests send no Origin header
if (!origin || federationCorsEnabled || allowedOrigins.includes(origin)) {
return callback(null, true);
}
return callback(null, false);
},
maxAge: 86400
}));
// Minimal security headers (no external dependency)
app.use((req, res, next) => {
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
res.setHeader('Referrer-Policy', 'no-referrer');
next();
});
// Body limit is small by default; only the proof route accepts photos.
// rawBody is captured for NIP-98 payload-tag verification.
const captureRawBody = (req, res, buf) => { req.rawBody = buf; };
const proofBodyParser = express.json({ limit: '2mb', verify: captureRawBody });
const defaultBodyParser = express.json({ limit: '100kb', verify: captureRawBody });
app.use((req, res, next) => {
const parser = /\/proof$/.test(req.path) ? proofBodyParser : defaultBodyParser;
parser(req, res, next);
});
app.use(express.static('public')); // Serve demo.html and other static files (legacy)
const rateLimitingEnabled = (process.env.ENABLE_RATE_LIMITING || 'true').toLowerCase() !== 'false';
const noRateLimit = (req, res, next) => next();
// ENABLE_RATE_LIMITING=false is used by local/test operators and must mean
// every limiter. Previously it disabled only the catch-all authenticated
// gate while route-level public, creation and stake limiters kept returning
// 429s — a browser suite could exhaust the shared IP bucket before a rider
// even reached the fare screen.
const publicRateLimiter = rateLimitingEnabled ? enforcePublicRateLimit : noRateLimit;
const authenticatedRateLimiter = rateLimitingEnabled ? enforceAuthenticatedRateLimit : noRateLimit;
const rideCreationLimiter = rateLimitingEnabled ? enforceRideCreationLimit : noRateLimit;
const stakeLimiter = rateLimitingEnabled ? enforceStakeLimit : noRateLimit;
if (!rateLimitingEnabled) {
console.warn('\u26A0\uFE0F Rate limiting DISABLED via ENABLE_RATE_LIMITING=false');
}
// Domain-agnostic route aliases: /api/tasks/* → /api/rides/*, /api/providers/* → /api/drivers/*
app.use((req, res, next) => {
if (req.path.startsWith('/api/tasks')) {
req.url = req.url.replace('/api/tasks', '/api/rides');
} else if (req.path.startsWith('/api/providers')) {
req.url = req.url.replace('/api/providers', '/api/drivers');
}
next();
});
// ==========================================
// NIP-98 AUTHENTICATION GATE
// When ENABLE_NIP98_AUTH=true, every mutating API route requires a valid
// NIP-98 signature. Stateless compute endpoints stay public.
// ==========================================
const nip98Enabled = (process.env.ENABLE_NIP98_AUTH || '').toLowerCase() === 'true';
const NIP98_PUBLIC_PATHS = new Set([
'/api/trips/estimate',
'/api/routes/preview'
]);
if (nip98Enabled) {
app.use((req, res, next) => {
const mutating = ['POST', 'PUT', 'PATCH', 'DELETE'].includes(req.method);
const guarded = req.path.startsWith('/api/') || req.path.startsWith('/rides');
if (!mutating || !guarded || NIP98_PUBLIC_PATHS.has(req.path)) {
return next();
}
if (req.user) {
return next();
}
return validateNIP98Auth(req, res, next);
});
console.log('🔐 NIP-98 authentication enforced on mutating API routes');
} else {
// Without a signature there is no identity, so every participant-only
// check in this file — managed ride details with exact coordinates,
// pickup notes, panic records, and `subscribe_ride` on
// the task socket — degrades to "anyone who knows the task id". That id
// is not a secret: the requester's own kind 37500 announcement puts it
// on public relays for federated discovery. So auth-off is not a weaker
// deployment, it is an open one, and it must never be the posture a
// real operator reaches by forgetting a variable.
if (process.env.NODE_ENV === 'production'
&& (process.env.ALLOW_UNAUTHENTICATED || '').toLowerCase() !== 'true') {
console.error('❌ Refusing to run with NIP-98 authentication disabled and NODE_ENV=production.');
console.error(' Task ids travel on public relays, so unauthenticated participant checks admit anyone.');
console.error(' Set ENABLE_NIP98_AUTH=true, or ALLOW_UNAUTHENTICATED=true for a throwaway public demo.');
process.exit(1);
}
console.log('⚠️ NIP-98 authentication DISABLED — participant checks are OPEN to anyone holding a task id');
}
// For sensitive GET endpoints: require NIP-98 only when auth is enabled
const optionalNip98 = nip98Enabled ? validateNIP98Auth : (req, res, next) => next();
// Rate limiting runs AFTER auth so it keys on the authenticated PUBKEY, not
// the IP — otherwise every user behind a shared mobile-carrier IP would share
// one bucket. Mutating API traffic is limited per user.
if (rateLimitingEnabled) {
app.use((req, res, next) => {
const guarded = req.path.startsWith('/api/') || req.path.startsWith('/rides');
const mutating = ['POST', 'PUT', 'PATCH', 'DELETE'].includes(req.method);
if (!guarded || !mutating) {
return next();
}
return authenticatedRateLimiter(req, res, next);
});
}
/**
* Does the authenticated signer match a stored party identity?
* Identities may carry a hex pubkey, an npub, or both.
*/
function actorMatchesIdentity(reqUser, identity) {
if (!reqUser || !identity) {
return false;
}
const signerPubkey = (reqUser.pubkey || '').toLowerCase();
if (identity.pubkey && identity.pubkey.toLowerCase() === signerPubkey) {
return true;
}
if (identity.npub) {
try {
return identity.npub.toLowerCase() === nip19.npubEncode(signerPubkey).toLowerCase();
} catch (error) {
return false;
}
}
return false;
}
/**
* Role authorisation for ride actions. Returns null when the signer is
* permitted (or auth is disabled), otherwise a { status, error, details }
* object the route should return.
*
* @param {Object} req - Express request (req.user set by NIP-98 middleware)
* @param {Object} ride - The ride/task record
* @param {string[]} allowed - Roles permitted: 'requester' and/or 'provider'
*/
function authoriseRideActor(req, ride, allowed = ['requester', 'provider']) {
if (!nip98Enabled || !req.user) {
return null;
}
const identities = [];
if (allowed.includes('requester')) {
identities.push(ride.requester || ride.rider);
}
if (allowed.includes('provider')) {
identities.push(ride.provider || ride.driver);
}
if (identities.some((identity) => actorMatchesIdentity(req.user, identity))) {
return null;
}
return {
status: 403,
error: 'Forbidden',
details: `Signer is not the ${allowed.join(' or ')} on this ride`
};
}
/**
* Coordinate/number validation shared across routes. `!lat` style checks
* rejected legitimate zero coordinates and admitted strings like "abc".
*/
function isValidLat(value) {
const n = Number(value);
return Number.isFinite(n) && n >= -90 && n <= 90;
}
function isValidLon(value) {
const n = Number(value);
return Number.isFinite(n) && n >= -180 && n <= 180;
}
function isPositiveInt(value, max = Number.MAX_SAFE_INTEGER) {
const n = Number(value);
return Number.isInteger(n) && n > 0 && n <= max;
}
/** Intermediate calling points a request or a destination change may carry */
const MAX_TASK_STOPS = 3;
/**
* Validate and normalise intermediate stops. Shared by the request handler
* and the destination-change endpoint so "add a stop" means the same thing
* whether it happens before or after the job is under way.
*
* @returns {{ stops: Array|null }|{ error: string }}
*/
function parseStops(stops) {
if (stops == null) {
return { stops: null };
}
if (!Array.isArray(stops) || stops.length > MAX_TASK_STOPS) {
return { error: `stops must be an array of at most ${MAX_TASK_STOPS} intermediate stops` };
}
if (stops.length === 0) {
return { stops: [] };
}
const parsed = [];
for (const stop of stops) {
const stopLon = stop?.lon != null ? stop.lon : stop?.lng;
if (!isValidLat(stop?.lat) || !isValidLon(stopLon)) {
return { error: 'each stop must contain valid lat and lon/lng' };
}
parsed.push({
lat: Number(stop.lat),
lon: Number(stopLon),
...(typeof stop.address === 'string' && stop.address.trim()
? { address: stop.address.trim().slice(0, 200) } : {})
});
}
return { stops: parsed };
}
function clampText(value, maxLen) {
if (typeof value !== 'string') {
return '';
}
return value.length > maxLen ? value.slice(0, maxLen) : value;
}
/**
* Flow-A session authorisation: sessions store bare hex pubkeys rather than
* identity objects. Returns null when permitted, else a 403 payload.
*/
function authoriseSessionActor(req, ...allowedHexKeys) {
if (!nip98Enabled || !req.user) {
return null;
}
const signer = (req.user.pubkey || '').toLowerCase();
const permitted = allowedHexKeys
.filter(Boolean)
.some((hex) => hex.toLowerCase() === signer);
if (permitted) {
return null;
}
return {
status: 403,
error: 'Forbidden',
details: 'Signer does not hold the required role on this ride session'
};
}
// Serve React frontend build if available (web/dist/)
const path = require('path');
const reactBuildPath = path.join(__dirname, 'web', 'dist');
app.use(express.static(reactBuildPath));
// ==========================================
// RELAY OPERATOR CONFIGURATION
// ==========================================
/**
* Parse a numeric env var. Unlike `parseFloat(x) || dflt`, a configured
* value of 0 is respected and garbage fails loudly.
*/
function envNumber(name, dflt) {
const raw = process.env[name];
if (raw == null || raw === '') {
return dflt;
}
const value = parseFloat(raw);
if (!Number.isFinite(value)) {
console.error(`\u274C ${name}="${raw}" is not a number`);
process.exit(1);
}
return value;
}
/**
* Resolve the operator's private key. Accepts hex via OPERATOR_PRIVKEY or
* bech32 nsec via OPERATOR_NSEC / OPERATOR_PRIVKEY. Exits on a malformed
* key \u2014 a silently absent key disables the entire public audit trail.
*/
function resolveOperatorPrivkey() {
const raw = process.env.OPERATOR_PRIVKEY || process.env.OPERATOR_NSEC || null;
if (!raw) {
return null;
}
const trimmed = raw.trim();
if (/^[0-9a-fA-F]{64}$/.test(trimmed)) {
return trimmed.toLowerCase();
}
if (trimmed.startsWith('nsec1')) {
try {
const decoded = nip19.decode(trimmed);
const data = decoded.data;
const hex = typeof data === 'string' ? data : Buffer.from(data).toString('hex');
if (/^[0-9a-f]{64}$/.test(hex)) {
return hex;
}
} catch (error) {
console.error(`\u274C OPERATOR_PRIVKEY/OPERATOR_NSEC is not a valid nsec: ${error.message}`);
process.exit(1);
}
}
console.error('\u274C OPERATOR_PRIVKEY/OPERATOR_NSEC must be 64 hex chars or an nsec1 string');
process.exit(1);
}
const config = {
// Operator settings
operatorName: process.env.OPERATOR_NAME || 'DonkeyRide Operator',
operatorPubkey: process.env.OPERATOR_PUBKEY,
operatorPrivkey: resolveOperatorPrivkey(),
operatorLightningAddress: process.env.OPERATOR_LIGHTNING,
// Default 0: the non-custodial operator takes NO cut of the fare (it never
// holds the fare, so it cannot). A licensed custodial operator may set a
// fee, which is only ever deducted on a custodial rail it is licensed for.
operatorFeePercent: envNumber('OPERATOR_FEE_PERCENT', 0),
// Fare rate card. Defaults are quoted in USD and auto-converted to the ride
// currency, so fares are sane in any currency (incl. KES) out of the box.
// An operator running a real market sets these to their own currency and
// sets FARE_CURRENCY to match (then no conversion is applied).
fareBase: envNumber('FARE_BASE', 2.50),
farePerKm: envNumber('FARE_PER_KM', 1.50),
farePerMinute: envNumber('FARE_PER_MINUTE', 0.30),
// Server settings
port: process.env.PORT || 3000,
wsPort: process.env.WS_PORT || 3001,
// Nostr relay to publish events. NO default: this used to fall back to
// 'wss://relay.damus.io', so `NOSTR_RELAY=''` — the obvious way to say
// "publish nowhere", and what the test suite sets — resolved to a large
// public relay instead. That is how signed task snapshots ended up on
// relay.damus.io. An unnamed relay is not a relay.
nostrRelay: process.env.NOSTR_RELAY || '',
// Relay URLs advertised to clients (public URLs, not Docker-internal ones)
publicRelays: (process.env.PUBLIC_RELAY_URLS || '')
.split(',').map(r => r.trim()).filter(Boolean),
// Operator policies
maxStakeAmount: envNumber('MAX_STAKE_AMOUNT', 10000), // Max stake in sats
minStakeAmount: envNumber('MIN_STAKE_AMOUNT', 50), // Min stake in sats
requireKYC: (process.env.REQUIRE_KYC || '').toLowerCase() === 'true',
};
// Fiat currencies the operator can price rides in. KES is included so a Kenyan
// operator can price in shillings and the M-Pesa/Tando rails show the exact
// amount. DEFAULT_FIAT_CURRENCY sets the fallback when a request omits one.
const SUPPORTED_FIAT = ['USD', 'EUR', 'GBP', 'KES'];
const DEFAULT_FIAT = (() => {
const c = (process.env.DEFAULT_FIAT_CURRENCY || 'GBP').toUpperCase();
return SUPPORTED_FIAT.includes(c) ? c : 'GBP';
})();
/** Normalise a requested currency to a supported one, else the operator default. */
function resolveFiatCurrency(requested) {
const c = typeof requested === 'string' ? requested.toUpperCase() : '';
return SUPPORTED_FIAT.includes(c) ? c : DEFAULT_FIAT;
}
// Currency the fare rate card is quoted in. Defaults to USD (the built-in rate
// card is USD-denominated and converted to the ride currency); an operator with
// a local rate card sets FARE_CURRENCY to their own currency.
const RATE_CARD_CURRENCY = (() => {
const c = (process.env.FARE_CURRENCY || 'USD').toUpperCase();
return SUPPORTED_FIAT.includes(c) ? c : 'USD';
})();
// Data handling is an operator choice, not a market assumption.
//
// blind — the coordinator receives coarse geohash cell centres and routed
// distance/time totals. Exact itinerary points are exchanged
// participant-to-participant by the clients after a match.
// managed — the operator receives exact points and may attach a database.
//
// Keep the process default compatible for developers and existing managed
// operators; the public/demo compose file explicitly selects `blind`.
const OPERATOR_DATA_MODE = (() => {
const mode = String(process.env.OPERATOR_DATA_MODE || 'managed').trim().toLowerCase();
if (!['blind', 'managed'].includes(mode)) {
console.error(`❌ Invalid OPERATOR_DATA_MODE "${mode}" (expected blind or managed)`);
process.exit(1);
}
return mode;
})();
const PUBLIC_ROUTING_URL = String(process.env.PUBLIC_ROUTING_URL || '').trim().replace(/\/$/, '');
const PRIVATE_LOCATION_PRECISION = 5; // roughly a neighbourhood, not a doorway
const SETTLEMENT_MODES = new Set(['priced', 'none']);
function normaliseSettlementMode(value) {
const mode = typeof value === 'string' ? value.trim().toLowerCase() : 'priced';
return SETTLEMENT_MODES.has(mode) ? mode : null;
}
function parseRouteSummary(value, allowZero = false) {
if (!value || typeof value !== 'object') return null;
const distanceKm = Number(value.distance_km ?? value.distanceKm);
const durationMinutes = Number(value.duration_minutes ?? value.durationMinutes);
const minimum = allowZero ? 0 : Number.MIN_VALUE;
if (!Number.isFinite(distanceKm) || distanceKm < minimum || distanceKm > 2000) return null;
if (!Number.isFinite(durationMinutes) || durationMinutes < minimum || durationMinutes > 48 * 60) return null;
if (allowZero && ((distanceKm === 0) !== (durationMinutes === 0))) return null;
return { distanceKm, durationMinutes };
}
/** Rate-card options passed to every estimateTripCost() call. */
function rateCardOptions(currency, multiplier = 1) {
// A service class (XL, Comfort) scales the whole rate card, so every
// derived figure — fare, breakdown rows, formatted string — stays
// internally consistent instead of a multiplied total that no longer
// matches its own breakdown.
const m = Number.isFinite(multiplier) && multiplier > 0 ? multiplier : 1;
return {
currency,
baseFare: config.fareBase * m,
perKm: config.farePerKm * m,
perMinute: config.farePerMinute * m,
rateCardCurrency: RATE_CARD_CURRENCY,
operatorFeePct: config.operatorFeePercent
};
}
/**
* Route + price a trip. The single pricing path for BOTH the upfront quote
* (`/api/trips/estimate`) and the fare recorded on the ride
* (`/api/rides/request`) — see the upfront-price guarantee below. Any change
* here moves both, which is the point.
*
* @returns {{distance:number, duration:number, coordinates:Array|null,
* routed:boolean, estimate:object}}
*/
async function routeAndPrice(pickup, dropoff, via, currency, multiplier = 1) {
let distance = 0;
let duration = 0;
let coordinates = null;
let routed = false;
if (dropoff && dropoff.lat != null && dropoff.lon != null) {
const osrmRoute = await getRoute(
pickup.lat, pickup.lon, dropoff.lat, dropoff.lon, via || []
);
if (osrmRoute) {
distance = parseFloat(osrmRoute.distanceKm);
duration = osrmRoute.durationMin;
coordinates = osrmRoute.coordinates;
routed = true;
} else {
const error = new Error('Road routing is unavailable; no straight-line estimate was substituted');
error.code = 'ROAD_ROUTING_UNAVAILABLE';
throw error;
}
}
const estimate = await estimateTripCost(
distance, duration, rateCardOptions(currency, multiplier)
);
return { distance, duration, coordinates, routed, estimate };
}
// ==========================================
// QUOTE STORE — the upfront-price guarantee across TIME
// ==========================================
// routeAndPrice() makes the quote and the fare agree for the same INPUTS,
// but the rate card is fiat and reaches sats through a BTC price cached for
// five minutes. A rider who reads the quote, picks a service class and types
// a meeting note can easily cross that boundary, and the ride then records a
// number they never saw — the completion screen even calls it the "agreed
// amount". Recomputing more carefully cannot fix that; only remembering the
// quote can. So the estimate mints one, and the request spends it.
//
// Kept in memory and short-lived, like every other bit of coordination state
// here: a lost quote costs a re-price, not a ride.
const quoteStore = new Map();
const QUOTE_TTL_MS = parseInt(process.env.QUOTE_TTL_MS || '600000', 10); // 10 min
// How far the request's coordinates may sit from the quoted ones. Not zero:
// clients round when they serialise. Far too small to buy a different journey.
const QUOTE_MATCH_TOLERANCE_KM = 0.1;
function rememberQuote(entry) {
// Unguessable: a quote is a promise about money, and a predictable
// handle would let one rider spend another's.
const id = `q_${require('crypto').randomBytes(16).toString('hex')}`;
quoteStore.set(id, { ...entry, expiresAt: Date.now() + QUOTE_TTL_MS });
return id;
}
/** The quote if it is still valid AND is for the journey being requested. */
function redeemQuote(quoteId, journey) {
if (typeof quoteId !== 'string' || !quoteId) return null;
const quote = quoteStore.get(quoteId);
if (!quote) return null;
if (quote.expiresAt <= Date.now()) {
quoteStore.delete(quoteId);
return null;
}
// A privacy-mode quote is bound to routed totals rather than exact
// coordinates. The routing client keeps the itinerary; the coordinator
// only needs the numbers the rate card prices.
if (quote.locationMode === 'participant_encrypted') {
const distanceDelta = Math.abs(Number(quote.distanceKm) - Number(journey.distanceKm));
const durationDelta = Math.abs(Number(quote.durationMinutes) - Number(journey.durationMinutes));
if (!Number.isFinite(distanceDelta) || distanceDelta > 0.05) return null;
if (!Number.isFinite(durationDelta) || durationDelta > 0.5) return null;
if ((quote.stopCount || 0) !== (journey.stopCount || 0)) return null;
if ((quote.currency || null) !== (journey.currency || null)) return null;
return quote;
}
// A managed-mode quote buys the journey it was given for, not a cheaper
// price on a different one. Everything the fare depends on has to match.
const near = (a, b) => a && b
&& calculateDistance(a.lat, a.lon, b.lat, b.lon) <= QUOTE_MATCH_TOLERANCE_KM;
if (!near(quote.pickup, journey.pickup)) return null;
if (Boolean(quote.dropoff) !== Boolean(journey.dropoff)) return null;
if (quote.dropoff && !near(quote.dropoff, journey.dropoff)) return null;
if ((quote.stopCount || 0) !== (journey.stopCount || 0)) return null;
if ((quote.currency || null) !== (journey.currency || null)) return null;
return quote;
}
/**
* The sats figure this quote showed for the class the rider actually chose.
* The confirm screen prices EVERY class up front, so the class is picked
* after the quote is minted — a quote is for a journey, not for one row of
* the rate card. Returns null for a class this quote never priced.
*/
function quotedFareFor(quote, optionId) {
if (!quote) return null;
const key = optionId || '__default__';
const priced = quote.fares && quote.fares[key];
return priced && Number.isFinite(priced.sats) ? priced : null;
}
const quoteSweep = setInterval(() => {
const now = Date.now();
for (const [id, q] of quoteStore) {
if (q.expiresAt <= now) quoteStore.delete(id);
}
}, 60 * 1000);
quoteSweep.unref();
/**
* Sats rows for a fare breakdown that actually sums to the quote. The pricing
* module returns fiat rows; the client shows sats-and-fiat, so convert with
* the SAME fiat→sats ratio the total used rather than re-deriving it.
*/
function breakdownSats(estimate) {
const rows = estimate.breakdown || {};
const totalFiat = estimate.fare?.fiat || 0;
const totalSats = estimate.fare?.sats || 0;
const toSats = (fiat) => (totalFiat > 0
? Math.round((fiat / totalFiat) * totalSats)
: 0);
const baseFareSats = toSats(rows.baseFare?.fiat || 0);
const timeFareSats = toSats(rows.duration?.fiat || 0);
// Rounding remainder lands on the distance row so the three rows sum to
// the quoted fare EXACTLY — a breakdown that is a sat out invites the
// "what's the extra for?" question this feature exists to answer.
return {
baseFareSats,
distanceFareSats: Math.max(0, totalSats - baseFareSats - timeFareSats),
timeFareSats,
operatorFeeSats: estimate.operatorFee?.sats || 0
};
}
const packageVersion = require('./package.json').version;
// ==========================================
// DOMAIN PROFILE
// ==========================================
let domainProfile;
try {
domainProfile = loadProfile(process.env.DOMAIN);
} catch (error) {
console.error(`\u274C Failed to load domain profile "${process.env.DOMAIN}": ${error.message}`);
process.exit(1);
}
console.log(`\uD83C\uDF10 Domain profile loaded: ${domainProfile.name} (${domainProfile.id})`);
if (config.operatorPrivkey) {
try {
const derived = nostrGetPublicKey(config.operatorPrivkey);
if (config.operatorPubkey && !config.operatorPubkey.startsWith('npub')
&& config.operatorPubkey.toLowerCase() !== derived.toLowerCase()) {
console.error('\u274C OPERATOR_PUBKEY does not match the key derived from the private key');
process.exit(1);
}
config.operatorPubkey = derived;
console.log('\uD83D\uDD11 Operator Nostr identity loaded');
} catch (error) {
console.error('\u274C Failed to derive operator pubkey from private key:', error.message);
process.exit(1);
}
} else {
console.warn('\u26A0\uFE0F No operator key configured (OPERATOR_PRIVKEY or OPERATOR_NSEC) \u2014 operator-signed Nostr events are DISABLED');
}
// ==========================================
// PAYMENT PROVIDER INITIALIZATION
// ==========================================
// Initialize payment provider with automatic fallbacks
let paymentProvider;
let stakeManager;
let httpServer = null;
/**
* Unify on the stake manager's primary provider and refuse to run a mock
* rail in production. Two divergent provider instances previously meant
* settlements were recorded on an object holding no stakes.
*/
function adoptPaymentProvider() {
paymentProvider = stakeManager.currentProvider;
// COMPLIANCE GATE: the reference operator is a coordinator, not a payment
// institution. A custodial rail (one where the operator receives, holds or
// can claim funds) makes the operator a money transmitter / EMI \u2014 a
// licensed activity. Refuse to run one unless the operator explicitly
// asserts it holds the requisite licence.
const custody = typeof paymentProvider.getCustodyModel === 'function'
? paymentProvider.getCustodyModel()
: 'custodial';
const licensed = (process.env.OPERATOR_LICENSED_CUSTODIAN || '').toLowerCase() === 'true';
if (custody !== 'none' && !licensed) {
console.error(`\u274C Payment provider '${paymentProvider.providerName}' is CUSTODIAL \u2014 the operator would receive and control funds, making it a money transmitter.`);
console.error(' The reference operator is non-custodial by design. Use PAYMENT_PROVIDER=cash (record-only, settles peer-to-peer).');
console.error(' Only set OPERATOR_LICENSED_CUSTODIAN=true if you are a licensed payment institution and accept that regulatory burden.');
process.exit(1);
}
if (process.env.NODE_ENV === 'production'
&& paymentProvider.getTrustModel() === 'demo'
&& (process.env.ALLOW_DEMO_PAYMENTS || '').toLowerCase() !== 'true') {
console.error('\u274C Refusing to run the demo payment provider with NODE_ENV=production.');
console.error(' Set PAYMENT_PROVIDER=cash for a real non-custodial rail, or ALLOW_DEMO_PAYMENTS=true for a public demo.');
process.exit(1);
}
const caps = paymentProvider.getCapabilities();
console.log(`\u2705 Payment provider: ${paymentProvider.providerName} (trust: ${caps.trustModel}, custody: ${custody})`);
if (custody === 'none') {
console.log('\uD83D\uDEE1\uFE0F Non-custodial: the operator never receives, holds, or transmits funds.');
} else {
console.log('\u26A0\uFE0F CUSTODIAL rail active under OPERATOR_LICENSED_CUSTODIAN \u2014 the operator is acting as a licensed payment institution.');
}
}
/**
* Build provider configuration map from environment variables.
* Mirrors PaymentProviderFactory.fromEnv so we can reuse configs for stake manager.
*/
function buildProviderConfigsFromEnv() {
return {
demo: {},
cash: {},
lnd: {
host: process.env.LND_HOST || 'localhost:10009',
cert: process.env.LND_CERT_PATH || '~/.lnd/tls.cert',
macaroon: process.env.LND_MACAROON_PATH || '~/.lnd/data/chain/bitcoin/mainnet/admin.macaroon',
network: process.env.LND_NETWORK || 'mainnet'
},
btcpay: {
url: process.env.BTCPAY_URL,
apiKey: process.env.BTCPAY_API_KEY,
storeId: process.env.BTCPAY_STORE_ID
},
alby: {
apiKey: process.env.ALBY_API_KEY,
refreshToken: process.env.ALBY_REFRESH_TOKEN
},
cln: {
socket: process.env.CLN_SOCKET || '~/.lightning/bitcoin/lightning-rpc',
network: process.env.CLN_NETWORK || 'bitcoin'
}
};
}
function parseProviderList(envValue, fallback) {
if (envValue && envValue.trim().length > 0) {
return envValue.split(',').map(p => p.trim()).filter(Boolean);
}
return Array.isArray(fallback) ? fallback : [fallback];
}
async function initializeStakeManager() {
const providerOrder = parseProviderList(
process.env.STAKE_PROVIDERS,
parseProviderList(process.env.PAYMENT_PROVIDER, 'demo')
);
// Allow explicit override of fallback order
const fallbacks = parseProviderList(process.env.PAYMENT_FALLBACKS, []);
fallbacks.forEach(p => {
if (!providerOrder.includes(p)) {
providerOrder.push(p);
}
});
const configs = buildProviderConfigsFromEnv();
const normalized = providerOrder.length > 0 ? providerOrder : ['demo'];
stakeManager = new ResilientStakeManager(normalized, configs, PaymentProviderFactory);
await stakeManager.initialize();
}
// ==========================================
// REDIS CLIENT
// ==========================================
let redis;
async function initializeRedis() {
if ((process.env.DISABLE_REDIS || '').toLowerCase() === 'true') {
console.log('⚠️ Redis disabled via DISABLE_REDIS env');
redis = null;
return;
}
try {
redis = Redis.createClient({
url: process.env.REDIS_URL || 'redis://localhost:6379'
});
redis.on('error', (err) => console.error('Redis error:', err));
await redis.connect();
console.log('✅ Redis connected');
} catch (error) {
console.warn('⚠️ Redis not available - driver location features disabled');
redis = null;
}
}
const activeRides = new Map();
const disputes = new Map();
const suspensions = new Map();
const theftReports = new Map();
const guardianState = {
bond: null,
guardians: new Set(
(process.env.GUARDIAN_PUBKEYS || '').split(',').map(s => s.trim()).filter(Boolean)
),
proposals: new Map(),
watchdogClaims: new Map()
};
// Multi-domain task manager — routes operations to the correct domain's TaskManager.
// Supports frontend domain switching: tasks created under locksmith use locksmith states, etc.
const _domainManagers = new Map();
_domainManagers.set(domainProfile.id, new TaskManager(domainProfile));
// Task persistence — attached to every domain manager once initialised in startServer()
let taskStore = null;
function _getManagerForDomain(domainId) {
if (!_domainManagers.has(domainId)) {
const profile = loadProfile(domainId);
const manager = new TaskManager(profile);
if (taskStore) {
manager.setStore(taskStore);
}
manager.setSnapshotPublisher(publishTaskSnapshot);
_domainManagers.set(domainId, manager);
}
return _domainManagers.get(domainId);
}
async function initializeTaskStore() {
// Always attach the Nostr snapshot publisher — it is the default
// durability layer, database or not.
for (const manager of _domainManagers.values()) {
manager.setSnapshotPublisher(publishTaskSnapshot);
}
// A database is entirely optional. The default deployment runs with none:
// durability comes from Nostr snapshots (rehydrated below). Only when
// DATABASE_URL is set (e.g. a licensed Mode-B operator retaining PII) does
// the operator use a store.
if (!process.env.DATABASE_URL) {
console.log('💾 No database configured — in-memory + Nostr snapshot durability');
return;
}
try {
const store = createTaskStore(process.env.DATABASE_URL);
await store.init();
taskStore = store;
for (const manager of _domainManagers.values()) {
manager.setStore(taskStore);
}
const persisted = await taskStore.loadActiveTasks();
for (const task of persisted) {
try {
const manager = _getManagerForDomain(task.domain || domainProfile.id);
manager.hydrateTask(task);
_rideIndex.set(task.id, task.domain || domainProfile.id);
} catch (error) {
console.warn(`⚠️ Could not rehydrate task ${task.id}:`, error.message);
}
}
console.log(`💾 Task store ready (${store.backend}) — rehydrated ${persisted.length} active task(s)`);
} catch (error) {
console.warn('⚠️ Task store unavailable — running in-memory + Nostr only:', error.message);
taskStore = null;
}
}
// Index: rideId → domainId (populated on create, lazy-filled on lookup)
const _rideIndex = new Map();
function _getManagerForRide(rideId) {
const cached = _rideIndex.get(rideId);
if (cached && _domainManagers.has(cached)) {
return _domainManagers.get(cached);
}
for (const [domainId, mgr] of _domainManagers) {
if (mgr.getRide(rideId)) {
_rideIndex.set(rideId, domainId);
return mgr;
}
}
return _domainManagers.get(domainProfile.id);
}
// Drop-in replacement for the single TaskManager — same API, multi-domain routing
const rideManager = {
// Ride lookup — searches all domain managers
getRide(rideId) {
return _getManagerForRide(rideId).getRide(rideId);
},
// Creation — accepts optional domain as last argument
createRide(requester, pickup, dropoff, fare, options = {}) {
const domain = options.domain || domainProfile.id;
delete options.domain;
const mgr = _getManagerForDomain(domain);
const ride = mgr.createRide(requester, pickup, dropoff, fare, options);
_rideIndex.set(ride.id, domain);
return ride;
},
// All per-ride operations delegate to the correct manager
acceptRide(rideId, ...args) { return _getManagerForRide(rideId).acceptRide(rideId, ...args); },
startEnRoute(rideId, ...args) { return _getManagerForRide(rideId).startEnRoute(rideId, ...args); },
arriveAtPickup(rideId, ...args) { return _getManagerForRide(rideId).arriveAtPickup(rideId, ...args); },
startTrip(rideId, ...args) { return _getManagerForRide(rideId).startTrip(rideId, ...args); },
completeTrip(rideId, ...args) { return _getManagerForRide(rideId).completeTrip(rideId, ...args); },
cancelRide(rideId, ...args) { return _getManagerForRide(rideId).cancelRide(rideId, ...args); },
transitionTo(rideId, ...args) { return _getManagerForRide(rideId).transitionTo(rideId, ...args); },
updateDriverLocation(rideId, ...args) { return _getManagerForRide(rideId).updateDriverLocation(rideId, ...args); },
updatePickup(rideId, ...args) { return _getManagerForRide(rideId).updatePickup(rideId, ...args); },
updateDropoff(rideId, ...args) { return _getManagerForRide(rideId).updateDropoff(rideId, ...args); },
recordRating(rideId, ...args) { return _getManagerForRide(rideId).recordRating(rideId, ...args); },
// Persist mutations made directly on the ride object (proofs, tips, safety, quotes)
persistRide(rideId) {
const mgr = _getManagerForRide(rideId);
const ride = mgr.getRide(rideId);
if (ride) {
mgr._persist(ride);
}
},
// All in-memory tasks where the pubkey is a party (either role).
// Tasks created via npub-only identities are matched through the
// derived npub as well.
getTasksByParticipant(pubkey) {
const key = (pubkey || '').toLowerCase();
let npubKey = null;
try {
npubKey = /^[0-9a-f]{64}$/.test(key) ? nip19.npubEncode(key).toLowerCase() : null;
} catch (error) {
npubKey = null;
}
const matchesIdentity = (identity) => Boolean(identity && (
identity.pubkey?.toLowerCase() === key
|| (npubKey && identity.npub?.toLowerCase() === npubKey)
));
const matches = [];
for (const mgr of _domainManagers.values()) {
for (const task of mgr.tasks.values()) {
if (matchesIdentity(task.provider || task.driver)
|| matchesIdentity(task.requester || task.rider)) {
matches.push(task);
}
}
}
return matches;
},
// Terminal check — uses the ride's own domain
isTerminal(status) {
for (const mgr of _domainManagers.values()) {
if (mgr.isTerminal(status)) return true;
}
return false;
},
// ETA calculation is domain-independent (haversine)
calculateETA(from, to, speed) {
return _domainManagers.get(domainProfile.id).calculateETA(from, to, speed);
},
// Aggregate methods — merge across all domains
getActiveRides() {
const all = [];
for (const mgr of _domainManagers.values()) {
all.push(...mgr.getActiveRides());
}
return all;
},
getActiveTasks() { return this.getActiveRides(); },
getStats() {
const merged = { total: 0 };
for (const mgr of _domainManagers.values()) {
const s = mgr.getStats();
for (const [key, val] of Object.entries(s)) {
merged[key] = (merged[key] || 0) + val;
}
}
return merged;
},
// Get the domain profile for a specific ride
getProfileForRide(rideId) {
return _getManagerForRide(rideId).profile;
},
};
const relayConfig = (process.env.REPUTATION_RELAYS || `${process.env.NOSTR_RELAYS || ''},${config.nostrRelay || ''}`)