managarten/packages/shared-hono/src/auth.ts
Till JS 76d11a84ee feat(auth): server-side tier gating via requireTier middleware
The JWT already carried a `tier` claim but nothing on the server read it
— AuthGate enforcement was client-only, so a valid JWT could hit paid
LLM/research endpoints regardless of the user's access tier.

- shared-hono authMiddleware now extracts `tier` into `c.userTier`,
  defaulting unknown/missing claims to `public` (never silently grants
  higher access).
- New `requireTier(minTier)` middleware + `hasTier`/`getTierLevel`
  helpers. Tier hierarchy (guest < public < beta < alpha < founder) is
  mirrored locally to avoid pulling the Svelte-facing shared-branding
  package into Bun services.
- Applied `requireTier('beta')` as defense-in-depth on resource-heavy
  apps/api modules (chat, context, food, guides, news-research, picture,
  plants, research, traces, who) and the MCP endpoint. Pure CRUD modules
  stay auth-only — access there is gated by ownership, not tier.
- DEV_BYPASS_AUTH now injects `userTier` (defaults to founder, override
  via DEV_USER_TIER).
- Authentication guideline documents the pattern + test suite covers
  hierarchy, passes-at-minimum, and rejection paths.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-19 17:38:06 +02:00

140 lines
4 KiB
TypeScript

/**
* JWT authentication middleware for Hono servers.
*
* Verifies EdDSA JWTs from mana-auth via JWKS (cached).
* Drop-in replacement for @mana/shared-nestjs-auth JwtAuthGuard.
*
* Sets `userId`, `userEmail`, `userRole` on Hono context.
*/
import type { Context, Next } from 'hono';
import { HTTPException } from 'hono/http-exception';
import { createRemoteJWKSet, jwtVerify } from 'jose';
import type { AccessTier } from './types';
const VALID_TIERS: ReadonlySet<AccessTier> = new Set([
'guest',
'public',
'beta',
'alpha',
'founder',
]);
function readTierClaim(raw: unknown): AccessTier {
return typeof raw === 'string' && VALID_TIERS.has(raw as AccessTier)
? (raw as AccessTier)
: 'public';
}
const AUTH_URL = () => process.env.MANA_AUTH_URL ?? 'http://localhost:3001';
const SERVICE_KEY = () => process.env.MANA_SERVICE_KEY ?? '';
/** Cached JWKS - jose handles refetch cooldown (~10 min) */
let cachedJWKS: ReturnType<typeof createRemoteJWKSet> | null = null;
let cachedJWKSUrl: string | null = null;
function getJWKS(): ReturnType<typeof createRemoteJWKSet> {
const jwksUrl = `${AUTH_URL()}/api/v1/auth/jwks`;
if (cachedJWKS && cachedJWKSUrl === jwksUrl) {
return cachedJWKS;
}
cachedJWKS = createRemoteJWKSet(new URL(jwksUrl));
cachedJWKSUrl = jwksUrl;
return cachedJWKS;
}
/**
* Build the issuer allowlist — accepts auth service URL variants
* (internal Docker URL, public URL, localhost).
*/
function getIssuers(): string[] {
const issuers = new Set<string>();
const jwtIssuer = process.env.JWT_ISSUER;
const authUrl = process.env.MANA_AUTH_URL;
if (jwtIssuer) issuers.add(jwtIssuer);
if (authUrl) issuers.add(authUrl);
issuers.add('https://auth.mana.how');
issuers.add('http://localhost:3001');
return [...issuers];
}
/**
* JWT auth middleware — verifies Bearer token via JWKS.
*
* Usage:
* ```ts
* const app = new Hono();
* app.use('/api/*', authMiddleware());
* app.get('/api/profile', (c) => {
* const userId = c.get('userId');
* return c.json({ userId });
* });
* ```
*/
export function authMiddleware() {
return async (c: Context, next: Next) => {
// Dev bypass
if (process.env.NODE_ENV === 'development' && process.env.DEV_BYPASS_AUTH === 'true') {
c.set('userId', process.env.DEV_USER_ID ?? '00000000-0000-0000-0000-000000000000');
c.set('userEmail', 'dev@example.com');
c.set('userRole', 'user');
c.set('userTier', readTierClaim(process.env.DEV_USER_TIER ?? 'founder'));
return next();
}
const auth = c.req.header('Authorization');
if (!auth?.startsWith('Bearer ')) {
throw new HTTPException(401, { message: 'Missing authorization header' });
}
const token = auth.slice(7);
try {
const jwks = getJWKS();
const audience = process.env.JWT_AUDIENCE ?? 'mana';
const { payload } = await jwtVerify(token, jwks, {
issuer: getIssuers(),
audience,
});
if (!payload.sub) {
throw new HTTPException(401, { message: 'Token missing subject claim' });
}
const claims = payload as Record<string, unknown>;
c.set('userId', payload.sub);
c.set('userEmail', claims.email ?? '');
c.set('userRole', claims.role ?? 'user');
c.set('userTier', readTierClaim(claims.tier));
c.set('sessionId', claims.sid ?? '');
return next();
} catch (err) {
if (err instanceof HTTPException) throw err;
console.error('[auth] Token verification failed:', err instanceof Error ? err.message : err);
throw new HTTPException(401, { message: 'Invalid or expired token' });
}
};
}
/**
* Service key auth middleware — validates X-Service-Key header.
* Used for admin/GDPR endpoints called by mana-auth.
*
* Usage:
* ```ts
* app.use('/api/v1/admin/*', serviceAuthMiddleware());
* ```
*/
export function serviceAuthMiddleware() {
return async (c: Context, next: Next) => {
const key = c.req.header('X-Service-Key');
const expected = SERVICE_KEY();
if (!key || !expected || key !== expected) {
throw new HTTPException(401, { message: 'Invalid service key' });
}
return next();
};
}