Skip to content
Open
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
1 change: 1 addition & 0 deletions packages/worker-utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"./instance-id": "./src/instance-id.ts",
"./kilo-token-auth": "./src/kilo-token-auth.ts",
"./kilo-token": "./src/kilo-token.ts",
"./kilo-auth-middleware": "./src/kilo-auth-middleware.ts",
"./sandbox-id": "./src/sandbox-id.ts",
"./hostname-label": "./src/hostname-label.ts",
"./deployment-slug": "./src/deployment-slug.ts",
Expand Down
10 changes: 10 additions & 0 deletions packages/worker-utils/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,16 @@ export {
} from './kilo-token.js';
export type { KiloTokenPayload, SignKiloTokenExtra } from './kilo-token.js';

export { createKiloAuthMiddleware } from './kilo-auth-middleware.js';
export type {
KiloAuthEnv,
KiloAuthMiddlewareOptions,
KiloAuthOrgMembership,
KiloAuthVariables,
ResolveSecret,
SecretBinding,
} from './kilo-auth-middleware.js';

export { SessionMetricsParamsSchema, TerminationReasons } from './session-metrics-schema.js';
export type { SessionMetricsParams, SessionMetricsParamsInput } from './session-metrics-schema.js';

Expand Down
Original file line number Diff line number Diff line change
@@ -1,16 +1,32 @@
import { describe, it, expect } from 'vitest';
import { Hono } from 'hono';
import { SignJWT } from 'jose';
import { kiloAuthMiddleware } from './kilo-auth.middleware';
import type { GastownEnv } from '../gastown.worker';
import { describe, expect, it } from 'vitest';
import { createKiloAuthMiddleware } from './kilo-auth-middleware';

const TEST_SECRET = 'test-secret-that-is-long-enough-for-hs256';

const resolveSecret = async (binding: { get(): Promise<string> } | string) =>
typeof binding === 'string' ? binding : await binding.get();

type TestEnv = {
Bindings: { NEXTAUTH_SECRET?: string };
Variables: {
kiloUserId: string;
kiloIsAdmin: boolean;
kiloApiTokenPepper: string | null;
kiloGastownAccess: boolean;
kiloOrgMemberships: { orgId: string; role: 'owner' | 'member' | 'billing_manager' }[];
};
};

function createApp() {
const app = new Hono<GastownEnv>();
app.use('/api/*', kiloAuthMiddleware);
const app = new Hono<TestEnv>();
app.use('/api/*', createKiloAuthMiddleware<TestEnv>({ resolveSecret }));
app.get('/api/whoami', c => {
return c.json({ kiloUserId: c.get('kiloUserId') });
return c.json({
kiloUserId: c.get('kiloUserId'),
kiloGastownAccess: c.get('kiloGastownAccess'),
});
});
return app;
}
Expand All @@ -24,7 +40,7 @@ async function signToken(payload: Record<string, unknown>) {
.sign(new TextEncoder().encode(TEST_SECRET));
}

describe('kiloAuthMiddleware', () => {
describe('createKiloAuthMiddleware', () => {
it('rejects when no token is provided', async () => {
const app = createApp();
const res = await app.request('/api/whoami', {}, {
Expand All @@ -33,11 +49,12 @@ describe('kiloAuthMiddleware', () => {
expect(res.status).toBe(401);
});

it('accepts a well-formed Kilo token', async () => {
it('accepts a well-formed Kilo token and sets the auth context', async () => {
const app = createApp();
const token = await signToken({
version: 3,
kiloUserId: 'user-abc',
gastownAccess: true,
env: 'development',
});

Expand All @@ -47,13 +64,12 @@ describe('kiloAuthMiddleware', () => {
{ NEXTAUTH_SECRET: TEST_SECRET } as never
);
expect(res.status).toBe(200);
const body = (await res.json()) as { kiloUserId: string };
const body = (await res.json()) as { kiloUserId: string; kiloGastownAccess: boolean };
expect(body.kiloUserId).toBe('user-abc');
expect(body.kiloGastownAccess).toBe(true);
});
});

describe('C15 deviceSessionId compatibility', () => {
it('accepts a token carrying deviceSessionId claim', async () => {
it('accepts a token carrying a deviceSessionId claim', async () => {
const app = createApp();
const token = await signToken({
version: 3,
Expand Down
90 changes: 90 additions & 0 deletions packages/worker-utils/src/kilo-auth-middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { createMiddleware } from 'hono/factory';
import type { MiddlewareHandler } from 'hono';
import { extractBearerToken } from './extract-bearer-token.js';
import { verifyKiloToken, type KiloTokenPayload } from './kilo-token.js';
import { resError } from './res.js';

/**
* A Cloudflare Secrets Store binding (production) or a plain string
* (test/local env vars). Structural so worker-utils does not need to pull in
* `@cloudflare/workers-types`.
*/
export type SecretBinding = { get(): Promise<string> } | string;

export type KiloAuthOrgMembership = {
orgId: string;
role: 'owner' | 'member' | 'billing_manager';
};

export type KiloAuthVariables = {
kiloUserId: string;
kiloIsAdmin: boolean;
kiloApiTokenPepper: string | null;
kiloGastownAccess: boolean;
kiloOrgMemberships: KiloAuthOrgMembership[];
};

export type ResolveSecret = (binding: SecretBinding) => Promise<string | null>;

export type KiloAuthMiddlewareOptions = {
resolveSecret: ResolveSecret;
onAuthenticated?: (payload: KiloTokenPayload) => void;
};

export type KiloAuthEnv = {
Bindings: { NEXTAUTH_SECRET?: SecretBinding | undefined };
Variables: KiloAuthVariables;
};

/**
* Hono middleware that validates Kilo user JWTs (HS256, signed with
* NEXTAUTH_SECRET) for dashboard/user-facing routes.
*
* Sets the `kiloUserId`, `kiloIsAdmin`, `kiloApiTokenPepper`,
* `kiloGastownAccess`, and `kiloOrgMemberships` variables on the Hono context.
*
* The secret is resolved via the injected `resolveSecret` so each service can
* keep its own Secrets Store handling (and test string fallback). The optional
* `onAuthenticated` hook lets a service tag its structured logger with the
* authenticated user id.
*/
export function createKiloAuthMiddleware<E extends KiloAuthEnv>(
options: KiloAuthMiddlewareOptions
): MiddlewareHandler<E> {
const { resolveSecret, onAuthenticated } = options;
return createMiddleware<E>(async (c, next) => {
const token = extractBearerToken(c.req.header('Authorization'));

if (!token) {
return c.json(resError('Authentication required'), 401);
}

if (!c.env.NEXTAUTH_SECRET) {
console.error('[kilo-auth] NEXTAUTH_SECRET not configured');
return c.json(resError('Internal server error'), 500);
}
const secret = await resolveSecret(c.env.NEXTAUTH_SECRET);
if (!secret) {
console.error('[kilo-auth] failed to resolve NEXTAUTH_SECRET from Secrets Store');
return c.json(resError('Internal server error'), 500);
}

try {
const payload = await verifyKiloToken(token, secret);
c.set('kiloUserId', payload.kiloUserId);
c.set('kiloIsAdmin', payload.isAdmin === true);
c.set('kiloApiTokenPepper', payload.apiTokenPepper ?? null);
c.set('kiloGastownAccess', payload.gastownAccess === true);
c.set('kiloOrgMemberships', payload.orgMemberships ?? []);
onAuthenticated?.(payload);
} catch (err) {
console.warn(
'[kilo-auth] token verification failed:',
err instanceof Error ? err.message : 'unknown error'
);
return c.json(resError('Invalid token'), 401);
}

return next();
});
}
9 changes: 8 additions & 1 deletion services/gastown/src/gastown.worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ import {
townIdMiddleware,
type AuthVariables,
} from './middleware/auth.middleware';
import { kiloAuthMiddleware } from './middleware/kilo-auth.middleware';
import { createKiloAuthMiddleware } from '@kilocode/worker-utils/kilo-auth-middleware';
import { resolveSecret } from './util/secret.util';
import { validateCfAccessRequest } from '@kilocode/worker-utils/cf-access';

import { trpcServer } from '@hono/trpc-server';
Expand Down Expand Up @@ -171,6 +172,12 @@ export type GastownEnv = {
};

const app = new Hono<GastownEnv>();

const kiloAuthMiddleware = createKiloAuthMiddleware<GastownEnv>({
resolveSecret,
onAuthenticated: payload => logger.setTags({ userId: payload.kiloUserId }),
});

const LOCAL_DEV_HOSTNAMES = new Set(['localhost', '127.0.0.1', '[::1]']);

async function cfAccessDebugMiddleware(c: Context<GastownEnv>, next: () => Promise<void>) {
Expand Down
49 changes: 0 additions & 49 deletions services/gastown/src/middleware/kilo-auth.middleware.ts

This file was deleted.

1 change: 1 addition & 0 deletions services/wasteland/src/middleware/auth.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ export type AuthVariables = {
kiloUserId: string;
kiloIsAdmin: boolean;
kiloApiTokenPepper: string | null;
kiloGastownAccess: boolean;
kiloOrgMemberships: JwtOrgMembership[];
requestStartTime: number;
};
48 changes: 0 additions & 48 deletions services/wasteland/src/middleware/kilo-auth.middleware.ts

This file was deleted.

9 changes: 8 additions & 1 deletion services/wasteland/src/wasteland.worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@ import { logger } from './util/log.util';
import { useWorkersLogger } from 'workers-tagged-logger';
import type { MiddlewareHandler } from 'hono';
import type { AuthVariables } from './middleware/auth.middleware';
import { kiloAuthMiddleware } from './middleware/kilo-auth.middleware';
import { createKiloAuthMiddleware } from '@kilocode/worker-utils/kilo-auth-middleware';
import { resolveSecret } from './util/secret.util';
import { validateCfAccessRequest } from '@kilocode/worker-utils/cf-access';
import { timingMiddleware } from './middleware/analytics.middleware';
import { wrappedWastelandRouter } from './trpc/router';
Expand All @@ -37,6 +38,12 @@ export type WastelandEnv = {
};

const app = new Hono<WastelandEnv>();

const kiloAuthMiddleware = createKiloAuthMiddleware<WastelandEnv>({
resolveSecret,
onAuthenticated: payload => logger.setTags({ userId: payload.kiloUserId }),
});

async function cfAccessDebugMiddleware(c: Context<WastelandEnv>, next: () => Promise<void>) {
// Bypass CF Access in dev. We can't trust the request hostname for
// a localhost check — `wrangler dev` rewrites `request.url` to the
Expand Down