-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
178 lines (153 loc) · 6.91 KB
/
Copy pathserver.js
File metadata and controls
178 lines (153 loc) · 6.91 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
import Fastify from 'fastify';
import cors from '@fastify/cors';
import registerDemoPlaintext from './routes/demo-plaintext.js';
import registerDemoProtected from './routes/demo-protected.js';
import registerUserData from './routes/user-data.js';
import registerProducts from './routes/products.js';
import registerApiKey from './routes/api-key.js';
import registerFormSubmit from './routes/form-submit.js';
import registerRateLimit from './routes/rate-limit.js';
import registerAuthLogin from './routes/auth-login.js';
import registerAnalytics from './routes/analytics.js';
// ============================================================================
// FISE Configuration
// ============================================================================
// Rules are now imported from shared-rules.js
// Each demo uses specific rules as defined in the shared configuration
// ============================================================================
// Fastify Server Setup
// ============================================================================
const fastify = Fastify({
logger: true // Simple logging without pino-pretty
});
// Enable CORS for frontend access
// Allow all origins for demo purposes
await fastify.register(cors, {
origin: true, // Allow all origins
credentials: true,
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With'],
preflight: true, // Explicitly enable preflight handling
strictPreflight: false // Allow preflight even if not configured
});
// ============================================================================
// API Routes
// ============================================================================
// Health check
fastify.get('/health', async (request, reply) => {
return { status: 'ok', timestamp: new Date().toISOString() };
});
// Register all demo routes
registerUserData(fastify);
registerProducts(fastify);
registerApiKey(fastify);
registerFormSubmit(fastify);
registerRateLimit(fastify);
registerAuthLogin(fastify);
registerAnalytics(fastify);
// Demo routes registered via modules
registerDemoPlaintext(fastify);
registerDemoProtected(fastify);
// ============================================================================
// Error Handling
// ============================================================================
fastify.setErrorHandler((error, request, reply) => {
fastify.log.error(error);
reply.code(error.statusCode || 500).send({
error: error.message || 'Internal Server Error',
statusCode: error.statusCode || 500
});
});
// ============================================================================
// Export for Vercel Serverless
// ============================================================================
// Singleton pattern to avoid re-initializing Fastify on every request
let isReady = false;
// Export the Fastify instance for Vercel serverless functions
export default async (req, res) => {
try {
// Initialize Fastify only once (singleton pattern for serverless)
if (!isReady) {
await fastify.ready();
isReady = true;
}
// Get origin from request headers
const origin = req.headers.origin || '*';
// Handle CORS preflight explicitly for Vercel
if (req.method === 'OPTIONS') {
res.setHeader('Access-Control-Allow-Origin', origin);
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.setHeader('Access-Control-Max-Age', '86400');
res.statusCode = 200;
return res.end();
}
// Intercept res.writeHead to inject CORS headers
const originalWriteHead = res.writeHead;
res.writeHead = function(statusCode, statusMessage, headers) {
// Handle both writeHead(status, headers) and writeHead(status, message, headers)
let finalHeaders = headers;
if (typeof statusMessage === 'object') {
finalHeaders = statusMessage;
}
finalHeaders = finalHeaders || {};
finalHeaders['Access-Control-Allow-Origin'] = origin;
finalHeaders['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS';
finalHeaders['Access-Control-Allow-Headers'] = 'Content-Type, Authorization, X-Requested-With';
finalHeaders['Access-Control-Allow-Credentials'] = 'true';
if (typeof statusMessage === 'object') {
return originalWriteHead.call(this, statusCode, finalHeaders);
} else {
return originalWriteHead.call(this, statusCode, statusMessage, finalHeaders);
}
};
// Ensure request has required properties
if (!req.url) {
req.url = req.path || '/';
}
if (!req.method) {
req.method = 'GET';
}
// Use Fastify's server to handle the request
// Vercel's req/res are Node.js IncomingMessage/ServerResponse, which Fastify can handle
fastify.server.emit('request', req, res);
} catch (error) {
fastify.log.error(error);
if (!res.headersSent) {
res.statusCode = 500;
res.setHeader('Access-Control-Allow-Origin', req.headers.origin || '*');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.end(JSON.stringify({ error: 'Internal Server Error' }));
}
}
};
// ============================================================================
// Start Server (for local development)
// ============================================================================
// Only start the server if not running on Vercel
if (process.env.VERCEL !== '1') {
const PORT = process.env.PORT || 3008;
const HOST = process.env.HOST || '0.0.0.0';
try {
await fastify.listen({ port: PORT, host: HOST });
console.log('\n🚀 FISE Fastify Demo Server Started!');
console.log(`📡 Server running at: http://localhost:${PORT}`);
console.log('\n📋 Available endpoints:');
console.log(' GET /health');
console.log(' GET /user/:id');
console.log(' GET /products');
console.log(' POST /generate-key');
console.log(' POST /submit-form');
console.log(' GET /limited-resource?token=...');
console.log(' POST /auth/login');
console.log(' GET /analytics?page=1&limit=10');
console.log('\n🧪 Demo endpoints:');
console.log(' GET /demo/plaintext (unprotected)');
console.log(' GET /demo/protected (FISE-protected)');
console.log(`\n💡 Try: curl http://localhost:${PORT}/demo/protected\n`);
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
}