-
Notifications
You must be signed in to change notification settings - Fork 158
Expand file tree
/
Copy pathindex.ts
More file actions
259 lines (228 loc) · 6.94 KB
/
index.ts
File metadata and controls
259 lines (228 loc) · 6.94 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
import express, { Express } from 'express';
import session from 'express-session';
import http from 'http';
import https from 'https';
import fs from 'fs';
import cors from 'cors';
import path from 'path';
import rateLimit from 'express-rate-limit';
import lusca from 'lusca';
import * as config from '../config';
import * as db from '../db';
import { serverConfig } from '../config/env';
import { Proxy } from '../proxy';
import routes from './routes';
import { configure } from './passport';
const limiter = rateLimit(config.getRateLimit());
const { GIT_PROXY_UI_PORT: uiPort, GIT_PROXY_HTTPS_UI_PORT: uiHttpsPort } = serverConfig;
const DEFAULT_SESSION_MAX_AGE_HOURS = 12;
const app: Express = express();
let _httpServer: http.Server | null = null;
let _httpsServer: https.Server | null = null;
const getServiceTLSOptions = () => ({
key:
config.getTLSEnabled() && config.getTLSKeyPemPath()
? fs.readFileSync(config.getTLSKeyPemPath()!)
: undefined,
cert:
config.getTLSEnabled() && config.getTLSCertPemPath()
? fs.readFileSync(config.getTLSCertPemPath()!)
: undefined,
});
/**
* CORS Configuration
*
* Environment Variable: ALLOWED_ORIGINS
*
* Configuration Options:
* 1. Production (restrictive): ALLOWED_ORIGINS='https://gitproxy.company.com,https://gitproxy-staging.company.com'
* 2. Development (permissive): ALLOWED_ORIGINS='*'
* 3. Local dev with Vite: ALLOWED_ORIGINS='http://localhost:3000'
* 4. Same-origin only: Leave ALLOWED_ORIGINS unset or empty
*
* Examples:
* - Single origin: ALLOWED_ORIGINS='https://example.com'
* - Multiple origins: ALLOWED_ORIGINS='http://localhost:3000,https://example.com'
* - All origins (testing): ALLOWED_ORIGINS='*'
* - Same-origin only: ALLOWED_ORIGINS='' or unset
*/
/**
* Parse ALLOWED_ORIGINS environment variable
* Supports:
* - '*' for all origins
* - Comma-separated list of origins: 'http://localhost:3000,https://example.com'
* - Empty/undefined for same-origin only
*/
function getAllowedOrigins(): string[] | '*' | undefined {
const allowedOrigins = process.env.ALLOWED_ORIGINS;
if (!allowedOrigins) {
return undefined; // No CORS, same-origin only
}
if (allowedOrigins === '*') {
return '*'; // Allow all origins
}
// Parse comma-separated list
return allowedOrigins
.split(',')
.map((origin) => origin.trim())
.filter(Boolean);
}
/**
* CORS origin callback - determines if origin is allowed
*/
function corsOriginCallback(
origin: string | undefined,
callback: (err: Error | null, allow?: boolean) => void,
) {
const allowedOrigins = getAllowedOrigins();
// Allow all origins
if (allowedOrigins === '*') {
return callback(null, true);
}
// No ALLOWED_ORIGINS set - only allow same-origin (no origin header)
if (!allowedOrigins) {
if (!origin) {
return callback(null, true); // Same-origin requests don't have origin header
}
return callback(null, false);
}
// Check if origin is in the allowed list
if (!origin || allowedOrigins.includes(origin)) {
return callback(null, true);
}
callback(new Error('Not allowed by CORS'));
}
const corsOptions: cors.CorsOptions = {
origin: corsOriginCallback,
credentials: true, // Allow credentials (cookies, authorization headers)
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'X-CSRF-TOKEN'],
exposedHeaders: ['Set-Cookie'],
maxAge: 86400, // 24 hours
};
/**
* Internal function used to bootstrap the Git Proxy API's express application.
* @param {Proxy} proxy A reference to the proxy, used to restart it when necessary.
* @return {Promise<Express>} the express application
*/
async function createApp(proxy: Proxy): Promise<Express> {
// configuration of passport is async
// Before we can bind the routes - we need the passport strategy
const passport = await configure();
const absBuildPath = path.join(__dirname, '../../build');
app.use(cors(corsOptions));
app.set('trust proxy', 1);
app.use(limiter);
app.use(
session({
store: db.getSessionStore(),
secret: config.getCookieSecret(),
resave: false,
saveUninitialized: false,
cookie: {
secure: 'auto',
httpOnly: true,
maxAge: (config.getSessionMaxAgeHours() || DEFAULT_SESSION_MAX_AGE_HOURS) * 60 * 60 * 1000,
},
}),
);
if (config.getCSRFProtection() && process.env.NODE_ENV !== 'test') {
app.use(
lusca({
csrf: {
cookie: { name: 'csrf' },
},
hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },
nosniff: true,
referrerPolicy: 'same-origin',
xframe: 'SAMEORIGIN',
xssProtection: true,
}),
);
}
app.use(passport.initialize());
app.use(passport.session());
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use('/', routes(proxy));
app.use('/', express.static(absBuildPath));
app.get('/*path', (_req, res) => {
res.sendFile(path.join(`${absBuildPath}/index.html`));
});
return app;
}
/**
* Starts the proxy service.
* @param {Proxy} proxy A reference to the proxy, used to restart it when necessary.
* @return {Promise<Express>} the express application (used for testing).
*/
async function start(proxy: Proxy) {
if (!proxy) {
console.warn("WARNING: proxy is null and can't be controlled by the API service");
}
const app = await createApp(proxy);
_httpServer = http.createServer(app);
_httpServer.listen(uiPort);
console.log(`Service Listening on ${uiPort}`);
app.emit('ready');
if (config.getTLSEnabled()) {
await new Promise<void>((resolve, reject) => {
const server = https.createServer(getServiceTLSOptions(), app);
server.on('error', reject);
server.listen(uiHttpsPort, () => {
console.log(`HTTPS Service Listening on ${uiHttpsPort}`);
resolve();
});
_httpsServer = server;
});
}
return app;
}
/**
* Stops the proxy service.
*/
async function stop(): Promise<void> {
const closePromises: Promise<void>[] = [];
if (_httpServer) {
closePromises.push(
new Promise((resolve, reject) => {
console.log(`Stopping Service Listening on ${uiPort}`);
_httpServer!.close((err) => {
if (err) {
reject(err);
} else {
console.log('Service stopped');
_httpServer = null;
resolve();
}
});
}),
);
}
if (_httpsServer) {
closePromises.push(
new Promise((resolve, reject) => {
_httpsServer!.close((err) => {
if (err) {
reject(err);
} else {
console.log('HTTPS Service stopped');
_httpsServer = null;
resolve();
}
});
}),
);
}
return Promise.all(closePromises).then(() => {});
}
export const Service = {
start,
stop,
get httpServer() {
return _httpServer;
},
get httpsServer() {
return _httpsServer;
},
};