blob: d22f26d874d5bf0d310d6aee15cdb325787a2d2b (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
|
import { createHash } from 'node:crypto';
import type { MiddlewareHandler } from 'hono';
import { lookupApiKey, type ApiKeyLookup } from './db';
export interface AuthVars {
apiKey: ApiKeyLookup;
}
function sha256Hex(input: string): string {
return createHash('sha256').update(input).digest('hex');
}
/**
* Hono middleware: require a valid `Authorization: Bearer ti_...` header.
* On success, attaches the resolved ApiKeyLookup to c.var.apiKey so the
* handler can see the caller's account + plan + key.
*/
export const auth: MiddlewareHandler<{ Variables: AuthVars }> = async (
c,
next
) => {
const header =
c.req.header('authorization') ?? c.req.header('Authorization');
if (!header) {
return c.json({ error: 'Missing Authorization header' }, 401);
}
const match = /^Bearer\s+(\S+)$/i.exec(header);
if (!match) {
return c.json(
{ error: 'Authorization header must be `Bearer <api_key>`' },
401
);
}
const token = match[1]!;
if (!token.startsWith('ti_')) {
return c.json({ error: 'Invalid API key format' }, 401);
}
const key = lookupApiKey(sha256Hex(token));
if (!key) {
return c.json({ error: 'Invalid or revoked API key' }, 401);
}
c.set('apiKey', key);
return next();
};
|