forked from FinesseStudioLab/Trivela
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
2341 lines (2110 loc) · 84.2 KB
/
Copy pathindex.js
File metadata and controls
2341 lines (2110 loc) · 84.2 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
/**
* Trivela Backend API
* Serves campaign data, health, and Stellar/Soroban RPC proxy for the frontend.
*/
// #288 — OpenTelemetry SDK MUST initialize before any `http` /
// `express` import so the auto-instrumentation patches catch them.
// `initTracing()` is fire-and-forget; the API/SDK still works as a
// no-op when the optional OTel deps aren't installed.
import { initTracing, traceparentMiddleware, shutdownTracing } from './tracing.js';
void initTracing();
import cors from 'cors';
import express from 'express';
import compression from 'compression';
import multer from 'multer';
import { join } from 'node:path';
import { pathToFileURL } from 'node:url';
import Redis from 'ioredis';
import createApiKeyAuth, { createMasterKeyAuth } from './middleware/apiKeyAuth.js';
import { createRateLimiter, createRedisStore } from './middleware/rateLimit.js';
import { createAuthLockout } from './middleware/authLockout.js';
import requestLogger, { log } from './middleware/logger.js';
import requestId from './middleware/requestId.js';
import securityHeaders from './middleware/securityHeaders.js';
import errorHandler from './middleware/errorHandler.js';
import { paginateItems } from './pagination.js';
import { checkSorobanRpcHealth } from './sorobanRpc.js';
import { createRpcPool } from './rpcPool.js';
import { resolveStellarNetworkConfig } from './config/stellarNetwork.js';
import { validateBackendEnv } from './config/envValidation.js';
import { createDal } from './dal/index.js';
import { createJobRunner } from './jobs/jobRunner.js';
import { WebhookService, WEBHOOK_EVENTS } from './services/webhookService.js';
import {
campaignCreateSchema,
campaignUpdateSchema,
cursorBodySchema,
apiKeyCreateSchema,
formatZodErrors,
} from './schemas.js';
import { createStorageAdapter } from './storage/index.js';
import {
uploadCampaignImage,
validateImageUpload,
MAX_IMAGE_SIZE_BYTES,
} from './services/imageUpload.js';
import { buildCampaignStats } from './services/campaignStatsService.js';
import { createCampaignExportRoute } from './routes/campaignExport.js';
import { createDeprecationMiddleware } from './middleware/deprecationNotice.js';
import { DEPRECATION_REGISTRY } from './deprecations.js';
import { generateAllowlist } from './lib/allowlist/merkle.js';
import { parseAllowlistCsv, validateGAddress, MAX_ALLOWLIST_ROWS } from './lib/allowlist/csv.js';
import { createEmbedRoute } from './routes/embed.js';
import { createVariantRoutes } from './routes/variants.js';
import { createVariantService } from './services/variantService.js';
import { createCohortRoutes } from './routes/cohorts.js';
import { createCohortService } from './services/cohortService.js';
import { createPushRoutes } from './routes/push.js';
import { createOrgRoutes } from './routes/orgs.js';
import { createAuditRouter } from './routes/audit.js';
import { createAuditLogService } from './services/auditLogService.js';
import { createWebPushService } from './services/webPushService.js';
import { createOrganizationRoutes } from './routes/organizations.js';
import { createUsageMeteringService } from './services/usageMeteringService.js';
import { createFeatureFlagRoutes } from './routes/featureFlags.js';
import { createFeatureFlagService } from './services/featureFlagService.js';
import { createUsageMeteringMiddleware } from './middleware/usageMetering.js';
import { requestTimeout } from './middleware/timeout.js';
import { PoolSaturatedError } from './rpcPool.js';
import { initializeWebSocket, getWebSocketServer } from './websocket/index.js';
import { requireScope } from './middleware/rbac.js';
import { createIdempotencyMiddleware } from './middleware/idempotency.js';
import { createDistributedLock, createInMemoryLock } from './jobs/distributedLock.js';
import { createExportJob } from './jobs/exportJob.js';
import { createEventIndexer } from './jobs/eventIndexer.js';
import { createSqliteJobQueueRepository } from './dal/sqliteJobQueueRepository.js';
import { createDurableJobQueue } from './jobs/durableJobQueue.js';
import { createStellarTomlRoute } from './routes/stellarToml.js';
import { createSponsoredAccountRoutes } from './routes/sponsoredAccounts.js';
import { createClaimableBalancesRoutes } from './routes/claimableBalances.js';
import { createFeeBumpRoutes } from './routes/feeBump.js';
import { createPathPaymentRoutes } from './routes/pathPayment.js';
import { createIndexReadRoutes } from './routes/indexRead.js';
import { createSep10Routes, createRequireWalletAuth } from './routes/sep10.js';
import { createZkInputsRoutes } from './routes/zkInputs.js';
import { createOperatorBalanceJob } from './jobs/operatorBalanceJob.js';
const DEFAULT_PORT = 3001;
const DEFAULT_RATE_LIMIT_WINDOW_MS = 60_000;
const DEFAULT_RATE_LIMIT_MAX_REQUESTS = 60;
const DEFAULT_AUTH_LOCKOUT_SOFT_THRESHOLD = 5;
const DEFAULT_AUTH_LOCKOUT_HARD_THRESHOLD = 10;
const DEFAULT_AUTH_LOCKOUT_BASE_LOCKOUT_MS = 60_000;
const DEFAULT_SHORT_CACHE_TTL_MS = 5_000;
const DEFAULT_JSON_BODY_LIMIT = '100kb';
const DEFAULT_RPC_POLL_INTERVAL_MS = 60_000;
const DEFAULT_REQUEST_TIMEOUT_MS = 30_000;
const LEGACY_API_PREFIX = '/api';
const API_V1_PREFIX = '/api/v1';
const CONTRACT_ID_PATTERN = /^C[A-Z2-7]{55}$/;
/**
* @param {string | number | undefined} value
* @param {number} fallback
* @returns {number}
*/
function normalizePositiveInteger(value, fallback) {
const parsed = Number.parseInt(String(value), 10);
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
}
/** @returns {{ name: string, description: string, active: boolean, rewardPerAction: number, createdAt: string }[]} */
function defaultSeed() {
return [
{
name: 'Welcome Campaign',
description: 'Earn points for completing onboarding',
active: true,
rewardPerAction: 10,
createdAt: new Date().toISOString(),
},
];
}
/** @param {string | undefined} value @returns {string[]} */
function parseAllowedOrigins(value) {
if (!value) {
return [];
}
return String(value)
.split(',')
.map((origin) => origin.trim())
.filter(Boolean);
}
/** @param {string[]} allowedOrigins @returns {import('cors').CorsOptions} */
function createCorsOptions(allowedOrigins) {
const corsOptions = {
maxAge: 86400,
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
// #288 — accept `traceparent` from instrumented frontends and
// expose it on responses so the browser can stitch its own
// spans into the same OpenTelemetry trace.
allowedHeaders: ['Content-Type', 'X-API-Key', 'Authorization', 'traceparent'],
exposedHeaders: ['traceparent'],
};
if (allowedOrigins.includes('*')) {
return { origin: true, ...corsOptions };
}
return {
origin(
/** @type {string | undefined} */ origin,
/** @type {(err: Error | null, allow?: boolean) => void} */ callback,
) {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
return;
}
callback(null, false);
},
...corsOptions,
};
}
/** @param {Record<string, unknown>} options @param {string} envKey @returns {string} */
function readOptionalConfigValue(options, envKey) {
const fromOptions = options[envKey];
if (typeof fromOptions === 'string' && fromOptions.trim().length > 0) {
return fromOptions;
}
const fromEnv = process.env[envKey];
return typeof fromEnv === 'string' ? fromEnv : '';
}
/** @param {unknown} value @param {string} label @returns {string} */
function validateContractId(value, label) {
if (!value) {
return '';
}
const normalized = String(value).trim();
if (!CONTRACT_ID_PATTERN.test(normalized)) {
throw new Error(`${label} must be a valid Stellar contract ID`);
}
return normalized;
}
/** @param {Record<string, unknown>} options @returns {import('express').Application} */
export async function createApp(options = {}) {
const isProduction = process.env.NODE_ENV === 'production';
const jsonBodyLimit =
/** @type {string} */ (options.jsonBodyLimit) ??
process.env.JSON_BODY_LIMIT ??
DEFAULT_JSON_BODY_LIMIT;
const corsAllowedOriginsRaw =
/** @type {string | undefined} */ (options.corsAllowedOrigins) ??
process.env.CORS_ALLOWED_ORIGINS ??
process.env.CORS_ORIGIN ??
(isProduction ? '' : 'http://localhost:5173');
const stellarConfig = resolveStellarNetworkConfig({
network: /** @type {string} */ (options.stellarNetwork) ?? process.env.STELLAR_NETWORK,
sorobanRpcUrl: /** @type {string} */ (options.sorobanRpcUrl) ?? process.env.SOROBAN_RPC_URL,
horizonUrl: /** @type {string} */ (options.horizonUrl) ?? process.env.HORIZON_URL,
networkPassphrase:
/** @type {string} */ (options.networkPassphrase) ?? process.env.STELLAR_NETWORK_PASSPHRASE,
});
const rewardsContractId = validateContractId(
readOptionalConfigValue(options, 'REWARDS_CONTRACT_ID'),
'REWARDS_CONTRACT_ID',
);
const campaignContractId = validateContractId(
readOptionalConfigValue(options, 'CAMPAIGN_CONTRACT_ID'),
'CAMPAIGN_CONTRACT_ID',
);
const fetchImpl = /** @type {typeof fetch} */ (options.fetchImpl) ?? globalThis.fetch;
const rpcUrlsRaw =
/** @type {string | undefined} */ (options.sorobanRpcUrls) ?? process.env.SOROBAN_RPC_URLS;
const rpcUrls = rpcUrlsRaw
? String(rpcUrlsRaw)
.split(',')
.map((u) => u.trim())
.filter(Boolean)
: [stellarConfig.sorobanRpcUrl];
const rpcPool = createRpcPool(rpcUrls);
const allowedOrigins = parseAllowedOrigins(corsAllowedOriginsRaw);
if (isProduction && allowedOrigins.includes('*')) {
throw new Error('Wildcard origins are not permitted in production.');
}
const rateLimitWindowMs = normalizePositiveInteger(
/** @type {any} */ (options.rateLimit)?.windowMs ?? process.env.RATE_LIMIT_WINDOW_MS,
DEFAULT_RATE_LIMIT_WINDOW_MS,
);
const rateLimitMaxRequests = normalizePositiveInteger(
/** @type {any} */ (options.rateLimit)?.maxRequests ?? process.env.RATE_LIMIT_MAX_REQUESTS,
DEFAULT_RATE_LIMIT_MAX_REQUESTS,
);
const authLockoutOptions = /** @type {any} */ (options.authLockout) ?? {};
const authLockoutSoftThreshold = normalizePositiveInteger(
authLockoutOptions.softThreshold ?? process.env.AUTH_LOCKOUT_SOFT_THRESHOLD,
DEFAULT_AUTH_LOCKOUT_SOFT_THRESHOLD,
);
const authLockoutHardThreshold = normalizePositiveInteger(
authLockoutOptions.hardThreshold ?? process.env.AUTH_LOCKOUT_HARD_THRESHOLD,
DEFAULT_AUTH_LOCKOUT_HARD_THRESHOLD,
);
const authLockoutBaseMs = normalizePositiveInteger(
authLockoutOptions.baseLockoutMs ?? process.env.AUTH_LOCKOUT_BASE_MS,
DEFAULT_AUTH_LOCKOUT_BASE_LOCKOUT_MS,
);
const seed = /** @type {any[]} */ (options.campaigns) ?? defaultSeed();
const dbPath = /** @type {string} */ (options.dbPath) ?? process.env.DB_PATH ?? './trivela.db';
const dal = await createDal({
dbPath,
campaigns: seed,
campaignRepository: options.campaignRepository,
auditLogRepository: options.auditLogRepository,
});
const campaignRepository = dal.campaigns;
const auditLogRepository = dal.auditLogs;
const webhookRepository = dal.webhooks;
const referralRepository = dal.referrals;
const variantRepository = dal.variants;
const cohortRepository = dal.cohorts;
const pushSubscriptionRepository = dal.pushSubscriptions;
const apiKeyRepository = dal.apiKeys;
const failedJobRepository = options.failedJobRepository ?? dal.failedJobs;
const allowlistRepository = dal.allowlists;
const orgMemberRepository = dal.orgMembers;
const usageRepository = options.usageRepository ?? dal.usage;
const idempotencyRepository = dal.idempotency;
const idempotencyMiddleware = createIdempotencyMiddleware({
repository: idempotencyRepository,
});
const storageAdapter = /** @type {import('./storage/storageAdapter.js').StorageAdapter} */ (
options.storageAdapter ?? createStorageAdapter(process.env)
);
const imageUpload = multer({
storage: multer.memoryStorage(),
limits: { fileSize: MAX_IMAGE_SIZE_BYTES },
});
const webhookService = new WebhookService(webhookRepository, {
fetchImpl,
logger: log,
});
const variantService = createVariantService({ variantRepo: variantRepository });
const cohortService = createCohortService({ cohortRepo: cohortRepository });
const auditLogService = createAuditLogService({
auditLogRepository,
orgMemberRepository,
});
const webPushService = createWebPushService({
repository: pushSubscriptionRepository,
vapid: {
publicKey: process.env.VAPID_PUBLIC_KEY,
privateKey: process.env.VAPID_PRIVATE_KEY,
subject: process.env.VAPID_SUBJECT,
},
logger: log,
});
const shortCacheTtlMs = normalizePositiveInteger(
/** @type {any} */ (options.shortCacheTtlMs) ?? process.env.SHORT_CACHE_TTL_MS,
DEFAULT_SHORT_CACHE_TTL_MS,
);
const rpcPollIntervalMs = normalizePositiveInteger(
/** @type {any} */ (options.rpcPollIntervalMs) ?? process.env.RPC_HEALTH_POLL_INTERVAL_MS,
DEFAULT_RPC_POLL_INTERVAL_MS,
);
const shortCache = new Map();
const indexerCursorState = {
cursor:
/** @type {string | null} */ (options.initialIndexerCursor) ??
process.env.INDEXER_EVENT_CURSOR ??
null,
updatedAt: new Date().toISOString(),
source: (options.initialIndexerCursor ?? process.env.INDEXER_EVENT_CURSOR) ? 'env' : 'runtime',
};
const rpcHealthCache = {
updatedAt: /** @type {string | null} */ (null),
payload: /** @type {unknown} */ (null),
};
const app = express();
const metrics = {
requestTotal: 0,
requestErrors: 0,
routeHits: new Map(),
authFailures: 0,
authLockouts: 0,
// p95 latency histogram — 12 buckets (ms): 50,100,200,500,1000,2000,5000,...
latencyBuckets: [50, 100, 200, 500, 1_000, 2_000, 5_000, 10_000, 30_000, Infinity],
latencyCounts: /** @type {number[]} */ ([]),
latencyTotal: 0,
latencySum: 0,
};
// Initialise bucket counters to 0.
metrics.latencyCounts = metrics.latencyBuckets.map(() => 0);
// Apply global request deadline so every route self-defends against slow
// upstreams. The timeout is configurable via REQUEST_TIMEOUT_MS.
const requestTimeoutMs = normalizePositiveInteger(
options.requestTimeoutMs ?? process.env.REQUEST_TIMEOUT_MS,
DEFAULT_REQUEST_TIMEOUT_MS,
);
app.use(requestTimeout(requestTimeoutMs));
/**
* Compatibility shim: ?api_version=v0 rewrites v1 routes to legacy patterns
* and adds a Deprecation header. This is a temporary bridge for integrators
* during the 90-day migration window (see docs/API_MIGRATION.md).
*/
app.use((req, res, next) => {
if (req.query.api_version === 'v0') {
// Rewrite /api/v1/* → /api/* for route matching
req.url = req.url.replace(/^\/api\/v1/, '/api');
res.setHeader('Deprecation', 'true');
res.setHeader('Sunset', 'Sat, 01 Jul 2026 00:00:00 GMT');
}
next();
});
// Brute-force / credential-stuffing guard (#588). Runs immediately before the
// auth middleware on every protected route; a spike in failures/lockouts is
// surfaced via the trivela_auth_* counters and structured warn logs.
const authGuard = createAuthLockout({
softThreshold: authLockoutSoftThreshold,
hardThreshold: authLockoutHardThreshold,
baseLockoutMs: authLockoutBaseMs,
timeProvider: authLockoutOptions.timeProvider,
delayFn: authLockoutOptions.delayFn,
store: authLockoutOptions.store,
onFailure: ({ key, failures }) => {
metrics.authFailures += 1;
log.warn({ key, failures }, 'Failed authentication attempt');
},
onLockout: ({ key, failures, lockoutMs, lockoutCount }) => {
metrics.authLockouts += 1;
log.warn(
{ key, failures, lockoutMs, lockoutCount },
'Authentication lockout triggered (possible brute-force)',
);
},
});
// Auth middlewares are exposed as [authGuard, requireX] arrays; Express
// flattens nested handler arrays, so existing route registrations pick up the
// guard with no change. Only auth-bearing routes are guarded, which keeps a
// 200 on a public route from ever resetting an attacker's failure counter.
const requireApiKey = [
authGuard,
createApiKeyAuth({
apiKeys:
/** @type {string} */ (options.apiKeys) ??
/** @type {string} */ (options.apiKey) ??
process.env.TRIVELA_API_KEYS ??
process.env.TRIVELA_API_KEY ??
'',
apiKeyRepository: options.apiKeyRepository ?? apiKeyRepository,
orgMemberRepository: options.orgMemberRepository ?? orgMemberRepository,
}),
];
const requireMasterKey = [
authGuard,
createMasterKeyAuth({
masterKey: /** @type {string} */ (options.masterKey) ?? process.env.TRIVELA_MASTER_KEY ?? '',
}),
];
const requireAdminMasterKey = requireMasterKey;
let rateLimitStore = null;
let usageRedisClient = null;
const redisUrl = process.env.REDIS_URL || process.env.REDIS_HOST;
if (redisUrl && !options.disableRedis) {
try {
const redisClient = new Redis(redisUrl, {
maxRetriesPerRequest: 3,
enableReadyCheck: true,
lazyConnect: false,
});
redisClient.on('error', (err) => {
log.error({ err }, 'Redis connection error');
});
rateLimitStore = createRedisStore(redisClient);
usageRedisClient = redisClient;
log.info(
{ redisUrl: redisUrl.replace(/:[^:@]+@/, ':***@') },
'Rate limiter using Redis store',
);
} catch (error) {
log.warn(
{ err: error },
'Failed to connect to Redis, falling back to in-memory rate limiter',
);
}
}
// Distributed lock — Redis when available, in-process Map otherwise (#564)
const lockTtlMs = normalizePositiveInteger(
/** @type {any} */ (options.lockTtlMs) ?? process.env.LOCK_TTL_MS,
30_000,
);
const lockProvider =
options.lockProvider ??
(usageRedisClient
? createDistributedLock(usageRedisClient, { ttlMs: lockTtlMs })
: createInMemoryLock({ ttlMs: lockTtlMs }));
// Data export job — daily CSV export to object storage (#562)
const exportRetentionDays = normalizePositiveInteger(
/** @type {any} */ (options.exportRetentionDays) ?? process.env.EXPORT_RETENTION_DAYS,
30,
);
const exportJob = createExportJob({
db: dal.db,
storage: storageAdapter,
logger: log,
retentionDays: exportRetentionDays,
uploadDir: process.env.UPLOAD_DIR ?? './uploads',
});
const eventIndexer = createEventIndexer({
db: dal.db,
rpcPool,
logger: log,
referralBonus: normalizePositiveInteger(
/** @type {any} */ (options.referralBonus) ?? process.env.REFERRAL_BONUS,
0,
),
});
// Durable job queue store — persistent across restarts (#565)
const jobQueueStore = createSqliteJobQueueRepository({ db: dal.db });
const usageMeteringService = createUsageMeteringService({
usageRepository,
redisClient: usageRedisClient ?? /** @type {any} */ (options.usageRedisClient) ?? null,
timeProvider: /** @type {any} */ (options.usageMeteringService)?.timeProvider,
});
const stopUsageFlush = usageMeteringService.startFlushInterval();
const usageMeteringMiddleware = createUsageMeteringMiddleware({ usageMeteringService });
const rateLimiter = createRateLimiter({
windowMs: rateLimitWindowMs,
maxRequests: rateLimitMaxRequests,
timeProvider: /** @type {any} */ (options.rateLimit)?.timeProvider,
store: rateLimitStore,
});
app.use(requestId);
app.use(compression({ threshold: 1024 }));
app.use(cors(createCorsOptions(allowedOrigins)));
app.use(securityHeaders);
app.use(createDeprecationMiddleware({ log }));
app.use(traceparentMiddleware());
app.use(requestLogger);
app.use(express.json({ limit: jsonBodyLimit }));
const uploadDir = process.env.UPLOAD_DIR ?? './uploads';
if ((process.env.STORAGE_BACKEND ?? 'local') === 'local') {
app.use('/uploads', express.static(uploadDir));
}
app.use(
(
/** @type {any} */ err,
/** @type {import('express').Request} */ _req,
/** @type {import('express').Response} */ res,
/** @type {import('express').NextFunction} */ next,
) => {
if (err?.type === 'entity.too.large') {
return res.status(413).json({ error: 'Request body too large', code: 'PAYLOAD_TOO_LARGE' });
}
return next(err);
},
);
app.use(
(
/** @type {import('express').Request} */ req,
/** @type {import('express').Response} */ res,
/** @type {import('express').NextFunction} */ next,
) => {
metrics.requestTotal += 1;
const _reqStart = Date.now();
res.on('finish', () => {
const routeKey = `${req.method} ${req.path}`;
metrics.routeHits.set(routeKey, (metrics.routeHits.get(routeKey) ?? 0) + 1);
if (res.statusCode >= 400) {
metrics.requestErrors += 1;
}
// Record request duration into the latency histogram.
const durationMs = Date.now() - _reqStart;
metrics.latencySum += durationMs;
metrics.latencyTotal += 1;
for (let _bi = 0; _bi < metrics.latencyBuckets.length; _bi++) {
if (durationMs <= metrics.latencyBuckets[_bi]) {
metrics.latencyCounts[_bi] += 1;
break;
}
}
});
next();
},
);
const SCHEMA_VERSION_HEADER = 'X-Trivela-Schema-Version';
const SCHEMA_VERSION = '1';
app.use(
(
/** @type {import('express').Request} */ req,
/** @type {import('express').Response} */ res,
/** @type {import('express').NextFunction} */ next,
) => {
res.setHeader(SCHEMA_VERSION_HEADER, SCHEMA_VERSION);
const requestedVersion = req.get(SCHEMA_VERSION_HEADER);
if (requestedVersion && requestedVersion !== SCHEMA_VERSION) {
return res.status(400).json({
error: 'Unsupported API schema version',
code: 'UNSUPPORTED_SCHEMA_VERSION',
supported: SCHEMA_VERSION,
requested: requestedVersion,
});
}
return next();
},
);
const jobMaxAttempts = normalizePositiveInteger(
/** @type {any} */ (options.jobMaxAttempts) ?? process.env.JOB_MAX_RETRIES,
5,
);
const jobBaseDelayMs = normalizePositiveInteger(
/** @type {any} */ (options.jobBaseDelayMs) ?? process.env.JOB_BASE_DELAY_MS,
1_000,
);
const jobMaxDelayMs = normalizePositiveInteger(
/** @type {any} */ (options.jobMaxDelayMs) ?? process.env.JOB_MAX_DELAY_MS,
30_000,
);
const jobRunner = createJobRunner({
handlers: {
async rpc_health_poll() {
for (const url of rpcPool.getUrls()) {
const result = await checkSorobanRpcHealth({ rpcUrl: url, fetchImpl });
if (/** @type {any} */ (result).status === 'ok') {
rpcPool.markHealthy(url);
} else {
rpcPool.markUnhealthy(url);
}
}
const rpcUrl = rpcPool.getHealthyRpcUrl();
const rpc = await checkSorobanRpcHealth({ rpcUrl, fetchImpl });
rpcHealthCache.payload = rpc;
rpcHealthCache.updatedAt = new Date().toISOString();
},
async webhook_retry_failed_deliveries() {
await webhookService.retryFailedDeliveries();
},
async data_export({ date }) {
await exportJob.run(date);
},
},
logger: log,
deadLetter: failedJobRepository,
lockProvider,
defaultMaxAttempts: jobMaxAttempts,
defaultBaseDelayMs: jobBaseDelayMs,
defaultMaxDelayMs: jobMaxDelayMs,
});
if (!options.disableJobs && rpcPollIntervalMs > 0) {
jobRunner.enqueue('rpc_health_poll', null);
setInterval(() => jobRunner.enqueue('rpc_health_poll', null), rpcPollIntervalMs).unref?.();
}
// Enqueue webhook retry job every 5 minutes (Issue #352)
if (!options.disableJobs) {
const webhookRetryIntervalMs = 5 * 60 * 1000; // 5 minutes
jobRunner.enqueue('webhook_retry_failed_deliveries', null);
setInterval(
() => jobRunner.enqueue('webhook_retry_failed_deliveries', null),
webhookRetryIntervalMs,
).unref?.();
}
// Daily data export — idempotent, safe to fire on every startup (#562)
if (!options.disableJobs) {
const doExport = () =>
jobRunner.enqueue('data_export', { date: new Date().toISOString().slice(0, 10) });
doExport();
setInterval(doExport, 24 * 60 * 60 * 1_000).unref?.();
}
// Durable job queue — starts poll loop and recovers stale jobs from prior crashes (#565)
const durableJobQueue = createDurableJobQueue({
store: jobQueueStore,
handlers: {},
logger: log,
deadLetter: failedJobRepository,
});
if (!options.disableJobs) {
durableJobQueue.start();
}
// #552 — Operator balance monitoring job
const operatorBalanceJob = createOperatorBalanceJob({
db: dal.db,
stellarConfig,
metrics,
env: process.env,
logger: log,
});
if (!options.disableJobs) {
operatorBalanceJob.start();
}
async function buildHealthPayload() {
const rpcUrl = rpcPool.getHealthyRpcUrl();
const rpc = rpcHealthCache.payload ?? (await checkSorobanRpcHealth({ rpcUrl, fetchImpl }));
return {
status: /** @type {any} */ (rpc).status === 'ok' ? 'ok' : 'degraded',
service: 'trivela-api',
timestamp: new Date().toISOString(),
rpc,
rpcPool: rpcPool.getStatus(),
};
}
/** @param {import('express').Request} req @returns {string} */
function formatAuditActor(req) {
const apiKey = req?.auth?.type === 'apiKey' ? req.auth.apiKey : '';
if (!apiKey) return 'anonymous';
const key = String(apiKey);
if (key.length <= 8) return 'apiKey:***';
return `apiKey:${key.slice(0, 4)}...${key.slice(-4)}`;
}
/**
* @param {import('express').Request} req
* @param {{ action: string, entity: string, entityId: string, diff: unknown }} entry
*/
function recordAuditEntry(req, { action, entity, entityId, diff }) {
try {
auditLogRepository.create({
actor: formatAuditActor(req),
action,
entity,
entityId,
diff,
orgId: req.auth?.orgId || null,
timestamp: new Date().toISOString(),
});
} catch (error) {
log.warn({ err: error }, 'Failed to record audit entry');
}
}
let isShuttingDown = false;
app.get('/health', async (_req, res) => {
const payload = await buildHealthPayload();
res.json(payload);
});
app.get('/ready', (_req, res) => {
if (isShuttingDown) {
return res.status(503).json({ status: 'shutting_down', ready: false });
}
return res.json({ status: 'ok', ready: true });
});
const siteOrigin =
process.env.SITE_ORIGIN ?? allowedOrigins.find((origin) => origin !== '*') ?? '';
// Embed endpoints use a tighter per-IP rate limit (30 req/min) to guard
// against scraping while still allowing reasonable widget traffic.
const embedRateLimiter = createRateLimiter({
windowMs: rateLimitWindowMs,
maxRequests: Math.min(30, rateLimitMaxRequests),
timeProvider: /** @type {any} */ (options.rateLimit)?.timeProvider,
store: rateLimitStore,
});
app.get(
'/embed/campaign/:id',
embedRateLimiter,
createEmbedRoute(campaignRepository, siteOrigin, {
embedSecret: process.env.EMBED_ATTRIBUTION_SECRET,
}),
);
app.get('/health/rpc', async (_req, res) => {
const rpcUrl = rpcPool.getHealthyRpcUrl();
const rpc = await checkSorobanRpcHealth({ rpcUrl, fetchImpl });
if (/** @type {any} */ (rpc).status !== 'ok') {
rpcPool.markUnhealthy(rpcUrl);
}
res.status(/** @type {any} */ (rpc).status === 'ok' ? 200 : 503).json({
...rpc,
rpcPool: rpcPool.getStatus(),
});
});
app.get('/health/indexer', (_req, res) => {
const health = eventIndexer?.getHealth?.() ?? {
status: 'unavailable',
lastLedger: 0,
lagLedgers: 0,
eventsTotal: 0,
errorsTotal: 0,
};
const isHealthy = health.status === 'ok' || health.status === 'idle';
res.status(isHealthy ? 200 : 503).json(health);
});
app.get('/metrics', (_req, res) => {
const uptimeSeconds = process.uptime();
const routeLines = [...metrics.routeHits.entries()]
.map(([route, count]) => {
const escapedRoute = route.replace(/\\/g, '\\\\').replace(/"/g, '\\"');
return `trivela_route_hits_total{route="${escapedRoute}"} ${count}`;
})
.join('\n');
// Latency histogram — cumulative buckets (le = upper bound in ms).
const latencyBucketLines = metrics.latencyBuckets
.map((le, i) => {
const cumulative = metrics.latencyCounts.slice(0, i + 1).reduce((a, b) => a + b, 0);
const leLabel = le === Infinity ? '+Inf' : String(le);
return `trivela_http_request_duration_ms_bucket{le="${leLabel}"} ${cumulative}`;
})
.join('\n');
// RPC pool saturation metrics.
const poolStatus = rpcPool.getStatus();
const payload = [
'# HELP trivela_requests_total Total HTTP requests handled.',
'# TYPE trivela_requests_total counter',
`trivela_requests_total ${metrics.requestTotal}`,
'# HELP trivela_request_errors_total Total HTTP requests with status >= 400.',
'# TYPE trivela_request_errors_total counter',
`trivela_request_errors_total ${metrics.requestErrors}`,
'# HELP trivela_auth_failures_total Total failed authentication attempts on guarded routes.',
'# TYPE trivela_auth_failures_total counter',
`trivela_auth_failures_total ${metrics.authFailures}`,
'# HELP trivela_auth_lockouts_total Total brute-force lockouts triggered on guarded routes.',
'# TYPE trivela_auth_lockouts_total counter',
`trivela_auth_lockouts_total ${metrics.authLockouts}`,
'# HELP trivela_process_uptime_seconds Node.js process uptime.',
'# TYPE trivela_process_uptime_seconds gauge',
`trivela_process_uptime_seconds ${uptimeSeconds.toFixed(3)}`,
'# HELP trivela_route_hits_total Route-level request counts.',
'# TYPE trivela_route_hits_total counter',
routeLines,
// Request latency histogram (issue #650 — p95 latency SLO).
'# HELP trivela_http_request_duration_ms HTTP request duration in milliseconds.',
'# TYPE trivela_http_request_duration_ms histogram',
latencyBucketLines,
`trivela_http_request_duration_ms_count ${metrics.latencyTotal}`,
`trivela_http_request_duration_ms_sum ${metrics.latencySum}`,
// RPC pool saturation (issue #650 — pool saturation safety).
'# HELP trivela_rpc_pool_in_use RPC pool slots currently in use.',
'# TYPE trivela_rpc_pool_in_use gauge',
`trivela_rpc_pool_in_use ${poolStatus.in_use}`,
'# HELP trivela_rpc_pool_idle RPC pool slots immediately available.',
'# TYPE trivela_rpc_pool_idle gauge',
`trivela_rpc_pool_idle ${poolStatus.idle}`,
'# HELP trivela_rpc_pool_waiting Callers queued waiting for a pool slot.',
'# TYPE trivela_rpc_pool_waiting gauge',
`trivela_rpc_pool_waiting ${poolStatus.waiting}`,
'# HELP trivela_rpc_pool_healthy Healthy RPC endpoints in the pool.',
'# TYPE trivela_rpc_pool_healthy gauge',
`trivela_rpc_pool_healthy ${poolStatus.healthy}`,
'# HELP trivela_rpc_pool_unhealthy Unhealthy RPC endpoints in the pool.',
'# TYPE trivela_rpc_pool_unhealthy gauge',
`trivela_rpc_pool_unhealthy ${poolStatus.unhealthy}`,
// Indexer metrics (#532).
...Object.entries(eventIndexer?.getMetrics?.() ?? {}).map(([key, value]) => [
`# HELP ${key.replace(/_/g, ' ')} Indexer metric.`,
`# TYPE ${key} gauge`,
`${key} ${value}`,
]).flat(),
]
.filter(Boolean)
.join('\n');
res.set('Content-Type', 'text/plain; version=0.0.4; charset=utf-8');
res.send(`${payload}\n`);
});
/** @param {import('express').Request} req @param {import('express').Response} res */
function apiInfo(req, res) {
const usingLegacyPrefix =
req.path.startsWith(LEGACY_API_PREFIX) && !req.path.startsWith(API_V1_PREFIX);
res.json({
name: 'Trivela API',
version: '0.1.0',
prefix: API_V1_PREFIX,
endpoints: {
health: 'GET /health',
ready: 'GET /ready',
healthRpc: 'GET /health/rpc',
metrics: 'GET /metrics',
info: `GET ${API_V1_PREFIX}`,
campaigns: `GET ${API_V1_PREFIX}/campaigns`,
campaignById: `GET ${API_V1_PREFIX}/campaigns/:id`,
campaignBySlug: `GET ${API_V1_PREFIX}/campaigns/by-slug/:slug`,
createCampaign: `POST ${API_V1_PREFIX}/campaigns`,
cloneCampaign: `POST ${API_V1_PREFIX}/campaigns/:id/clone`,
updateCampaign: `PUT ${API_V1_PREFIX}/campaigns/:id`,
deleteCampaign: `DELETE ${API_V1_PREFIX}/campaigns/:id`,
auditLogs: `GET ${API_V1_PREFIX}/audit-logs`,
usage: `GET ${API_V1_PREFIX}/usage`,
adminUsage: `GET ${API_V1_PREFIX}/admin/usage`,
adminUsageQuotas: `PUT ${API_V1_PREFIX}/admin/usage/quotas`,
config: `GET ${API_V1_PREFIX}/config`,
explorer: `GET ${API_V1_PREFIX}/explorer`,
},
compatibility: {
legacyPrefix: LEGACY_API_PREFIX,
legacyRoutesSupported: true,
migrationNote:
'Prefer /api/v1/* routes. Legacy /api/* routes remain available for compatibility.',
usingLegacyPrefix,
},
stellar: {
...stellarConfig,
},
config: {
rewardsContractId: rewardsContractId || null,
campaignContractId: campaignContractId || null,
},
cors: {
allowedOrigins,
},
rateLimit: {
keying: 'per API key when present, otherwise per IP address',
windowMs: rateLimitWindowMs,
maxRequests: rateLimitMaxRequests,
},
authLockout: {
keying: 'per client IP address',
softThreshold: authLockoutSoftThreshold,
hardThreshold: authLockoutHardThreshold,
baseLockoutMs: authLockoutBaseMs,
},
body: {
jsonLimit: jsonBodyLimit,
},
});
}
/** @param {import('express').Request} _req @param {import('express').Response} res */
function getPublicConfig(_req, res) {
res.json({
stellar: {
...stellarConfig,
},
contracts: {
rewards: rewardsContractId || null,
campaign: campaignContractId || null,
},
});
}
/** @param {import('express').Request} _req @param {import('express').Response} res */
function getExplorerLinks(_req, res) {
res.json({
network: stellarConfig.network,
explorerUrl: stellarConfig.explorerUrl,
});
}
/** @param {import('express').Request} req @param {import('express').Response} res */
function listCampaigns(req, res) {
const cacheKey = `campaigns:${req.originalUrl}`;
const cached = shortCache.get(cacheKey);
if (cached && cached.expiresAt > Date.now()) {
return res.set('x-cache', 'HIT').json(cached.payload);
}
const activeRaw =
typeof req.query.active === 'string' ? req.query.active.toLowerCase() : undefined;
const activeFilter = activeRaw === 'true' ? true : activeRaw === 'false' ? false : undefined;
const q = typeof req.query.q === 'string' ? req.query.q.trim() : '';
const sort = typeof req.query.sort === 'string' ? req.query.sort : undefined;
const order =
req.query.order === 'asc' ? 'asc' : req.query.order === 'desc' ? 'desc' : undefined;
const category = typeof req.query.category === 'string' ? req.query.category.trim() : undefined;
const tagsRaw = typeof req.query.tags === 'string' ? req.query.tags.trim() : '';
const tags = tagsRaw
? tagsRaw
.split(',')
.map((t) => t.trim())
.filter(Boolean)
: undefined;
// Status filtering (Issue #457)
// By default, only show published campaigns to public API
// API key holders can request draft/archived/all statuses
const statusRaw = typeof req.query.status === 'string' ? req.query.status.trim() : undefined;
const hasApiKey = req.context?.apiKeyRecord !== undefined;
let status = statusRaw;
if (statusRaw && ['draft', 'archived', 'all'].includes(statusRaw) && !hasApiKey) {
// Require API key for non-published statuses
return res.status(401).json({
error: 'API key required to access draft, archived, or all campaigns',
code: 'UNAUTHORIZED',
});
}
// Default to published only for public API
if (!status && !hasApiKey) {
status = 'published';
}
// Handle urgency sorting separately since it requires application-level logic
const isUrgencySort = sort === 'urgency';
const dbSort = isUrgencySort ? undefined : sort;
const dbOrder = isUrgencySort ? undefined : order;
const items = campaignRepository.list({
active: activeFilter,
q,
sort: dbSort,
order: dbOrder,
category,
tags,
status,
});
// Apply urgency sorting if requested
let sortedItems = items;
if (isUrgencySort) {
const { sortByUrgency } = await import('./utils/urgency.js');
sortedItems = sortByUrgency(items);
}
const payload = paginateItems(sortedItems, req.query);
shortCache.set(cacheKey, {
expiresAt: Date.now() + shortCacheTtlMs,
payload,