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
1 change: 1 addition & 0 deletions packages/worker-utils/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"./kilo-token-auth": "./src/kilo-token-auth.ts",
"./kilo-token": "./src/kilo-token.ts",
"./kilo-token-policy": "./src/kilo-token-policy.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 @@ -160,6 +160,16 @@ export type {
VerifiedKiloAuthContext,
} from './kilo-token-policy.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,18 +1,35 @@
import { describe, expect, it } from 'vitest';
import { Hono, type Context } from 'hono';
import { SignJWT } from 'jose';
import { GASTOWN_AUDIENCE } from '@kilocode/worker-utils/internal-service-token-audiences';
import { kiloAuthMiddleware } from './kilo-auth.middleware';
import type { GastownEnv } from '../gastown.worker';
import { GASTOWN_AUDIENCE } from './internal-service-token-audiences';
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() {
let downstreamCalls = 0;
const app = new Hono<GastownEnv>();
const app = new Hono<TestEnv>();
const kiloAuthMiddleware = createKiloAuthMiddleware<TestEnv>({
resolveSecret,
audiencePolicy: { audience: GASTOWN_AUDIENCE, mode: 'allow-legacy' },
});
app.use('/api/*', kiloAuthMiddleware);
app.use('/trpc/*', kiloAuthMiddleware);
const handler = (c: Context<GastownEnv>) => {
const handler = (c: Context<TestEnv>) => {
downstreamCalls += 1;
return c.json({
kiloUserId: c.get('kiloUserId'),
Expand Down Expand Up @@ -42,7 +59,7 @@ async function signToken(
}

async function request(
app: Hono<GastownEnv>,
app: Hono<TestEnv>,
token: string | undefined,
secret: string | { get(): Promise<string | null> } | null = TEST_SECRET
) {
Expand All @@ -57,7 +74,7 @@ async function request(
);
}

describe('kiloAuthMiddleware', () => {
describe('createKiloAuthMiddleware', () => {
it.each([
['missing authentication', undefined],
['malformed authentication', 'Bearer'],
Expand Down
93 changes: 93 additions & 0 deletions packages/worker-utils/src/kilo-auth-middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
import { createMiddleware } from 'hono/factory';
import type { MiddlewareHandler } from 'hono';
import { extractBearerToken } from './extract-bearer-token.js';
import type { KiloTokenPayload } from './kilo-token.js';
import type { KiloResourceAudiencePolicy } from './kilo-token-policy.js';
import { verifyKiloTokenForResource } from './kilo-token-policy.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;
audiencePolicy: KiloResourceAudiencePolicy;
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, audiencePolicy, 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 verifyKiloTokenForResource(token, secret, audiencePolicy);
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();
});
}
11 changes: 10 additions & 1 deletion services/gastown/src/gastown.worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ 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 { GASTOWN_AUDIENCE } from '@kilocode/worker-utils/internal-service-token-audiences';
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 +173,13 @@ export type GastownEnv = {
};

const app = new Hono<GastownEnv>();

const kiloAuthMiddleware = createKiloAuthMiddleware<GastownEnv>({
resolveSecret,
audiencePolicy: { audience: GASTOWN_AUDIENCE, mode: 'allow-legacy' },
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
54 changes: 0 additions & 54 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;
};
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,19 @@ import { describe, expect, it } from 'vitest';
import { Hono, type Context } from 'hono';
import { SignJWT } from 'jose';
import { WASTELAND_AUDIENCE } from '@kilocode/worker-utils/internal-service-token-audiences';
import { kiloAuthMiddleware } from './kilo-auth.middleware';
import { createKiloAuthMiddleware } from '@kilocode/worker-utils/kilo-auth-middleware';
import type { WastelandEnv } from '../wasteland.worker';
import { resolveSecret } from '../util/secret.util';

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

function createApp() {
let downstreamCalls = 0;
const app = new Hono<WastelandEnv>();
const kiloAuthMiddleware = createKiloAuthMiddleware<WastelandEnv>({
resolveSecret,
audiencePolicy: { audience: WASTELAND_AUDIENCE, mode: 'allow-legacy' },
});
app.use('/api/*', kiloAuthMiddleware);
app.use('/trpc/*', kiloAuthMiddleware);
const handler = (c: Context<WastelandEnv>) => {
Expand Down
53 changes: 0 additions & 53 deletions services/wasteland/src/middleware/kilo-auth.middleware.ts

This file was deleted.

11 changes: 10 additions & 1 deletion services/wasteland/src/wasteland.worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@ 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 { WASTELAND_AUDIENCE } from '@kilocode/worker-utils/internal-service-token-audiences';
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 +39,13 @@ export type WastelandEnv = {
};

const app = new Hono<WastelandEnv>();

const kiloAuthMiddleware = createKiloAuthMiddleware<WastelandEnv>({
resolveSecret,
audiencePolicy: { audience: WASTELAND_AUDIENCE, mode: 'allow-legacy' },
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