forked from Emmy123222/Stellar-MicroPay
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
324 lines (283 loc) · 12.4 KB
/
Copy pathserver.js
File metadata and controls
324 lines (283 loc) · 12.4 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
/**
* src/server.js
* Express server entry point for Stellar MicroPay backend.
*/
"use strict";
const express = require("express");
const cors = require("cors");
const cookieParser = require("cookie-parser");
const compression = require("compression");
const helmet = require("helmet");
const pinoHttp = require("pino-http");
const rateLimit = require("express-rate-limit");
require("dotenv").config();
const Sentry = require("@sentry/node");
const accountRoutes = require("./routes/accounts");
const authRoutes = require("./routes/auth");
const paymentRoutes = require("./routes/payments");
const analyticsRoutes = require("./routes/analytics");
const healthRoutes = require("./routes/health");
const federationRoutes = require("./routes/federation");
const turretsRoutes = require("./routes/turrets");
const tipsRoutes = require("./routes/tips");
const webhookRoutes = require("./routes/webhooks");
const swaggerUi = require("swagger-ui-express");
const swaggerSpec = require("./swagger");
const { startTurretsServer } = require("./turretsServer");
const { resumeAllMonitors } = require("./services/paymentMonitor");
const logger = require("./utils/logger");
const { validateEnv, parseAllowedOrigins } = require("./config/validateEnv");
const app = express();
const PORT = process.env.PORT || 4000;
// ─── Error message sanitization (#206) ───────────────────────────────────────
// Stellar secret keys: 'S' + 55 base32 chars [A-Z2-7]. Strip before logging or
// sending to Sentry/clients so a mis-routed key never appears in outputs.
const STELLAR_SECRET_PATTERN = /S[A-Z2-7]{55}/g;
function sanitizeMessage(msg) {
return typeof msg === "string" ? msg.replace(STELLAR_SECRET_PATTERN, "[REDACTED]") : msg;
}
// ─── Sentry ───────────────────────────────────────────────────────────────────
Sentry.init({
dsn: process.env.SENTRY_DSN,
environment: process.env.NODE_ENV || "development",
// Only enable in production unless SENTRY_DSN is explicitly set
enabled: !!process.env.SENTRY_DSN,
tracesSampleRate: 0.2,
// #206: strip Stellar secret keys from error messages before Sentry receives them
beforeSend(event) {
if (event.exception?.values) {
event.exception.values = event.exception.values.map((v) => ({
...v,
value: sanitizeMessage(v.value),
}));
}
return event;
},
});
function stripProtocol(value) {
return String(value || "")
.replace(/^https?:\/\//i, "")
.replace(/\/.*$/, "")
.trim();
}
function getFederationDomain(req) {
return stripProtocol(
process.env.FEDERATION_DOMAIN ||
process.env.DOMAIN ||
process.env.HOME_DOMAIN ||
req.get("host") ||
"stellarmicropay.io"
);
}
function getFederationServerUrl(req) {
if (process.env.FEDERATION_SERVER_URL) {
return process.env.FEDERATION_SERVER_URL;
}
const domain = getFederationDomain(req);
const protocol =
process.env.FEDERATION_SERVER_PROTOCOL ||
(domain.startsWith("localhost") || domain.startsWith("127.0.0.1") ? "http" : "https");
return `${protocol}://${domain}/federation`;
}
// ─── Middleware ───────────────────────────────────────────────────────────────
/**
* Content-Security-Policy directives for this JSON API.
*
* The backend serves no HTML pages of its own except Swagger UI at /api/docs,
* so the policy is intentionally restrictive:
*
* defaultSrc – block everything not listed explicitly.
* scriptSrc – only same-origin scripts (Swagger UI bundles its own JS).
* styleSrc – same-origin + unsafe-inline (Swagger UI injects inline styles).
* imgSrc – same-origin + data URIs (Swagger UI logo).
* connectSrc – only same-origin fetch/XHR (all API calls go to self).
* fontSrc – same-origin only.
* objectSrc – none (no Flash / plugins).
* frameSrc – none (not embedded in iframes).
* upgradeInsecureRequests – omitted intentionally; handled at the load-balancer
* level in production.
*
* Helmet v7+ ships with CSP *disabled* by default, so this must be explicit.
*/
const helmetOptions = {
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'"],
styleSrc: ["'self'", "'unsafe-inline'"],
imgSrc: ["'self'", "data:"],
connectSrc: ["'self'"],
fontSrc: ["'self'"],
objectSrc: ["'none'"],
frameSrc: ["'none'"],
// Disallow this API from being framed by any site (clickjacking defence,
// the CSP-level equivalent of X-Frame-Options: DENY).
frameAncestors: ["'none'"],
// Forbid <base> tag hijacking and form posts to third-party origins.
baseUri: ["'self'"],
formAction: ["'self'"],
},
},
// HTTP Strict Transport Security — force HTTPS for two years, cover subdomains,
// and allow browser-preload-list inclusion. TLS is terminated at the
// load-balancer, so the header is emitted here for clients that reach us
// directly over HTTPS.
hsts: {
maxAge: 63072000, // 2 years
includeSubDomains: true,
preload: true,
},
// Send no referrer to other origins (avoids leaking API paths / tokens in
// Referer headers).
referrerPolicy: { policy: "no-referrer" },
// This JSON API should never be embedded cross-origin, nor share its window.
crossOriginResourcePolicy: { policy: "same-site" },
crossOriginOpenerPolicy: { policy: "same-origin" },
// Belt-and-braces clickjacking header for older clients that ignore CSP.
frameguard: { action: "deny" },
// Block Adobe cross-domain policy files.
permittedCrossDomainPolicies: { permittedPolicies: "none" },
};
// Remove the framework fingerprint header (helmet also does this, but disabling
// at the Express level guarantees it even if helmet config changes).
app.disable("x-powered-by");
app.use(helmet(helmetOptions));
// gzip/brotli-negotiated response compression (#611) — shrinks JSON payloads
// before they hit the wire. Must run before routes register their handlers so
// res.write/res.end get wrapped for every response. SSE streams are excluded so
// EventSource can receive incremental chunks without buffering delays.
app.use(
compression({
filter: (req, res) => {
if (req.path?.endsWith("/stream")) {
return false;
}
return compression.filter(req, res);
},
})
);
// Structured JSON request logging (#269) — replaces morgan('dev'); reuses the
// shared pino logger so HTTP logs are machine-parseable (Datadog/CloudWatch).
app.use(pinoHttp({ logger }));
app.use(express.json({ limit: "10kb" }));
// Parses the Cookie header into req.cookies so the SEP-0010 session cookie
// (set in routes/auth.js) can be read back by middleware/auth.js's
// extractToken and by the CSRF origin check (#780).
app.use(cookieParser());
// JSON parsing error handler
app.use((err, req, res, next) => {
if (err instanceof SyntaxError && err.status === 400 && "body" in err) {
return res.status(400).json({ error: "Invalid JSON body" });
}
next();
});
// CORS
// parseAllowedOrigins validates format at startup (see validateEnv.js) and
// returns the trimmed list of origins that are safe to use at runtime.
// Any malformed entries cause process.exit(1) before this line is reached.
const { origins: allowedOrigins } = parseAllowedOrigins(process.env.ALLOWED_ORIGINS);
app.use(
cors({
origin: (origin, callback) => {
// Allow requests with no origin (e.g. curl, Postman)
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error(`CORS: origin ${origin} not allowed`));
}
},
methods: ["GET", "POST", "DELETE"],
allowedHeaders: ["Content-Type", "Authorization"],
credentials: true,
})
);
// ─── Health route (exempt from rate limiting) ─────────────────────────────────
app.use("/health", healthRoutes);
app.use("/api/health", healthRoutes);
// Stellar SEP-0001 discovery document. Wallets and SDKs read this file to
// discover the SEP-0002 federation endpoint for `name*domain` addresses.
app.get("/.well-known/stellar.toml", (req, res) => {
const serverUrl = getFederationServerUrl(req);
const tomlContent = `# Stellar MicroPay federation discovery
FEDERATION_SERVER="${serverUrl}"
`;
res.setHeader("Content-Type", "application/toml; charset=utf-8");
res.send(tomlContent);
});
// Global rate limiting — 100 requests per 15 minutes per IP.
// standardHeaders: true → emits RateLimit-Limit, RateLimit-Remaining, RateLimit-Reset (RFC 6585 draft-7).
// legacyHeaders: false → suppresses deprecated X-RateLimit-* headers.
// Clients should inspect RateLimit-Remaining and back off when it approaches 0.
const limiter = rateLimit({
windowMs: 15 * 60 * 1000,
max: 100,
standardHeaders: true,
legacyHeaders: false,
message: { error: "Too many requests, please try again later." },
});
app.use(limiter);
// ─── API Versioning & Deprecation Policy (#853) ────────────────────────────────
const { apiDeprecationHeader } = require("./middleware/deprecation");
// Primary Versioned Routes (/api/v1/*)
app.use("/api/v1/auth", authRoutes);
app.use("/api/v1/accounts", accountRoutes);
app.use("/api/v1/payments", paymentRoutes);
app.use("/api/v1/webhooks", webhookRoutes);
app.use("/api/v1/analytics", analyticsRoutes);
app.use("/api/v1/turrets", turretsRoutes);
app.use("/api/v1/tips", tipsRoutes);
app.use("/api/v1/health", healthRoutes);
// Legacy Unversioned Routes (/api/*) — includes HTTP Deprecation & Sunset headers
app.use("/api/auth", apiDeprecationHeader, authRoutes);
app.use("/api/accounts", apiDeprecationHeader, accountRoutes);
app.use("/api/payments", apiDeprecationHeader, paymentRoutes);
app.use("/api/webhooks", apiDeprecationHeader, webhookRoutes);
app.use("/api/analytics", apiDeprecationHeader, analyticsRoutes);
app.use("/api/turrets", apiDeprecationHeader, turretsRoutes);
app.use("/api/tips", apiDeprecationHeader, tipsRoutes);
app.use("/federation", federationRoutes);
// ─── API Documentation ─────────────────────────────────────────────────────────
app.use(
"/api/docs",
swaggerUi.serve,
swaggerUi.setup(swaggerSpec, {
customSiteTitle: "Stellar MicroPay API Docs",
customCss: ".swagger-ui .topbar { display: none }",
swaggerOptions: { url: "/api/docs.json" },
})
);
app.get("/api/docs.json", (req, res) => {
res.setHeader("Content-Type", "application/json");
res.send(swaggerSpec);
});
// ─── 404 Handler ───────────────────────────────────────────────────────────────
app.use((req, res) => {
const sanitizedPath = req.path.replace(/[\r\n]/g, "");
logger.warn({ method: req.method, path: sanitizedPath }, "Route not found");
res.status(404).json({ error: "Route not found" });
});
// ─── Error Handling ────────────────────────────────────────────────────────────
// Sentry must capture errors before the generic handler responds
Sentry.setupExpressErrorHandler(app);
app.use((err, req, res, next) => {
void next;
const status = err.status || 500;
const message = sanitizeMessage(err.message) || "Internal Server Error";
logger.error({ status, message }, "Request error");
res.status(status).json({ error: message });
});
// ─── Start ────────────────────────────────────────────────────────────────────
if (require.main === module) {
validateEnv();
app.listen(PORT, () => {
console.log(`
✨ Stellar MicroPay API
🚀 Server running at http://localhost:${PORT}
🌐 Network: ${process.env.STELLAR_NETWORK || "testnet"}
`);
});
startTurretsServer();
// Resume SSE monitoring for all webhooks that existed before restart
resumeAllMonitors();
}
module.exports = app;