Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 14 additions & 1 deletion kiloclaw/src/auth/middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -104,9 +104,22 @@ export async function internalApiMiddleware(c: Context<AppEnv>, next: Next) {
return c.json({ error: 'Forbidden' }, 403);
}

if (apiKey !== secret) {
if (!timingSafeEqual(apiKey, secret)) {
return c.json({ error: 'Forbidden' }, 403);
}

return next();
}

function timingSafeEqual(a: string, b: string): boolean {
const encoder = new TextEncoder();
const aBytes = encoder.encode(a);
const bBytes = encoder.encode(b);

if (aBytes.length !== bBytes.length) {
// Compare a against itself so the timing is constant regardless of length mismatch
crypto.subtle.timingSafeEqual(aBytes, aBytes);
return false;
}
return crypto.subtle.timingSafeEqual(aBytes, bBytes);
}
17 changes: 17 additions & 0 deletions kiloclaw/src/test-setup.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { timingSafeEqual } from 'node:crypto';

// Polyfill crypto.subtle.timingSafeEqual for Vitest (Node environment).
// This API is available natively in Cloudflare Workers but not in Node.js.
if (!crypto.subtle.timingSafeEqual) {
Object.defineProperty(crypto.subtle, 'timingSafeEqual', {
value(a: ArrayBuffer | ArrayBufferView, b: ArrayBuffer | ArrayBufferView): boolean {
const bufA = ArrayBuffer.isView(a)
? Buffer.from(a.buffer, a.byteOffset, a.byteLength)
: Buffer.from(a);
const bufB = ArrayBuffer.isView(b)
? Buffer.from(b.buffer, b.byteOffset, b.byteLength)
: Buffer.from(b);
return timingSafeEqual(bufA, bufB);
},
});
}
1 change: 1 addition & 0 deletions kiloclaw/vitest.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export default defineConfig({
name: 'unit',
globals: true,
environment: 'node',
setupFiles: ['src/test-setup.ts'],
include: ['src/**/*.test.ts'],
coverage: {
provider: 'v8',
Expand Down