feat(research): cut over canonical runtime and enforce agent budgets

This commit is contained in:
Boki 2026-10-24 16:47:19 -04:00
parent ab08db82fd
commit bbf0dd4453
103 changed files with 6138 additions and 3112 deletions

View file

@ -4,6 +4,15 @@ import type { Hono, MiddlewareHandler } from 'hono';
type Role = 'read' | 'admin' | 'service';
const verifiedPrincipals = new WeakMap<Request, 'operator' | 'service'>();
const credentialRequests = new WeakSet<Request>();
const researchPrincipals = new WeakMap<Request, `agent:${string}`>();
const researchBearer = (request: Request) =>
/^Bearer sb-research\./i.test(request.headers.get('authorization') ?? '');
/** Research routes opt into this accessor; privileged service/operator accessors never impersonate agents. */
export function getResearchHttpPrincipal(
request: Request
): 'operator' | 'service' | `agent:${string}` | undefined {
return researchPrincipals.get(request) ?? getCredentialHttpPrincipal(request);
}
/** Server-owned identity established only after successful HTTP authorization. */
export function getVerifiedHttpPrincipal(request: Request): 'operator' | 'service' | undefined {
@ -22,6 +31,10 @@ export interface HttpSecurityOptions {
hostname?: string;
origins?: string[];
browserSessions?: boolean;
/** Explicit web API HTTP capability; never used by synchronous authorize or WebSocket upgrades. */
resolveResearchCredential?: (
request: Request
) => Promise<{ principal: `agent:${string}` } | Response | undefined>;
}
const cookieName = 'stock_bot_session';
const sessionSeconds = 3600;
@ -153,7 +166,14 @@ export function createHttpSecurity(options: HttpSecurityOptions = httpSecurityOp
return { role, cookie: true };
}
function authorize(request: Request, admin = false): Response | undefined {
researchPrincipals.delete(request);
verifiedPrincipals.delete(request);
if (researchBearer(request)) {
return Response.json(
{ error: 'Research credentials are unavailable on this interface' },
{ status: 403, headers: { 'Cache-Control': 'no-store' } }
);
}
credentialRequests.delete(request);
const identity = authenticate(request);
if (!identity) {
@ -193,6 +213,28 @@ export function createHttpSecurity(options: HttpSecurityOptions = httpSecurityOp
await next();
return undefined;
}
if (researchBearer(context.req.raw)) {
context.header('Cache-Control', 'no-store');
if (disabled || !options.resolveResearchCredential || context.req.header('upgrade')) {
return context.json(
{ error: 'Research credentials are unavailable on this interface' },
403
);
}
if (context.req.header('origin') && !originAllowed(context.req.raw)) {
return context.json({ error: 'Untrusted request origin' }, 403);
}
const resolved = await options.resolveResearchCredential(context.req.raw);
if (resolved instanceof Response) {
return resolved;
}
if (!resolved) {
return context.json({ error: 'Invalid or disabled research credential' }, 401);
}
researchPrincipals.set(context.req.raw, resolved.principal);
await next();
return undefined;
}
const admin =
!['GET', 'HEAD'].includes(context.req.method) ||
/^\/api\/(queue|operations|handlers)(\/|$)/.test(path);
@ -243,6 +285,12 @@ export function createHttpSecurity(options: HttpSecurityOptions = httpSecurityOp
if (token.length > 4096) {
return context.json({ error: 'Invalid access token' }, 401);
}
if (token.startsWith('sb-research.')) {
return context.json(
{ error: 'Research credentials cannot establish browser sessions' },
403
);
}
const role = disabled ? 'admin' : roleForToken(token);
if (!role || role === 'service') {
return context.json({ error: 'Invalid access token' }, 401);
@ -266,7 +314,13 @@ export function createHttpSecurity(options: HttpSecurityOptions = httpSecurityOp
return context.json({ authenticated: false });
});
}
return { mount, authorize, hostname, allowedOrigins };
return {
mount,
authorize,
hostname,
allowedOrigins,
researchEnabled: !disabled && !!options.resolveResearchCredential,
};
}
export type HttpSecurity = ReturnType<typeof createHttpSecurity>;

View file

@ -8,6 +8,7 @@ export {
authenticatedServiceFetch,
getVerifiedHttpPrincipal,
getCredentialHttpPrincipal,
getResearchHttpPrincipal,
} from './http/security';
export type { HttpSecurity, HttpSecurityOptions } from './http/security';
export { calculatePoolSize, getServicePoolSize, getHandlerPoolSize } from './pool-size-calculator';