-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
233 lines (206 loc) · 8.8 KB
/
Copy pathserver.ts
File metadata and controls
233 lines (206 loc) · 8.8 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
import "./workers/batch.processor.js"
/**
* VERIDAQ Fastify server entry point.
*
* Plugin registration order matters:
* 1. Infrastructure plugins (cors, helmet, cookie, rate-limit, multipart)
* 2. Auth plugin (registers JWT helpers used by route preHandlers)
* 3. Route plugins
* 4. Swagger (registers after routes so all schemas are available)
*/
import cookie from "@fastify/cookie"
import cors from "@fastify/cors"
import helmet from "@fastify/helmet"
import multipart from "@fastify/multipart"
import rateLimit from "@fastify/rate-limit"
import swagger from "@fastify/swagger"
import swaggerUi from "@fastify/swagger-ui"
import Fastify from "fastify"
import { config } from "./config/index.js"
import { authPlugin } from "./plugins/auth.js"
import { prismaPlugin } from "./plugins/prisma.js"
import { redisPlugin } from "./plugins/redis.js"
import { adminRoutes } from "./routes/admin.js"
import { authRoutes } from "./routes/auth.js"
import { employerRoutes } from "./routes/employer.js"
import { institutionRoutes } from "./routes/institution.js"
import { crossmintRoutes } from "./routes/crossmint.js"
import { earningsRoutes } from "./routes/earnings.js"
import { paymentRoutes } from "./routes/payment.js"
import { statsRoutes } from "./routes/stats.js"
import { verificationRoutes } from "./routes/verification.js"
const loggerConfig =
config.NODE_ENV === "production"
? { level: "warn" }
: { level: "info", transport: { target: "pino-pretty", options: { colorize: true } } }
const app = Fastify({
logger: loggerConfig,
// Limit request bodies to 10 MB. Excel files with thousands of rows are
// typically well under this; raise it if institutions report failures.
bodyLimit: 10 * 1024 * 1024,
// Trust the Railway proxy so req.protocol reflects x-forwarded-proto.
// Without this, cookies would always think they're on HTTP (internal
// proxy connection) and would set secure=false, breaking cross-origin auth.
trustProxy: true,
})
async function bootstrap() {
const extensionOrigins = (config.EXTENSION_ORIGINS ?? "")
.split(",")
.map((origin) => origin.trim())
.filter(Boolean)
// Security headers
await app.register(helmet, {
contentSecurityPolicy: config.NODE_ENV === "production",
})
// CORS — allow the configured frontend URL and any Railway
// subdomain (dynamic `.up.railway.app` origins). Railway
// generates per-service subdomains that the user can't predict
// at build time, so a static list won't work.
const isRailwayOrigin = (origin: string) =>
origin.endsWith(".up.railway.app") ||
/^https:\/\/[a-z0-9-]+\.railway\.app$/.test(origin)
await app.register(cors, {
origin: (origin, cb) => {
if (!origin) return cb(null, true)
if (
origin === config.FRONTEND_URL ||
isRailwayOrigin(origin) ||
extensionOrigins.includes(origin)
) {
return cb(null, true)
}
return cb(new Error("Origin not allowed"), false)
},
credentials: true,
methods: ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"],
})
// Cookie support — used for httpOnly JWT refresh tokens
await app.register(cookie, {
secret: config.JWT_SECRET,
})
// Rate limiting — apply globally; tighten on auth routes in the route plugin
await app.register(rateLimit, {
max: 300,
timeWindow: "1 minute",
redis: app.redis, // uses the redis plugin registered below
})
// Multipart — for Excel file uploads (max 10 MB per file)
await app.register(multipart, { limits: { fileSize: 10 * 1024 * 1024 } })
// Database and cache
await app.register(prismaPlugin)
await app.register(redisPlugin)
// Fix any institutions with non-hex onChainId (legacy seed bug)
const crypto = await import("crypto")
try {
const badInstitutions = await app.prisma.$queryRaw<{ id: string; on_chain_id: string; kyc_approved: boolean }[]>`
SELECT id, "onChainId" as on_chain_id, "kycApproved" as kyc_approved FROM institutions
WHERE "onChainId" !~ '^0x[0-9a-f]{64}$'
`
for (const inst of badInstitutions) {
const newOnChainId = "0x" + crypto.createHash("sha256").update(inst.id).digest("hex")
await app.prisma.institution.update({
where: { id: inst.id },
data: { onChainId: newOnChainId, blockchainStatus: inst.kyc_approved ? "PENDING" : "NOT_REGISTERED" },
})
app.log.warn({ institutionId: inst.id, oldOnChainId: inst.on_chain_id, newOnChainId }, "Fixed non-hex onChainId")
}
} catch (err) {
app.log.warn({ err }, "onChainId migration skipped — table may not exist yet")
}
// Validate platform admin wallet at startup
try {
const { privateKeyToAccount } = await import("viem/accounts")
const rawKey = config.PLATFORM_ADMIN_PRIVATE_KEY
if (rawKey) {
const key = rawKey.startsWith("0x") ? rawKey : `0x${rawKey}`
const acct = privateKeyToAccount(key as `0x${string}`)
app.log.info({ address: acct.address }, "Platform admin wallet validated")
} else {
app.log.error("PLATFORM_ADMIN_PRIVATE_KEY is not set — batch registration will fail")
}
} catch (err) {
app.log.error({ err }, "CRITICAL: PLATFORM_ADMIN_PRIVATE_KEY is invalid — batch registration will fail")
}
// Auth plugin — registers jwtVerify, jwtSign, and role-check decorators
await app.register(authPlugin)
// API documentation (available at /docs in non-production environments)
if (config.NODE_ENV !== "production") {
await app.register(swagger, {
openapi: {
info: {
title: "VERIDAQ API",
version: "1.0.0",
description: "Privacy-preserving credential verification platform.",
},
components: {
securitySchemes: { bearerAuth: { type: "http", scheme: "bearer", bearerFormat: "JWT" } },
},
},
})
await app.register(swaggerUi, { routePrefix: "/docs" })
}
// ── Public routes (no auth) ─────────────────────────────────────
// Must be registered before any plugin that adds auth hooks,
// because Fastify parent hooks propagate to all child contexts.
await app.register(async function publicRoutes(publicApp) {
const { VerificationService } = await import("./services/verification.service.js")
const verifySvc = new VerificationService(publicApp.prisma)
publicApp.get("/api/verify/check/:id", async (req, rep) => {
const { id } = req.params as { id: string }
if (!id) return rep.code(400).send({ error: "Missing verification ID" })
const request = await verifySvc.getPublicRequest(id)
if (!request) return rep.code(404).send({ error: "Verification record not found" })
if (!request.result || !request.completedAt) {
return rep.code(202).send({ status: request.status, message: "Verification still processing" })
}
return {
id: request.id,
status: request.status,
result: request.result,
institution: request.institution?.name ?? null,
claimType: request.claimType,
threshold: request.threshold,
txHash: request.txHash,
completedAt: request.completedAt,
}
})
})
// Routes
await app.register(authRoutes, { prefix: "/api/auth" })
await app.register(institutionRoutes, { prefix: "/api/institution" })
await app.register(earningsRoutes, { prefix: "/api/earnings" })
await app.register(employerRoutes, { prefix: "/api/employer" })
await app.register(adminRoutes, { prefix: "/api/admin" })
await app.register(verificationRoutes, { prefix: "/api/verify" })
await app.register(paymentRoutes, { prefix: "/api/payment" })
await app.register(crossmintRoutes, { prefix: "/api/crossmint" })
await app.register(statsRoutes, { prefix: "/api/stats" })
// Auto-fix stuck PROCESSING verification requests from before the last restart
try {
const stuckCount = await app.prisma.verificationRequest.updateMany({
where: { status: "PROCESSING" },
data: {
status: "FAILED",
result: "CLAIM_NOT_SATISFIED",
completedAt: new Date(),
proofJson: JSON.stringify({ note: "Auto-failed on server restart — proof gen interrupted" }),
},
})
if (stuckCount.count > 0) {
app.log.warn({ count: stuckCount.count }, "Fixed stuck verification requests from prior session")
}
} catch (err) {
app.log.warn({ err }, "Failed to auto-fix stuck verification requests")
}
// Health check — used by Docker and load balancers
app.get("/health", async () => ({ status: "ok", ts: Date.now() }))
await app.listen({ port: config.PORT, host: "0.0.0.0" })
app.log.info(`Server running at http://0.0.0.0:${config.PORT}`)
if (config.NODE_ENV !== "production") {
app.log.info(`API docs at http://localhost:${config.PORT}/docs`)
}
}
bootstrap().catch((err) => {
console.error("Failed to start server:", err)
process.exit(1)
})