aboutsummaryrefslogtreecommitdiff
path: root/test/cors.test.ts
blob: 621c263cf6e6bd6101f88260e2d4729dae50aef6 (plain) (blame)
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
import { describe, expect, it } from 'vitest';

import { PosthookServer } from '../src/server/index.js';

const corsHeaders = (corsOriginsRaw: string, origin: string | undefined) => {
    const server = new PosthookServer({} as any, {} as any, corsOriginsRaw);
    return (server as any).corsHeaders(origin) as Record<string, string>;
};

describe('CORS origin matching', () => {
    it('defaults to allow-all with *', () => {
        expect(corsHeaders('*', 'http://localhost:8080')).toEqual({
            'Access-Control-Allow-Origin': '*',
        });
    });

    it('supports apex and wildcard host matching over https', () => {
        expect(corsHeaders('*.liz.coffee,liz.coffee', 'https://liz.coffee')).toEqual({
            'Access-Control-Allow-Origin': 'https://liz.coffee',
        });

        expect(corsHeaders('*.liz.coffee,liz.coffee', 'https://beta.posthook.liz.coffee')).toEqual({
            'Access-Control-Allow-Origin': 'https://beta.posthook.liz.coffee',
        });

        expect(corsHeaders('*.liz.coffee,liz.coffee', 'https://evil.com')).toEqual({});
    });

    it('rejects http origins when restricted', () => {
        expect(corsHeaders('*.liz.coffee,liz.coffee', 'http://liz.coffee')).toEqual({});
    });

    it('does not match apex with wildcard alone', () => {
        expect(corsHeaders('*.liz.coffee', 'https://liz.coffee')).toEqual({});
        expect(corsHeaders('*.liz.coffee', 'https://a.liz.coffee')).toMatchObject({
            'Access-Control-Allow-Origin': 'https://a.liz.coffee',
        });
    });
});