MCPcopy Create free account
hub / github.com/Kilo-Org/cloud / authMiddleware

Function authMiddleware

services/kiloclaw/src/auth/middleware.ts:18–77  ·  view source on GitHub ↗
(c: Context<AppEnv>, next: Next)

Source from the content-addressed store, hash-verified

16 * 4. Validate apiTokenPepper against DB via Hyperdrive
17 * 5. Reject the request when the user is blocked
18 * 6. Set ctx.userId, ctx.authToken on context
19 */
20export async function authMiddleware(c: Context<AppEnv>, next: Next) {
21 const secret = c.env.NEXTAUTH_SECRET;
22 if (!secret) {
23 console.error('[auth] NEXTAUTH_SECRET not configured');
24 return c.json({ error: 'Server configuration error' }, 500);
25 }
26
27 // Extract token: Bearer header first, then cookie fallback
28 let token: string | undefined;
29 const authHeader = c.req.header('authorization');
30 if (authHeader?.toLowerCase().startsWith('bearer ')) {
31 token = authHeader.substring(7);
32 }
33 if (!token) {
34 token = getCookie(c, KILOCLAW_AUTH_COOKIE);
35 }
36
37 if (!token) {
38 return c.json({ error: 'Authentication required' }, 401);
39 }
40
41 const result = await validateKiloToken(token, secret, c.env.WORKER_ENV);
42 if (!result.success) {
43 console.warn('[auth] Token validation failed:', result.error);
44 return c.json({ error: 'Authentication failed' }, 401);
45 }
46
47 // The token must carry the account's current pepper (`isKiloUserCredentialPepperCurrent`).
48 if (!c.env.HYPERDRIVE?.connectionString) {
49 console.error('[auth] HYPERDRIVE not configured -- cannot validate token pepper');
50 return c.json({ error: 'Server configuration error' }, 500);
51 }
52
53 try {
54 const db = getWorkerDb(c.env.HYPERDRIVE.connectionString);
55 const user = await findPepperByUserId(db, result.userId);
56 if (!user) {
57 console.warn('[auth] User not found in DB:', result.userId);
58 return c.json({ error: 'User not found' }, 401);
59 }
60 if (
61 !isKiloUserCredentialPepperCurrent({ apiTokenPepper: result.pepper }, user.api_token_pepper)
62 ) {
63 console.warn('[auth] Pepper mismatch for user:', result.userId);
64 return c.json({ error: 'Token revoked' }, 401);
65 }
66 // A blocked user must not keep access through an unrotated token.
67 if (user.blocked_reason) {
68 console.warn('[auth] Blocked user rejected:', result.userId);
69 return c.json({ error: 'Token revoked' }, 401);
70 }
71 } catch (err) {
72 console.error('[auth] Pepper validation failed:', err);
73 return c.json({ error: 'Authentication service unavailable' }, 500);
74 }
75

Callers 2

gastown.worker.tsFile · 0.90
authGuardFunction · 0.90

Calls 8

validateKiloTokenFunction · 0.90
getWorkerDbFunction · 0.90
findPepperByUserIdFunction · 0.90
errorMethod · 0.65
jsonMethod · 0.65
warnMethod · 0.65
setMethod · 0.65
nextFunction · 0.50

Tested by

no test coverage detected