import useApp, {TestApp} from "./_app"; import Controller from "../src/Controller"; import CsrfProtectionComponent from "../src/components/CsrfProtectionComponent"; import supertest from "supertest"; let app: TestApp; useApp((addr, port) => { return app = new class extends TestApp { protected async init(): Promise { this.use(new class extends Controller { routes(): void { this.get('/', (req, res, next) => { res.render('test/csrf.njk'); }, 'csrf_test'); this.post('/', (req, res, next) => { res.json({ status: 'ok', }); }, 'csrf_test'); } }()); await super.init(); } protected registerComponents() { super.registerComponents(); this.use(new CsrfProtectionComponent()); } }(addr, port); }); describe('Test CSRF protection', () => { let cookies: string[]; let csrf: string; test('no csrf token should be in session at first', (done) => { const agent = supertest(app.getExpressApp()); agent.post('/') .expect(401, (err, res) => { if (err) return done(err); expect(res.text).toContain(`You weren't assigned any CSRF token.`); cookies = res.get('Set-Cookie'); agent.get('/') .set('Cookie', cookies) .expect(200, (err, res) => { if (err) return done(err); csrf = res.text; done(); }); }); }); test('sending no csrf token should fail', (done) => { expect(cookies).toBeDefined(); const agent = supertest(app.getExpressApp()); agent.post('/') .set('Cookie', cookies) .expect(401) .end((err, res) => { if (err) return done(err); expect(res.text).toContain(`You didn't provide any CSRF token.`); done(); }); }); test('sending an invalid csrf token should fail', (done) => { expect(cookies).toBeDefined(); const agent = supertest(app.getExpressApp()); agent.post('/') .set('Cookie', cookies) .set('Content-Type', 'application/json') .send({csrf: 'not_a_valid_csrf'}) .expect(401, (err, res) => { if (err) return done(err); expect(res.text).toContain(`Tokens don't match.`); done(); }); }); test('sending a valid csrf token should success', (done) => { expect(cookies).toBeDefined(); const agent = supertest(app.getExpressApp()); agent.post('/') .set('Cookie', cookies) .set('Content-Type', 'application/json') .send({csrf: csrf}) .expect(200, done); }); });