|
| 1 | +import { RPCHandler } from '../adapters/fetch' |
| 2 | +import { os } from '../builder' |
| 3 | +import { SimpleCsrfProtectionHandlerPlugin } from './simple-csrf-protection' |
| 4 | + |
| 5 | +beforeEach(() => { |
| 6 | + vi.clearAllMocks() |
| 7 | +}) |
| 8 | + |
| 9 | +describe('simpleCsrfProtectionHandlerPlugin', () => { |
| 10 | + const interceptor = vi.fn(({ next }) => next()) |
| 11 | + |
| 12 | + const handler = new RPCHandler({ |
| 13 | + ping: os.handler(() => 'pong'), |
| 14 | + }, { |
| 15 | + plugins: [ |
| 16 | + new SimpleCsrfProtectionHandlerPlugin(), |
| 17 | + ], |
| 18 | + rootInterceptors: [interceptor], |
| 19 | + }) |
| 20 | + |
| 21 | + it('should work', async () => { |
| 22 | + await expect( |
| 23 | + handler.handle(new Request('http://localhost/ping?data=%7B%7D')), |
| 24 | + ).resolves.toEqual({ matched: true, response: expect.toSatisfy(response => response.status === 403) }) |
| 25 | + |
| 26 | + await expect( |
| 27 | + handler.handle(new Request('http://localhost/ping?data=%7B%7D', { |
| 28 | + headers: { |
| 29 | + 'x-csrf-token': 'orpc', |
| 30 | + }, |
| 31 | + })), |
| 32 | + ).resolves.toEqual({ matched: true, response: expect.toSatisfy(response => response.status === 200) }) |
| 33 | + }) |
| 34 | + |
| 35 | + it('should throw error when interceptor messes with the context', async () => { |
| 36 | + interceptor.mockImplementation((options) => { |
| 37 | + return options.next({ |
| 38 | + ...options, |
| 39 | + context: {}, // <-- interceptor messes with the context |
| 40 | + }) |
| 41 | + }) |
| 42 | + |
| 43 | + await expect( |
| 44 | + handler.handle(new Request('http://localhost/ping?data=%7B%7D')), |
| 45 | + ).resolves.toEqual({ matched: true, response: expect.toSatisfy(response => response.status === 500) }) |
| 46 | + |
| 47 | + await expect( |
| 48 | + handler.handle(new Request('http://localhost/ping?data=%7B%7D', { |
| 49 | + headers: { |
| 50 | + 'x-csrf-token': 'orpc', |
| 51 | + }, |
| 52 | + })), |
| 53 | + ).resolves.toEqual({ matched: true, response: expect.toSatisfy(response => response.status === 500) }) |
| 54 | + }) |
| 55 | + |
| 56 | + it('can exclude procedure', async () => { |
| 57 | + const exclude = vi.fn(() => true) |
| 58 | + |
| 59 | + const ping = os.handler(() => 'pong') |
| 60 | + |
| 61 | + const handler = new RPCHandler({ ping }, { |
| 62 | + plugins: [ |
| 63 | + new SimpleCsrfProtectionHandlerPlugin({ |
| 64 | + exclude, |
| 65 | + }), |
| 66 | + ], |
| 67 | + }) |
| 68 | + |
| 69 | + await expect( |
| 70 | + handler.handle(new Request('http://localhost/ping?data=%7B%7D')), |
| 71 | + ).resolves.toEqual({ matched: true, response: expect.toSatisfy(response => response.status === 200) }) |
| 72 | + |
| 73 | + expect(exclude).toHaveBeenCalledTimes(1) |
| 74 | + expect(exclude).toHaveBeenCalledWith(expect.objectContaining({ |
| 75 | + path: ['ping'], |
| 76 | + procedure: ping, |
| 77 | + })) |
| 78 | + }) |
| 79 | +}) |
0 commit comments