-
Notifications
You must be signed in to change notification settings - Fork 93
Expand file tree
/
Copy pathserver.js
More file actions
382 lines (346 loc) · 11.4 KB
/
server.js
File metadata and controls
382 lines (346 loc) · 11.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
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
// Copyright(C) 2025-2026 Advanced Micro Devices, Inc. All rights reserved.
// SPDX-License-Identifier: MIT
/**
* GAIA SDK Documentation Proxy Server
*
* Auth proxy for Mintlify-hosted documentation with access code protection.
* Proxies authenticated requests to the Mintlify site.
*
* Environment Variables:
* DOCS_AUTH_ENABLED - Set to 'true' to require access code
* DOCS_ACCESS_CODE - The access code users must enter
* MINTLIFY_URL - The Mintlify site URL (default: https://amd-gaia.ai)
* PORT - Server port (default: 3000)
*/
require('dotenv').config();
const express = require('express');
const rateLimit = require('express-rate-limit');
const { createProxyMiddleware } = require('http-proxy-middleware');
const cookieParser = require('cookie-parser');
const crypto = require('crypto');
const url = require('url');
const app = express();
const PORT = process.env.PORT || 3000;
// Configuration
const AUTH_ENABLED = process.env.DOCS_AUTH_ENABLED === 'true';
const ACCESS_CODE = process.env.DOCS_ACCESS_CODE || '';
const MINTLIFY_URL = process.env.MINTLIFY_URL || 'https://amd-gaia.ai';
const COOKIE_SECRET = process.env.COOKIE_SECRET || crypto.randomBytes(32).toString('hex');
const COOKIE_NAME = 'gaia_docs_auth';
const COOKIE_MAX_AGE = 7 * 24 * 60 * 60 * 1000; // 7 days
// Server-side redirect storage (nonce -> { url, expires })
// Redirect URLs are stored server-side to prevent user-controlled data in redirects
const pendingRedirects = new Map();
const NONCE_MAX_AGE = 10 * 60 * 1000; // 10 minutes
// Middleware
app.use(cookieParser(COOKIE_SECRET));
app.use(express.urlencoded({ extended: true }));
// Generate auth token from access code
function generateToken(code) {
return crypto.createHmac('sha256', COOKIE_SECRET).update(code).digest('hex');
}
// Verify auth token
function verifyToken(token) {
if (!ACCESS_CODE) return false;
const expected = generateToken(ACCESS_CODE);
return token === expected;
}
// Sanitize redirect URL to prevent open redirect attacks
function sanitizeRedirect(url) {
// Must start with / but not // (protocol-relative URLs)
if (url && typeof url === 'string' && url.startsWith('/') && !url.startsWith('//')) {
return url;
}
return '/';
}
// Store a redirect URL server-side and return a nonce for form submission
function storeRedirect(redirectUrl) {
const nonce = crypto.randomBytes(16).toString('hex');
const safeUrl = sanitizeRedirect(redirectUrl);
pendingRedirects.set(nonce, { url: safeUrl, expires: Date.now() + NONCE_MAX_AGE });
// Clean up expired nonces
for (const [key, value] of pendingRedirects) {
if (Date.now() > value.expires) {
pendingRedirects.delete(key);
}
}
return nonce;
}
// Retrieve and consume a stored redirect URL by nonce
function consumeRedirect(nonce) {
if (!nonce || typeof nonce !== 'string') return '/';
const entry = pendingRedirects.get(nonce);
if (entry && Date.now() <= entry.expires) {
pendingRedirects.delete(nonce);
return entry.url;
}
return '/';
}
// HTML-escape a string to prevent XSS
function escapeHtml(str) {
return str
.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
}
// Login page HTML - uses nonce (not redirect URL) in form to prevent open redirect
function getLoginPage(nonce) {
const safeNonce = escapeHtml(nonce);
return `
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>GAIA SDK Documentation - Access Required</title>
<style>
* { box-sizing: border-box; margin: 0; padding: 0; }
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: linear-gradient(135deg, #0a0a0a 0%, #1a1a2e 100%);
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
color: #fff;
}
.container {
background: rgba(255, 255, 255, 0.05);
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.1);
border-radius: 16px;
padding: 48px;
max-width: 420px;
width: 90%;
text-align: center;
}
.logo {
width: 80px;
height: 80px;
margin-bottom: 24px;
}
h1 {
font-size: 24px;
font-weight: 600;
margin-bottom: 8px;
}
.subtitle {
color: rgba(255, 255, 255, 0.6);
font-size: 14px;
margin-bottom: 32px;
}
.form-group {
margin-bottom: 24px;
}
input[type="password"] {
width: 100%;
padding: 14px 16px;
font-size: 16px;
border: 1px solid rgba(255, 255, 255, 0.2);
border-radius: 8px;
background: rgba(0, 0, 0, 0.3);
color: #fff;
outline: none;
transition: border-color 0.2s;
}
input[type="password"]:focus {
border-color: #ED1C24;
}
input[type="password"]::placeholder {
color: rgba(255, 255, 255, 0.4);
}
button {
width: 100%;
padding: 14px 24px;
font-size: 16px;
font-weight: 600;
border: none;
border-radius: 8px;
background: #ED1C24;
color: #fff;
cursor: pointer;
transition: background 0.2s, transform 0.1s;
}
button:hover {
background: #c8171e;
}
button:active {
transform: scale(0.98);
}
.error {
background: rgba(237, 28, 36, 0.2);
border: 1px solid rgba(237, 28, 36, 0.3);
color: #ff6b6b;
padding: 12px;
border-radius: 8px;
margin-bottom: 24px;
font-size: 14px;
}
.footer {
margin-top: 32px;
font-size: 12px;
color: rgba(255, 255, 255, 0.4);
}
.footer a {
color: rgba(255, 255, 255, 0.6);
text-decoration: none;
}
.footer a:hover {
color: #ED1C24;
}
</style>
</head>
<body>
<div class="container">
<svg class="logo" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
<circle cx="50" cy="50" r="45" stroke="#ED1C24" stroke-width="4" fill="none"/>
<text x="50" y="58" text-anchor="middle" fill="#ED1C24" font-size="24" font-weight="bold" font-family="sans-serif">GAIA</text>
</svg>
<h1>GAIA SDK Documentation</h1>
<p class="subtitle">This documentation is access-restricted. Please enter the access code to continue.</p>
{{ERROR}}
<form method="POST" action="/auth/login">
<input type="hidden" name="nonce" value="${safeNonce}">
<div class="form-group">
<input type="password" name="code" placeholder="Enter access code" required autofocus>
</div>
<button type="submit">Access Documentation</button>
</form>
<p class="footer">
Need access? Contact <a href="https://github.com/amd/gaia">GAIA team</a>
</p>
</div>
</body>
</html>
`;
}
// Health check endpoint (must be before auth middleware)
app.get('/health', (req, res) => {
res.status(200).json({ status: 'ok', auth: AUTH_ENABLED, target: MINTLIFY_URL });
});
// Auth middleware
function authMiddleware(req, res, next) {
// Skip auth if disabled
if (!AUTH_ENABLED) {
return next();
}
// Skip auth for login/logout routes and health check
if (req.path.startsWith('/auth/') || req.path === '/health') {
return next();
}
// Check for valid auth cookie
const token = req.signedCookies[COOKIE_NAME];
if (token && verifyToken(token)) {
return next();
}
// Store redirect URL server-side and use nonce in form
const originalUrl = req.originalUrl || req.url || '/';
const nonce = storeRedirect(originalUrl);
res.status(401).send(getLoginPage(nonce).replace('{{ERROR}}', ''));
}
// Rate limit login attempts
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 10, // limit each IP to 10 login attempts per windowMs
message: 'Too many login attempts. Please try again later.',
standardHeaders: true,
legacyHeaders: false,
});
// Login handler
app.post('/auth/login', loginLimiter, (req, res) => {
const { code, nonce } = req.body;
if (code === ACCESS_CODE) {
// Set signed cookie
const token = generateToken(code);
res.cookie(COOKIE_NAME, token, {
signed: true,
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
maxAge: COOKIE_MAX_AGE,
sameSite: 'lax'
});
// Retrieve redirect URL from server-side storage and validate with url.parse()
const target = consumeRedirect(nonce);
const parsed = url.parse(target || '');
// Only redirect to relative paths (no host/protocol) to prevent open redirects
if (!parsed.host && !parsed.protocol && parsed.pathname) {
// Sanitize pathname to prevent protocol-relative URLs (e.g., //evil.com)
const safePath = parsed.pathname.startsWith('/') && !parsed.pathname.startsWith('//') ? parsed.pathname : '/';
res.redirect(303, safePath);
} else {
res.redirect(303, '/');
}
} else {
// Retrieve the original redirect URL and re-store with a new nonce for retry
const originalRedirect = consumeRedirect(nonce);
const newNonce = storeRedirect(originalRedirect);
res.redirect(`/auth/login-error?nonce=${newNonce}`);
}
});
// Login error handler (uses nonce to retrieve redirect URL)
app.get('/auth/login-error', (req, res) => {
// Retrieve redirect URL from server-side storage and re-store for the form
const originalRedirect = consumeRedirect(req.query.nonce);
const newNonce = storeRedirect(originalRedirect);
const errorHtml = '<div class="error">Invalid access code. Please try again.</div>';
res.status(401).send(getLoginPage(newNonce).replace('{{ERROR}}', errorHtml));
});
// Logout handler
app.get('/auth/logout', (req, res) => {
res.clearCookie(COOKIE_NAME);
res.redirect('/');
});
// Simple in-memory rate limiter for general requests (no external dependencies)
const rateLimitStore = new Map();
const RATE_LIMIT_WINDOW = 60 * 1000; // 1 minute
const RATE_LIMIT_MAX = 100; // max requests per window
function rateLimiter(req, res, next) {
const ip = req.ip || req.connection.remoteAddress;
const now = Date.now();
const record = rateLimitStore.get(ip) || { count: 0, resetAt: now + RATE_LIMIT_WINDOW };
if (now > record.resetAt) {
record.count = 0;
record.resetAt = now + RATE_LIMIT_WINDOW;
}
record.count++;
rateLimitStore.set(ip, record);
if (record.count > RATE_LIMIT_MAX) {
return res.status(429).send('Too Many Requests');
}
next();
}
// Apply rate limiter before auth middleware
app.use(rateLimiter);
// Apply auth middleware
app.use(authMiddleware);
// Proxy to Mintlify site (after auth)
const proxyMiddleware = createProxyMiddleware({
target: MINTLIFY_URL,
changeOrigin: true,
secure: true,
// Don't modify the path
pathRewrite: null,
// Handle proxy errors
on: {
error: (err, req, res) => {
console.error('Proxy error:', err.message);
res.status(502).send('Documentation temporarily unavailable. Please try again later.');
},
proxyReq: (proxyReq, req, res) => {
// Remove cookies from proxied request (Mintlify doesn't need our auth cookies)
proxyReq.removeHeader('cookie');
}
}
});
app.use('/', proxyMiddleware);
// Start server
app.listen(PORT, () => {
console.log(`GAIA Docs Proxy running on port ${PORT}`);
console.log(`Proxying to: ${MINTLIFY_URL}`);
console.log(`Auth protection: ${AUTH_ENABLED ? 'ENABLED' : 'DISABLED'}`);
if (AUTH_ENABLED && !ACCESS_CODE) {
console.warn('WARNING: Auth is enabled but DOCS_ACCESS_CODE is not set!');
}
});