-
Notifications
You must be signed in to change notification settings - Fork 21
Expand file tree
/
Copy pathindex.js
More file actions
505 lines (460 loc) · 16.5 KB
/
index.js
File metadata and controls
505 lines (460 loc) · 16.5 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
require("dotenv").config();
const express = require("express");
const cors = require("cors");
const path = require("path");
const fs = require("fs");
const { randomUUID } = require("crypto");
const multer = require("multer");
const sharp = require("sharp");
// Swagger
const swaggerUi = require("swagger-ui-express");
const swaggerSpecs = require("./src/swagger");
// Sentry Error Tracking
const { SentryService, createSentryMiddleware } = require("./src/services/sentryService");
const sentryService = new SentryService();
// Services & Config
const { loadConfig } = require("./src/config");
const { AppDatabase } = require("./src/db/appDatabase");
const { ActorAuthService } = require("./src/services/actorAuthService");
const { NotificationService } = require("./src/services/notificationService");
const { SorobanLeaseService } = require("./src/services/sorobanLeaseService");
const { LeaseRenewalService } = require("./src/services/leaseRenewalService");
const {
LeaseRenewalJob,
startLeaseRenewalScheduler,
} = require("./src/jobs/leaseRenewalJob");
const {
RentPaymentTrackerService,
} = require("./services/rentPaymentTrackerService");
const { startPaymentTrackerJob } = require("./src/jobs/paymentTrackerJob");
const { createPaymentRoutes } = require("./src/routes/paymentRoutes");
const { LateFeeJob, startLateFeeScheduler } = require("./src/jobs/lateFeeJob");
const { LateFeeService } = require("./src/services/lateFeeService");
const { LateFeeController } = require("./src/controllers/LateFeeController");
const { createLateFeeRoutes } = require("./src/routes/lateFeeRoutes");
const {
getUSDCToFiatRates,
getXLMToUSDCPath,
} = require("./services/priceFeedService");
const AvailabilityService = require("./services/availabilityService");
const AssetMetadataService = require("./services/assetMetadataService");
const AutoReclaimWorker = require("./services/autoReclaimWorker");
const {
createConditionProofService,
} = require("./services/conditionProofService");
const {
createFileConditionProofStore,
} = require("./services/conditionProofStore");
const {
createSecurityDepositLockService,
requireLockedSecurityDeposit,
} = require("./services/securityDepositLock");
const {
TenantCreditScoreAggregator,
} = require("./tenantCreditScoreAggregator");
const { LeasePartitioningService } = require("./src/services/leasePartitioningService");
const { LeaseArchivalJob } = require("./src/jobs/leaseArchivalJob");
// Routes
const leaseRoutes = require("./src/routes/leaseRoutes");
const ownerRoutes = require("./src/routes/ownerRoutes");
const kycRoutes = require("./src/routes/kycRoutes");
const sanctionsRoutes = require("./src/routes/sanctionsRoutes");
const evictionNoticeRoutes = require("./src/routes/evictionNoticeRoutes");
const vendorRoutes = require("./src/routes/vendorRoutes");
const taxRoutes = require("./src/routes/taxRoutes");
const propertyRoutes = require("./src/routes/propertyRoutes");
const marketTrendsRoutes = require("./src/routes/marketTrendsRoutes");
const referralRoutes = require("./src/routes/referralRoutes");
const { LeaseCacheService } = require("./src/services/LeaseCacheService");
// Audit Service
const { AuditService } = require("./src/services/auditService");
const { createAuditRoutes } = require("./src/routes/auditRoutes");
/**
* Build authentication middleware for landlords and tenants.
*
* @param {ActorAuthService} actorAuthService Auth service.
* @returns {import('express').RequestHandler}
*/
function requireActorAuth(actorAuthService) {
return (req, res, next) => {
const authHeader = req.headers.authorization || "";
if (!authHeader.startsWith("Bearer ")) {
return res
.status(401)
.json({ success: false, error: "Authentication required" });
}
const token = authHeader.slice("Bearer ".length).trim();
try {
req.actor = actorAuthService.verifyToken(token);
return next();
} catch (error) {
return res.status(401).json({ success: false, error: error.message });
}
};
}
/**
* Create the Express app with injectable services for testing.
*/
function createApp(dependencies = {}) {
const app = express();
const config = dependencies.config || loadConfig();
const database =
dependencies.database || new AppDatabase(config.database.filename);
// Dependencies & Services
const actorAuthService =
dependencies.actorAuthService || new ActorAuthService(config);
const notificationService =
dependencies.notificationService || new NotificationService(database);
const sorobanLeaseService =
dependencies.sorobanLeaseService || new SorobanLeaseService(config);
const leaseRenewalService =
dependencies.leaseRenewalService ||
new LeaseRenewalService(
database,
notificationService,
sorobanLeaseService,
config,
);
const lateFeeService =
dependencies.lateFeeService ||
new LateFeeService(database, notificationService, sorobanLeaseService);
const lateFeeController = new LateFeeController(lateFeeService);
const availabilityService =
dependencies.availabilityService || new AvailabilityService();
const assetMetadataService =
dependencies.assetMetadataService || new AssetMetadataService();
const creditScoreAggregator =
dependencies.creditScoreAggregator || new TenantCreditScoreAggregator();
const proofService =
dependencies.conditionProofService ||
createConditionProofService({ store: createFileConditionProofStore() });
const depositGatekeeper =
dependencies.securityDepositService || createSecurityDepositLockService();
const leaseCacheService = dependencies.leaseCacheService || new LeaseCacheService(database);
const leasePartitioningService =
dependencies.leasePartitioningService || new LeasePartitioningService(database);
// Inject for use in routes/controllers
app.locals.database = database;
app.locals.availabilityService = availabilityService;
app.locals.assetMetadataService = assetMetadataService;
app.locals.lateFeeService = lateFeeService;
app.locals.leaseCacheService = leaseCacheService;
app.locals.leasePartitioningService = leasePartitioningService;
// Middleware
app.use(cors());
app.use(express.json({ limit: "50mb" }));
app.use(express.urlencoded({ extended: true, limit: "50mb" }));
// Initialize Sentry
if (config.sentry?.dsn) {
sentryService.initialize(config.sentry);
app.use(createSentryMiddleware(sentryService));
}
// Audit Service
const auditService = new AuditService(database);
app.locals.auditService = auditService;
// Static Files
const uploadDir = path.join(__dirname, "uploads");
if (!fs.existsSync(uploadDir)) fs.mkdirSync(uploadDir, { recursive: true });
app.use("/uploads", express.static(uploadDir));
// Multer for image optimization
const storage = multer.diskStorage({
destination: (req, file, cb) => cb(null, uploadDir),
filename: (req, file, cb) => cb(null, `${Date.now()}_${file.originalname}`),
});
const upload = multer({ storage });
// Swagger Documentation
app.use("/api-docs", swaggerUi.serve, swaggerUi.setup(swaggerSpecs));
// --- Base Routes ---
app.get("/", (req, res) => {
res.json({
project: "LeaseFlow Protocol",
description: "Secure Lease Indexer and Storage Facilitator",
status: "Active",
version: "1.0.0",
contract_id:
config.contracts?.defaultContractId ||
"CAEGD57WVTVQSYWYB23AISBW334QO7WNA5XQ56S45GH6BP3D2AVHKUG4",
});
});
// Health Check Endpoint for Load Balancers and Monitoring
app.get("/health", (req, res) => {
const health = {
status: "ok",
timestamp: new Date().toISOString(),
uptime: process.uptime(),
environment: config.sentry?.environment || process.env.NODE_ENV || "development",
version: "1.0.0",
};
// Check database connectivity
try {
req.app.locals.database.db.prepare("SELECT 1").get();
health.database = "connected";
} catch (error) {
health.database = "disconnected";
health.status = "degraded";
}
// Check if Sentry monitoring is enabled
if (config.sentry?.dsn) {
health.monitoring = "enabled";
} else {
health.monitoring = "disabled";
}
// Check if audit logging is available
try {
req.app.locals.database.db.prepare("SELECT 1 FROM audit_log LIMIT 1").get();
health.audit_logging = "available";
} catch (error) {
health.audit_logging = "not_configured";
}
const statusCode = health.status === "ok" ? 200 : 503;
res.status(statusCode).json(health);
});
// --- API Routes ---
app.use('/api/leases', leaseRoutes);
app.use('/api/owners', ownerRoutes);
app.use('/api/kyc', kycRoutes);
app.use('/api/sanctions', sanctionsRoutes);
app.use('/api/eviction-notices', evictionNoticeRoutes);
app.use('/api/vendors', vendorRoutes);
app.use('/api/tax', taxRoutes);
app.use('/api/properties', propertyRoutes);
app.use('/api/market-trends', marketTrendsRoutes);
app.use('/api/referrals', referralRoutes);
app.use('/api', createPaymentRoutes(database));
app.use('/api/audit', createAuditRoutes(database));
// --- Lease Renewal Routes ---
app.get(
"/renewal-proposals/:proposalId",
requireActorAuth(actorAuthService),
(req, res) => {
try {
const proposal = leaseRenewalService.getProposalForActor({
proposalId: req.params.proposalId,
actorId: req.actor.id,
actorRole: req.actor.role,
});
res.status(200).json({ success: true, data: proposal });
} catch (error) {
res
.status(error.statusCode || 500)
.json({ success: false, error: error.message });
}
},
);
app.post(
"/renewal-proposals/:proposalId/accept",
requireActorAuth(actorAuthService),
(req, res) => {
try {
const result = leaseRenewalService.acceptProposal({
proposalId: req.params.proposalId,
actorId: req.actor.id,
actorRole: req.actor.role,
});
res.status(200).json({
success: true,
data: result.proposal,
warning: result.warning,
});
} catch (error) {
res
.status(error.statusCode || 500)
.json({ success: false, error: error.message });
}
},
);
// --- Credit Score Routes ---
app.post("/api/tenant-credit-score", (req, res) => {
try {
const { tenantId, metrics = {}, cacheTtlSeconds } = req.body || {};
const result = creditScoreAggregator.getOrCompute(
tenantId,
metrics,
cacheTtlSeconds,
);
res.status(200).json(result);
} catch (error) {
res.status(400).json({ error: error.message });
}
});
// --- Condition Proof Routes ---
app.post("/leases/:leaseId/condition-proofs", async (req, res) => {
try {
const proof = await proofService.createProof({
leaseId: req.params.leaseId,
moveInStartedAt: req.body?.move_in_started_at,
submittedAt: req.body?.submitted_at,
note: req.body?.note,
photos: req.body?.photos,
});
res.status(201).json(proof);
} catch (error) {
res.status(500).json({
error: "CONDITION_PROOF_CREATE_FAILED",
message: error.message,
});
}
});
// --- Security Deposit Routes ---
app.post(
"/move-in/generate-digital-key",
requireLockedSecurityDeposit({
action: "Generate Digital Key",
service: depositGatekeeper,
}),
(req, res) => {
res.status(200).json({
success: true,
message:
"Security deposit verified. Digital key generation is authorized.",
verification: req.securityDepositVerification,
});
},
);
// --- Price Feed Routes ---
app.get("/api/price-feed", async (req, res) => {
try {
const { currencies } = req.query;
const rates = await getUSDCToFiatRates(
currencies ? currencies.split(",") : ["ngn", "eur", "usd"],
);
res.json({ success: true, rates, base_currency: "USDC" });
} catch (error) {
res.status(500).json({ success: false, message: error.message });
}
});
// --- Image Optimization ---
app.post("/api/images/optimize", upload.single("image"), async (req, res) => {
try {
if (!req.file)
return res.status(400).json({ error: "No image file provided" });
const { width = 300, height = 300 } = req.query;
const outputPath = path.join(
uploadDir,
"optimized",
`${Date.now()}_optimized.webp`,
);
if (!fs.existsSync(path.dirname(outputPath)))
fs.mkdirSync(path.dirname(outputPath), { recursive: true });
await sharp(req.file.path)
.resize(parseInt(width), parseInt(height), { fit: "cover" })
.toFormat("webp", { quality: 80 })
.toFile(outputPath);
res.json({
success: true,
path: `/uploads/optimized/${path.basename(outputPath)}`,
});
} catch (error) {
res.status(500).json({ error: error.message });
}
});
// Error Handler
app.use((err, req, res, next) => {
// Log to Sentry if initialized
if (config.sentry?.dsn) {
sentryService.captureException(err, {
publicKey: req.actor?.publicKey,
leaseId: req.params.leaseId || req.body?.leaseId,
extra: {
path: req.path,
method: req.method,
body: req.body,
query: req.query,
},
});
}
console.error("[App] Error:", err);
res
.status(500)
.json({ error: "Internal server error.", details: err.message });
});
return app;
}
// Start Server if called directly
if (require.main === module) {
const config = loadConfig();
const app = createApp({ config });
const port = config.port || 3000;
// Initialize Background Services
const database = app.locals.database;
const availabilityService = app.locals.availabilityService;
const assetMetadataService = app.locals.assetMetadataService;
const initServices = async () => {
try {
await availabilityService.initialize();
} catch (e) {
console.warn("AvailabilityService failed to initialize:", e.message);
}
try {
await assetMetadataService.initialize();
} catch (e) {
console.warn(
"AssetMetadataService failed to initialize (Postgres might be down):",
e.message,
);
}
try {
await leasePartitioningService.initialize();
console.log("Lease partitioning service initialized");
} catch (e) {
console.warn(
"LeasePartitioningService failed to initialize:",
e.message,
);
}
};
initServices().finally(() => {
app.listen(port, () => {
console.log(`LeaseFlow Backend running at http://localhost:${port}`);
// Background Jobs
if (config.jobs?.renewalJobEnabled) {
const notificationService = new NotificationService(database);
const sorobanLeaseService = new SorobanLeaseService(config);
const leaseRenewalService = new LeaseRenewalService(
database,
notificationService,
sorobanLeaseService,
config,
);
startLeaseRenewalScheduler(
new LeaseRenewalJob(leaseRenewalService),
config,
);
console.log("Lease renewal scheduler started");
}
if (config.jobs?.lateFeeJobEnabled) {
const lateFeeService = app.locals.lateFeeService;
startLateFeeScheduler(new LateFeeJob(lateFeeService), config);
console.log("Late fee enforcement scheduler started");
}
const reclaimWorker = new AutoReclaimWorker();
// Payment Tracker
const paymentTrackerService = new RentPaymentTrackerService(database, {
contractAccountId: config.contracts?.defaultContractId,
});
startPaymentTrackerJob(paymentTrackerService, {
cronExpression: process.env.PAYMENT_TRACKER_CRON || "* * * * *",
});
console.log("Payment tracker job started");
reclaimWorker
.initialize()
.then(() => {
reclaimWorker.start();
})
.catch((err) => {
console.warn("AutoReclaimWorker failed to initialize:", err.message);
});
// Lease Archival Job (Task 2 - Table Partitioning)
if (config.jobs?.archivalJobEnabled) {
const archivalJob = new LeaseArchivalJob(leasePartitioningService, {
cronExpression: process.env.LEASE_ARCHIVAL_CRON || '0 2 1 * *',
monthsSinceExpiry: parseInt(process.env.LEASE_ARCHIVAL_MONTHS || '24', 10),
enabled: config.jobs.archivalJobEnabled
});
archivalJob.start();
console.log("Lease archival job started");
}
});
});
}
module.exports = { createApp };