|
| 1 | +import crypto from 'crypto' |
| 2 | +import type { NextFunction, Request, RequestHandler, Response } from 'express' |
| 3 | + |
| 4 | +import { UnauthorizedError } from '@crowd/common' |
| 5 | +import { findApiKeyByHash, optionsQx, touchApiKeyLastUsed } from '@crowd/data-access-layer' |
| 6 | + |
| 7 | +export function staticApiKeyMiddleware(): RequestHandler { |
| 8 | + return async (req: Request, _res: Response, next: NextFunction): Promise<void> => { |
| 9 | + try { |
| 10 | + const authHeader = req.headers.authorization |
| 11 | + |
| 12 | + if (!authHeader || !authHeader.startsWith('Bearer ')) { |
| 13 | + next(new UnauthorizedError('Missing or invalid Authorization header')) |
| 14 | + return |
| 15 | + } |
| 16 | + |
| 17 | + const providedKey = authHeader.slice('Bearer '.length) |
| 18 | + const keyHash = crypto.createHash('sha256').update(providedKey).digest('hex') |
| 19 | + |
| 20 | + const qx = optionsQx(req) |
| 21 | + const apiKey = await findApiKeyByHash(qx, keyHash) |
| 22 | + |
| 23 | + if (!apiKey) { |
| 24 | + next(new UnauthorizedError('Invalid API key')) |
| 25 | + return |
| 26 | + } |
| 27 | + |
| 28 | + if (apiKey.revokedAt) { |
| 29 | + next(new UnauthorizedError('API key has been revoked')) |
| 30 | + return |
| 31 | + } |
| 32 | + |
| 33 | + if (apiKey.expiresAt && apiKey.expiresAt < new Date()) { |
| 34 | + next(new UnauthorizedError('API key has expired')) |
| 35 | + return |
| 36 | + } |
| 37 | + |
| 38 | + // fire and forget — don't block the request |
| 39 | + touchApiKeyLastUsed(qx, apiKey.id).catch(() => {}) |
| 40 | + |
| 41 | + req.actor = { id: apiKey.name, type: 'service', scopes: apiKey.scopes } |
| 42 | + |
| 43 | + next() |
| 44 | + } catch (err) { |
| 45 | + next(err) |
| 46 | + } |
| 47 | + } |
| 48 | +} |
0 commit comments