Skip to content

Commit 17a18dd

Browse files
committed
feat: add conditional CSRF protection based on user agents
1 parent ed9abb4 commit 17a18dd

File tree

1 file changed

+34
-12
lines changed

1 file changed

+34
-12
lines changed

src/service/index.ts

Lines changed: 34 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -55,19 +55,41 @@ async function createApp(proxy: Proxy): Promise<Express> {
5555
}),
5656
);
5757
if (config.getCSRFProtection() && process.env.NODE_ENV !== 'test') {
58-
app.use(
59-
lusca({
60-
csrf: {
61-
cookie: { name: 'csrf' },
62-
},
63-
hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },
64-
nosniff: true,
65-
referrerPolicy: 'same-origin',
66-
xframe: 'SAMEORIGIN',
67-
xssProtection: true,
68-
}),
69-
);
58+
const luscaBase = lusca({
59+
hsts: { maxAge: 31536000, includeSubDomains: true, preload: true },
60+
nosniff: true,
61+
referrerPolicy: 'same-origin',
62+
xframe: 'SAMEORIGIN',
63+
xssProtection: true,
64+
});
65+
const luscaCsrf = lusca({
66+
csrf: {
67+
cookie: { name: 'csrf' },
68+
},
69+
});
70+
71+
app.use((req, res, next) => {
72+
const userAgent = req.headers['user-agent'] || '';
73+
const origin = req.headers['origin'] || '';
74+
const referer = req.headers['referer'] || '';
75+
const isCli = req.headers['x-client-type'] === 'cli' || userAgent.includes('git-proxy-cli');
76+
console.log('origin, referer, isCli', origin, referer, isCli);
77+
console.log('userAgent', userAgent);
78+
const browserAgentLookups = ['Mozilla', 'AppleWebKit', 'Chrome', 'Safari', 'Firefox', 'Edge'];
79+
const isBrowserRequest = browserAgentLookups.some((lookup) => userAgent.includes(lookup));
80+
if (isCli || (!origin && !referer && !isBrowserRequest)) {
81+
console.log('isCli or no origin or referer or browser request');
82+
return luscaBase(req, res, next);
83+
}
84+
85+
luscaBase(req, res, (err) => {
86+
console.log('is browser request');
87+
if (err) return next(err);
88+
luscaCsrf(req, res, next);
89+
});
90+
});
7091
}
92+
7193
app.use(passport.initialize());
7294
app.use(passport.session());
7395
app.use(express.json());

0 commit comments

Comments
 (0)