/ src / proxy.test.ts
proxy.test.ts
 1  import assert from 'node:assert/strict'
 2  import { afterEach, describe, it } from 'node:test'
 3  
 4  import { NextRequest } from 'next/server'
 5  
 6  import { proxy } from './proxy'
 7  
 8  const originalAccessKey = process.env.ACCESS_KEY
 9  
10  afterEach(() => {
11    if (originalAccessKey === undefined) delete process.env.ACCESS_KEY
12    else process.env.ACCESS_KEY = originalAccessKey
13  })
14  
15  describe('proxy', () => {
16    it('keeps CORS headers on extension-install auth failures for allowed origins', () => {
17      process.env.ACCESS_KEY = 'top-secret'
18  
19      const request = new NextRequest('http://localhost/api/extensions/install', {
20        method: 'POST',
21        headers: {
22          origin: 'https://swarmclaw.ai',
23        },
24      })
25  
26      const response = proxy(request)
27      assert.equal(response.status, 401)
28      assert.equal(response.headers.get('access-control-allow-origin'), 'https://swarmclaw.ai')
29      assert.equal(response.headers.get('vary'), 'Origin')
30    })
31  
32    it('prefers the auth cookie over a stale access-key header', () => {
33      process.env.ACCESS_KEY = 'top-secret'
34  
35      const request = new NextRequest('http://localhost/api/agents', {
36        headers: {
37          cookie: 'sc_auth=top-secret',
38          'x-access-key': 'stale-key',
39        },
40      })
41  
42      const response = proxy(request)
43      assert.equal(response.status, 200)
44    })
45  
46    it('does not lock out invalid requests in development', () => {
47      process.env.ACCESS_KEY = 'top-secret'
48      const originalNodeEnv = process.env.NODE_ENV;
49      (process.env as any).NODE_ENV = 'development'
50  
51      try {
52        for (let i = 0; i < 6; i++) {
53          const response = proxy(new NextRequest('http://localhost/api/agents', {
54            headers: {
55              'x-access-key': 'bad-key',
56            },
57          }))
58          assert.equal(response.status, 401)
59        }
60        const finalResponse = proxy(new NextRequest('http://localhost/api/agents', {
61          headers: {
62            'x-access-key': 'bad-key',
63          },
64        }))
65        assert.equal(finalResponse.status, 401)
66      } finally {
67        if (originalNodeEnv === undefined) delete (process.env as any).NODE_ENV
68        else (process.env as any).NODE_ENV = originalNodeEnv
69      }
70    })
71  })