Files
courier/lib/api-key.ts
T
2026-11-22 14:20:34 +00:00

73 lines
2.0 KiB
TypeScript

import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
import { config } from "./config";
import { query } from "./db";
export type ApiKey = {
id: string;
app: string;
fromDomain: string;
allowedFrom: string[] | null;
dailyLimit: number;
monthlyLimit: number;
};
type KeyRow = {
id: string;
app: string;
from_domain: string;
allowed_from: string[] | null;
daily_limit: number;
monthly_limit: number;
};
export function hashKey(key: string): string {
return createHmac("sha256", config.apiKeyPepper).update(key).digest("hex");
}
export function generateKey(): string {
return `ck_live_${randomBytes(24).toString("base64url")}`;
}
export function keyPrefix(key: string): string {
return key.slice(0, 16);
}
export function safeEqual(a: string, b: string): boolean {
const left = Buffer.from(a);
const right = Buffer.from(b);
return left.length === right.length && timingSafeEqual(left, right);
}
export async function authenticate(request: Request): Promise<ApiKey | null> {
const header = request.headers.get("authorization") ?? "";
if (!header.toLowerCase().startsWith("bearer ")) return null;
const token = header.slice(7).trim();
if (!token.startsWith("ck_live_")) return null;
const { rows } = await query<KeyRow>(
`select id, app, from_domain, allowed_from, daily_limit, monthly_limit
from api_keys
where key_hash = $1 and revoked_at is null`,
[hashKey(token)],
);
const row = rows[0];
if (!row) return null;
await query(`update api_keys set last_used_at = now() where id = $1`, [row.id]).catch(() => {});
return {
id: row.id,
app: row.app,
fromDomain: row.from_domain,
allowedFrom: row.allowed_from,
dailyLimit: row.daily_limit,
monthlyLimit: row.monthly_limit,
};
}
export function fromAllowed(key: ApiKey, address: string): boolean {
if (!key.allowedFrom?.length) return true;
return key.allowedFrom.map((value) => value.toLowerCase()).includes(address.toLowerCase());
}