gcs-backend-server / lib /apiKeyMiddleware.js
github-actions[bot]
chore: deploy from GitHub Actions (2026-03-08T13:13:40Z)
d9d886e
Raw History Blame Contribute Delete
2.2 kB
/**
* 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 }