Files
teamspeak-music-bot/src/web/auth/api-key-header.ts
T
senlinjun aab8a004ae feat(web): add API-key authentication for the REST API
- api_keys table + hashed key store (src/data/api-keys.ts), tsmb_-prefixed
  plaintext shown once, per-user cap of 20, lastUsedAt tracking
- requireAuth accepts Authorization: Bearer / X-API-Key headers as an
  alternative to the session cookie; key inherits the owner user's
  role/capabilities/bot scope
- csrf origin check skipped for key-only requests (no ambient credentials);
  requests that also carry the session cookie stay gated
- /api/keys management endpoints (session-only, guests excluded, keys
  themselves rejected) with audit logging
- user deletion / password reset cascade-revoke the user's keys
- Settings page: API key management section (create/copy-once/revoke)
- docs: README section + full endpoint reference in docs/API.md
2026-09-29 21:51:43 +08:00

37 lines
1.2 KiB
TypeScript

import type { Request } from "express";
import { SESSION_COOKIE_NAME } from "./validateSession.js";
/**
* Extract a raw API key from the `X-API-Key` header or an
* `Authorization: Bearer <key>` header. Returns null when neither is present.
*/
export function extractApiKey(req: Request): string | null {
const header = req.headers["x-api-key"];
if (typeof header === "string" && header.trim()) {
return header.trim();
}
const auth = req.headers.authorization;
if (typeof auth === "string") {
const match = /^bearer\s+(.+)$/i.exec(auth);
if (match) {
const key = match[1].trim();
if (key) return key;
}
}
return null;
}
export function hasApiKeyCredential(req: Request): boolean {
return extractApiKey(req) !== null;
}
/**
* API-key clients (no session cookie) skip the origin check entirely. Requests
* that ALSO carry the session cookie must NOT rely on this — an attacker page
* can set arbitrary headers while the victim's cookie rides along ambiently,
* so the cookie keeps the request under the origin check.
*/
export function isApiKeyOnlyRequest(req: Request): boolean {
return hasApiKeyCredential(req) && !req.headers.cookie?.includes(`${SESSION_COOKIE_NAME}=`);
}