mirror of
https://github.com/ZHANGTIANYAO1/teamspeak-music-bot.git
synced 2026-12-03 03:12:51 +08:00
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
This commit is contained in:
1 parent
2ea02f54d9
commit
aab8a004ae
16 files changed
+1272
-7
No files matched your search
@@ -0,0 +1,124 @@
|
||||
import { describe, it, expect, beforeEach, afterEach, vi } from "vitest";
|
||||
import { createHash } from "node:crypto";
|
||||
import { createDatabase, type BotDatabase } from "./database.js";
|
||||
import { createUserStore, type UserStore } from "./users.js";
|
||||
import {
|
||||
createApiKeyStore,
|
||||
type ApiKeyStore,
|
||||
MAX_API_KEYS_PER_USER,
|
||||
API_KEY_TOUCH_INTERVAL_MS,
|
||||
} from "./api-keys.js";
|
||||
|
||||
function sha256(key: string) {
|
||||
return createHash("sha256").update(key).digest("hex");
|
||||
}
|
||||
|
||||
describe("ApiKeyStore", () => {
|
||||
let botDb: BotDatabase;
|
||||
let users: UserStore;
|
||||
let keys: ApiKeyStore;
|
||||
let userId: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
botDb = createDatabase(":memory:");
|
||||
users = createUserStore(botDb.db);
|
||||
keys = createApiKeyStore(botDb.db);
|
||||
const u = await users.createUser("alice", "pw-alice", "admin");
|
||||
userId = u.id;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
botDb.close();
|
||||
});
|
||||
|
||||
it("create returns a tsmb_-prefixed raw key whose sha256 is stored, never the plaintext", () => {
|
||||
const created = keys.create(userId, "ci");
|
||||
expect(created).not.toBeNull();
|
||||
expect(created!.rawKey).toMatch(/^tsmb_[A-Za-z0-9_-]{40,}$/);
|
||||
const row = botDb.db.prepare("SELECT keyHash, keyPrefix FROM api_keys").get() as {
|
||||
keyHash: string;
|
||||
keyPrefix: string;
|
||||
};
|
||||
expect(row.keyHash).toBe(sha256(created!.rawKey));
|
||||
expect(row.keyHash).not.toContain(created!.rawKey);
|
||||
expect(created!.key.keyPrefix).toBe(created!.rawKey.slice(0, 12));
|
||||
});
|
||||
|
||||
it("validateAndTouch resolves the owner user for a fresh key", () => {
|
||||
const { rawKey } = keys.create(userId, "ci")!;
|
||||
const result = keys.validateAndTouch(rawKey);
|
||||
expect(result).not.toBeNull();
|
||||
expect(result!.userId).toBe(userId);
|
||||
expect(result!.username).toBe("alice");
|
||||
expect(result!.role).toBe("admin");
|
||||
});
|
||||
|
||||
it("validateAndTouch returns null for an unknown or empty key", () => {
|
||||
keys.create(userId, "ci");
|
||||
expect(keys.validateAndTouch("tsmb_not-a-real-key")).toBeNull();
|
||||
expect(keys.validateAndTouch("")).toBeNull();
|
||||
});
|
||||
|
||||
it("delete removes the key so it no longer validates", () => {
|
||||
const { key, rawKey } = keys.create(userId, "ci")!;
|
||||
expect(keys.delete(key.id, userId)).toBe(true);
|
||||
expect(keys.validateAndTouch(rawKey)).toBeNull();
|
||||
});
|
||||
|
||||
it("delete with userId refuses to remove another user's key", async () => {
|
||||
const { key } = keys.create(userId, "ci")!;
|
||||
const other = await users.createUser("bob", "pw-bob", "member");
|
||||
expect(keys.delete(key.id, other.id)).toBe(false);
|
||||
expect(keys.delete(key.id)).toBe(true);
|
||||
});
|
||||
|
||||
it("keys of a deleted user stop validating", async () => {
|
||||
const { rawKey } = keys.create(userId, "ci")!;
|
||||
users.deleteUser(userId);
|
||||
expect(keys.validateAndTouch(rawKey)).toBeNull();
|
||||
});
|
||||
|
||||
it("enforces the per-user key cap", () => {
|
||||
for (let i = 0; i < MAX_API_KEYS_PER_USER; i++) {
|
||||
expect(keys.create(userId, `key-${i}`)).not.toBeNull();
|
||||
}
|
||||
expect(keys.create(userId, "one-too-many")).toBeNull();
|
||||
expect(keys.listForUser(userId)).toHaveLength(MAX_API_KEYS_PER_USER);
|
||||
});
|
||||
|
||||
it("touches lastUsedAt at most once per interval", () => {
|
||||
vi.useFakeTimers();
|
||||
vi.setSystemTime(new Date("2026-01-01T00:00:00Z"));
|
||||
const { rawKey } = keys.create(userId, "ci")!;
|
||||
keys.validateAndTouch(rawKey);
|
||||
const first = (botDb.db.prepare("SELECT lastUsedAt FROM api_keys").get() as { lastUsedAt: number }).lastUsedAt;
|
||||
vi.setSystemTime(new Date("2026-01-01T00:00:00Z").getTime() + 30_000);
|
||||
keys.validateAndTouch(rawKey);
|
||||
const second = (botDb.db.prepare("SELECT lastUsedAt FROM api_keys").get() as { lastUsedAt: number }).lastUsedAt;
|
||||
expect(second).toBe(first);
|
||||
vi.setSystemTime(new Date("2026-01-01T00:00:00Z").getTime() + API_KEY_TOUCH_INTERVAL_MS + 1000);
|
||||
keys.validateAndTouch(rawKey);
|
||||
const third = (botDb.db.prepare("SELECT lastUsedAt FROM api_keys").get() as { lastUsedAt: number }).lastUsedAt;
|
||||
expect(third).toBeGreaterThan(first);
|
||||
});
|
||||
|
||||
it("deleteAllForUser clears every key of that user", async () => {
|
||||
keys.create(userId, "a");
|
||||
keys.create(userId, "b");
|
||||
const other = await users.createUser("bob", "pw-bob", "member");
|
||||
keys.create(other.id, "c");
|
||||
keys.deleteAllForUser(userId);
|
||||
expect(keys.listForUser(userId)).toHaveLength(0);
|
||||
expect(keys.listForUser(other.id)).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("listAll exposes usernames for admin views", async () => {
|
||||
keys.create(userId, "ci");
|
||||
const other = await users.createUser("bob", "pw-bob", "member");
|
||||
keys.create(other.id, "deploy");
|
||||
const all = keys.listAll();
|
||||
expect(all).toHaveLength(2);
|
||||
expect(all.map((k) => k.username).sort()).toEqual(["alice", "bob"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,130 @@
|
||||
import { createHash, randomBytes, randomUUID } from "node:crypto";
|
||||
import type Database from "better-sqlite3";
|
||||
|
||||
export const MAX_API_KEYS_PER_USER = 20;
|
||||
export const API_KEY_TOUCH_INTERVAL_MS = 60 * 60 * 1000; // 1 hour
|
||||
/** Visible prefix stored for list views, e.g. "tsmb_a1b2c3d4". */
|
||||
export const API_KEY_PREFIX_LENGTH = 12;
|
||||
|
||||
export interface ApiKeyRow {
|
||||
id: string;
|
||||
userId: string;
|
||||
name: string;
|
||||
keyPrefix: string;
|
||||
createdAt: number;
|
||||
lastUsedAt: number | null;
|
||||
}
|
||||
|
||||
export interface ApiKeyWithUser extends ApiKeyRow {
|
||||
username: string;
|
||||
}
|
||||
|
||||
export interface ApiKeyValidation {
|
||||
keyId: string;
|
||||
userId: string;
|
||||
username: string;
|
||||
role: "admin" | "member";
|
||||
}
|
||||
|
||||
export interface CreatedApiKey {
|
||||
key: ApiKeyRow;
|
||||
/** Plaintext key — returned exactly once, at creation time. */
|
||||
rawKey: string;
|
||||
}
|
||||
|
||||
export interface ApiKeyStore {
|
||||
/** Returns null when the per-user key cap is reached. */
|
||||
create(userId: string, name: string): CreatedApiKey | null;
|
||||
listForUser(userId: string): ApiKeyRow[];
|
||||
listAll(): ApiKeyWithUser[];
|
||||
/** With userId, only deletes a key owned by that user. */
|
||||
delete(id: string, userId?: string): boolean;
|
||||
deleteAllForUser(userId: string): void;
|
||||
validateAndTouch(rawKey: string): ApiKeyValidation | null;
|
||||
}
|
||||
|
||||
function hashKey(rawKey: string): string {
|
||||
return createHash("sha256").update(rawKey).digest("hex");
|
||||
}
|
||||
|
||||
export function createApiKeyStore(db: Database.Database): ApiKeyStore {
|
||||
const insertStmt = db.prepare(
|
||||
"INSERT INTO api_keys (id, userId, name, keyHash, keyPrefix, createdAt, lastUsedAt) VALUES (?, ?, ?, ?, ?, ?, NULL)"
|
||||
);
|
||||
const selectForUserStmt = db.prepare(
|
||||
"SELECT id, userId, name, keyPrefix, createdAt, lastUsedAt FROM api_keys WHERE userId = ? ORDER BY createdAt DESC"
|
||||
);
|
||||
const selectAllStmt = db.prepare(
|
||||
`SELECT k.id, k.userId, k.name, k.keyPrefix, k.createdAt, k.lastUsedAt, u.username
|
||||
FROM api_keys k INNER JOIN users u ON u.id = k.userId
|
||||
ORDER BY k.createdAt DESC`
|
||||
);
|
||||
const selectByIdStmt = db.prepare(
|
||||
"SELECT id, userId, name, keyPrefix, createdAt, lastUsedAt FROM api_keys WHERE id = ?"
|
||||
);
|
||||
const deleteStmt = db.prepare("DELETE FROM api_keys WHERE id = ?");
|
||||
const deleteAllForUserStmt = db.prepare("DELETE FROM api_keys WHERE userId = ?");
|
||||
const countForUserStmt = db.prepare("SELECT COUNT(*) AS n FROM api_keys WHERE userId = ?");
|
||||
const validateStmt = db.prepare(
|
||||
`SELECT k.id, k.userId, k.lastUsedAt, u.username, u.role
|
||||
FROM api_keys k INNER JOIN users u ON u.id = k.userId
|
||||
WHERE k.keyHash = ?`
|
||||
);
|
||||
const touchStmt = db.prepare("UPDATE api_keys SET lastUsedAt = ? WHERE id = ?");
|
||||
|
||||
return {
|
||||
create(userId, name) {
|
||||
const count = (countForUserStmt.get(userId) as { n: number }).n;
|
||||
if (count >= MAX_API_KEYS_PER_USER) {
|
||||
return null;
|
||||
}
|
||||
const rawKey = `tsmb_${randomBytes(32).toString("base64url")}`;
|
||||
const row: ApiKeyRow = {
|
||||
id: randomUUID(),
|
||||
userId,
|
||||
name,
|
||||
keyPrefix: rawKey.slice(0, API_KEY_PREFIX_LENGTH),
|
||||
createdAt: Date.now(),
|
||||
lastUsedAt: null,
|
||||
};
|
||||
insertStmt.run(row.id, row.userId, row.name, hashKey(rawKey), row.keyPrefix, row.createdAt);
|
||||
return { key: row, rawKey };
|
||||
},
|
||||
|
||||
listForUser(userId) {
|
||||
return selectForUserStmt.all(userId) as ApiKeyRow[];
|
||||
},
|
||||
|
||||
listAll() {
|
||||
return selectAllStmt.all() as ApiKeyWithUser[];
|
||||
},
|
||||
|
||||
delete(id, userId) {
|
||||
const row = selectByIdStmt.get(id) as ApiKeyRow | undefined;
|
||||
if (!row) return false;
|
||||
if (userId !== undefined && row.userId !== userId) return false;
|
||||
deleteStmt.run(id);
|
||||
return true;
|
||||
},
|
||||
|
||||
deleteAllForUser(userId) {
|
||||
deleteAllForUserStmt.run(userId);
|
||||
},
|
||||
|
||||
validateAndTouch(rawKey) {
|
||||
if (!rawKey) return null;
|
||||
const row = validateStmt.get(hashKey(rawKey)) as
|
||||
| { id: string; userId: string; lastUsedAt: number | null; username: string; role: string }
|
||||
| undefined;
|
||||
if (!row) return null;
|
||||
// The reserved guest principal must never authenticate via API keys;
|
||||
// guest access is session-only by design.
|
||||
if (row.role !== "admin" && row.role !== "member") return null;
|
||||
const now = Date.now();
|
||||
if (row.lastUsedAt === null || now - row.lastUsedAt > API_KEY_TOUCH_INTERVAL_MS) {
|
||||
touchStmt.run(now, row.id);
|
||||
}
|
||||
return { keyId: row.id, userId: row.userId, username: row.username, role: row.role };
|
||||
},
|
||||
};
|
||||
}
|
||||
+3
-1
@@ -7,7 +7,9 @@ export type AuditAction =
|
||||
| "user.password_reset"
|
||||
| "user.password_changed"
|
||||
| "user.role_changed"
|
||||
| "user.permissions_changed";
|
||||
| "user.permissions_changed"
|
||||
| "api_key.created"
|
||||
| "api_key.deleted";
|
||||
|
||||
export interface AuditEntry {
|
||||
id: number;
|
||||
|
||||
@@ -268,6 +268,18 @@ function initTables(db: Database.Database): void {
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_userId ON sessions(userId);
|
||||
CREATE INDEX IF NOT EXISTS idx_sessions_expiresAt ON sessions(expiresAt);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS api_keys (
|
||||
id TEXT PRIMARY KEY,
|
||||
userId TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
keyHash TEXT NOT NULL UNIQUE,
|
||||
keyPrefix TEXT NOT NULL,
|
||||
createdAt INTEGER NOT NULL,
|
||||
lastUsedAt INTEGER,
|
||||
FOREIGN KEY (userId) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_api_keys_userId ON api_keys(userId);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS user_audit (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
timestamp INTEGER NOT NULL,
|
||||
|
||||
Reference in new issue
Block a user