New API + API Token Updates

This commit is contained in:
2026-01-16 13:20:11 -07:00
parent 756ab2a38f
commit 4412229990
26 changed files with 1661 additions and 1012 deletions

44
src/lib/api-auth.ts Normal file
View File

@@ -0,0 +1,44 @@
import { db } from "../db";
import { apiTokens, users } from "../db/schema";
import { eq } from "drizzle-orm";
import crypto from "node:crypto";
export function hashToken(token: string): string {
return crypto.createHash("sha256").update(token).digest("hex");
}
export async function validateApiToken(token: string) {
const hashedToken = hashToken(token);
const result = await db
.select({
user: users,
tokenData: apiTokens,
})
.from(apiTokens)
.innerJoin(users, eq(apiTokens.userId, users.id))
.where(eq(apiTokens.token, hashedToken))
.get();
if (!result) {
return null;
}
// Update last used at
await db
.update(apiTokens)
.set({ lastUsedAt: new Date() })
.where(eq(apiTokens.id, result.tokenData.id));
const scopes = result.tokenData.scopes.split(",").map((s) => s.trim());
return {
user: result.user,
scopes,
};
}
export function generateApiToken(): string {
const buffer = crypto.randomBytes(32);
return "ch_" + buffer.toString("hex");
}