File size: 2,196 Bytes
d9d886e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
 * API Key authentication middleware
 *
 * The API key is read from the environment variable API_KEY.
 * If API_KEY is not set the middleware is a no-op (useful in local dev).
 *
 * ─── HTTP (Express) ─────────────────────────────────────────────────────────
 * Clients must supply the key in ONE of the following ways:
 *   β€’ Header:  x-api-key: <key>
 *   β€’ Header:  Authorization: Bearer <key>
 *   β€’ Query:   ?api_key=<key>
 *
 * ─── WebSocket (Socket.IO) ──────────────────────────────────────────────────
 * Clients must supply the key in ONE of the following ways:
 *   β€’ io('<url>', { auth: { apiKey: '<key>' } })
 *   β€’ io('<url>', { extraHeaders: { 'x-api-key': '<key>' } })
 */

/**
 * Express middleware β€” runs on every HTTP request.
 */
const httpApiKeyMiddleware = (req, res, next) => {
  const apiKey = process.env.API_KEY

  // Key not configured β†’ allow all (development mode)
  if (!apiKey) return next()

  // Skip preflight requests
  if (req.method === 'OPTIONS') return next()

  const headerKey =
    req.headers['x-api-key'] ||
    (req.headers.authorization || '').replace(/^Bearer\s+/i, '').trim()
  const queryKey = req.query.api_key

  if (headerKey === apiKey || queryKey === apiKey) return next()

  return res
    .status(401)
    .json({ error: 'Unauthorized: invalid or missing API key' })
}

/**
 * Socket.IO middleware β€” runs on every new connection handshake.
 */
const socketApiKeyMiddleware = (socket, next) => {
  const apiKey = process.env.API_KEY

  // Key not configured β†’ allow all (development mode)
  if (!apiKey) return next()

  const fromAuth =
    socket.handshake.auth && socket.handshake.auth.apiKey
  const fromHeader =
    socket.handshake.headers && socket.handshake.headers['x-api-key']

  if (fromAuth === apiKey || fromHeader === apiKey) return next()

  return next(new Error('Unauthorized: invalid or missing API key'))
}

module.exports = { httpApiKeyMiddleware, socketApiKeyMiddleware }