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
7 changes: 5 additions & 2 deletions cloudflare-gastown/src/gastown.worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,7 @@ import {
import { mayorAuthMiddleware } from './middleware/mayor-auth.middleware';
import { townAuthMiddleware } from './middleware/town-auth.middleware';
import { orgAuthMiddleware } from './middleware/org-auth.middleware';
import { adminAuditMiddleware } from './middleware/admin-audit.middleware';
import { timingMiddleware, instrumented } from './middleware/analytics.middleware';
import { handleGetTownConfig, handleUpdateTownConfig } from './handlers/town-config.handler';
import {
Expand Down Expand Up @@ -432,10 +433,12 @@ app.post('/api/towns/:townId/rigs/:rigId/triage/resolve', c =>
app.use('/api/users/*', async (c: Context<GastownEnv, string>, next) =>
kiloAuthMiddleware(c, next)
);
// Town routes: kilo auth + town ownership check (supports both personal and org-owned towns).
// Town routes: kilo auth + admin audit + town ownership check (supports both personal and org-owned towns).
app.use('/api/towns/:townId/*', async (c: Context<GastownEnv, string>, next) =>
kiloAuthMiddleware(c, async () => {
await townAuthMiddleware(c, next);
await adminAuditMiddleware(c, async () => {
await townAuthMiddleware(c, next);
});
})
);

Expand Down
40 changes: 40 additions & 0 deletions cloudflare-gastown/src/middleware/admin-audit.middleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { createMiddleware } from 'hono/factory';
import type { GastownEnv } from '../gastown.worker';
import { writeEvent } from '../util/analytics.util';

/**
* Middleware that logs admin access to town routes.
*
* Must run AFTER kiloAuthMiddleware (which sets kiloIsAdmin and kiloUserId).
* Only emits an analytics event when the request is from an admin user —
* regular user traffic is unaffected.
*
* The event is written to Cloudflare Analytics Engine with:
* - event: 'admin.town_access'
* - userId: the admin's user ID
* - townId: the town being accessed
* - route: the HTTP method + path
*/
export const adminAuditMiddleware = createMiddleware<GastownEnv>(async (c, next) => {
const isAdmin = c.get('kiloIsAdmin');
if (!isAdmin) return next();

const adminUserId = c.get('kiloUserId');
const townId = c.req.param('townId');
const method = c.req.method;
const path = c.req.path;

console.log(
`[admin-audit] Admin ${adminUserId} accessing town ${townId ?? 'N/A'}: ${method} ${path}`
);

writeEvent(c.env, {
event: 'admin.town_access',
delivery: 'http',
route: `${method} ${path}`,
userId: adminUserId,
townId: townId ?? undefined,
});

return next();
});
Loading
Loading