mirror of
https://github.com/Memo-2023/mana-monorepo.git
synced 2026-05-14 21:41:09 +02:00
refactor(infra): remove zitare + clock NestJS backends, add shared-hono package
Both apps are fully local-first via Dexie.js + mana-sync. Their NestJS backends were pure CRUD wrappers (20 + 31 source files) that are no longer needed. Changes: - Add packages/shared-hono: JWT auth via JWKS (jose), Drizzle DB factory, health route, generic GDPR admin handler, error middleware - Migrate zitare lists page from fetch() to listsStore (local-first) - Rewrite clock timers store from API-based to timerCollection (Dexie) - Update clock +layout.svelte CommandBar search to use local collections - Remove zitare-backend + clock-backend from docker-compose, CI/CD, Prometheus, env generation, setup scripts - Add docs/TECHNOLOGY_AUDIT_2026_03.md with full repo analysis Net result: -2 Docker containers, -2 ports, -2728 lines of code Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
parent
82de69476f
commit
32939fbfb5
81 changed files with 1236 additions and 2727 deletions
30
packages/shared-hono/package.json
Normal file
30
packages/shared-hono/package.json
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
{
|
||||
"name": "@manacore/shared-hono",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"description": "Shared Hono infrastructure: auth, health, admin, error handling for lightweight compute servers",
|
||||
"type": "module",
|
||||
"main": "./src/index.ts",
|
||||
"types": "./src/index.ts",
|
||||
"exports": {
|
||||
".": "./src/index.ts",
|
||||
"./auth": "./src/auth.ts",
|
||||
"./db": "./src/db.ts",
|
||||
"./health": "./src/health.ts",
|
||||
"./admin": "./src/admin.ts",
|
||||
"./error": "./src/error.ts"
|
||||
},
|
||||
"scripts": {
|
||||
"type-check": "tsc --noEmit"
|
||||
},
|
||||
"dependencies": {
|
||||
"hono": "^4.7.0",
|
||||
"jose": "^6.0.11",
|
||||
"drizzle-orm": "^0.45.1",
|
||||
"postgres": "^3.4.5"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.10.1",
|
||||
"typescript": "^5.9.3"
|
||||
}
|
||||
}
|
||||
74
packages/shared-hono/src/admin.ts
Normal file
74
packages/shared-hono/src/admin.ts
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
/**
|
||||
* Generic GDPR admin routes for Hono servers.
|
||||
*
|
||||
* Provides user-data count and deletion endpoints called by
|
||||
* mana-core-auth for GDPR compliance (right to be forgotten).
|
||||
*
|
||||
* Each app defines which tables contain user data; this module
|
||||
* handles the routing and service-key authentication.
|
||||
*/
|
||||
|
||||
import { Hono } from 'hono';
|
||||
import { eq, sql } from 'drizzle-orm';
|
||||
import type { PgTable } from 'drizzle-orm/pg-core';
|
||||
import { serviceAuthMiddleware } from './auth';
|
||||
|
||||
interface UserTable {
|
||||
/** Drizzle table reference */
|
||||
table: PgTable;
|
||||
/** Name shown in the response (e.g. "tasks", "favorites") */
|
||||
name: string;
|
||||
/** The user_id column on this table */
|
||||
userIdColumn: ReturnType<typeof sql>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create admin routes for GDPR compliance.
|
||||
*
|
||||
* Usage:
|
||||
* ```ts
|
||||
* import { adminRoutes } from '@manacore/shared-hono/admin';
|
||||
* import { tasks, projects, reminders } from './db';
|
||||
*
|
||||
* app.route('/api/v1/admin', adminRoutes(db, [
|
||||
* { table: tasks, name: 'tasks', userIdColumn: tasks.userId },
|
||||
* { table: projects, name: 'projects', userIdColumn: projects.userId },
|
||||
* { table: reminders, name: 'reminders', userIdColumn: reminders.userId },
|
||||
* ]));
|
||||
* ```
|
||||
*/
|
||||
export function adminRoutes(db: any, tables: UserTable[]): Hono {
|
||||
const route = new Hono();
|
||||
|
||||
route.use('/*', serviceAuthMiddleware());
|
||||
|
||||
/** Get user data counts across all tables. */
|
||||
route.get('/user-data/:userId', async (c) => {
|
||||
const userId = c.req.param('userId');
|
||||
const counts: Record<string, number> = {};
|
||||
|
||||
for (const { table, name, userIdColumn } of tables) {
|
||||
const [result] = await db
|
||||
.select({ count: sql<number>`count(*)` })
|
||||
.from(table)
|
||||
.where(eq(userIdColumn, userId));
|
||||
counts[name] = Number(result?.count ?? 0);
|
||||
}
|
||||
|
||||
return c.json({ userId, counts });
|
||||
});
|
||||
|
||||
/** Delete all user data (GDPR right to be forgotten). */
|
||||
route.delete('/user-data/:userId', async (c) => {
|
||||
const userId = c.req.param('userId');
|
||||
|
||||
// Delete in reverse order (children before parents if there are FKs)
|
||||
for (const { table, userIdColumn } of [...tables].reverse()) {
|
||||
await db.delete(table).where(eq(userIdColumn, userId));
|
||||
}
|
||||
|
||||
return c.json({ userId, deleted: true, message: 'All user data deleted' });
|
||||
});
|
||||
|
||||
return route;
|
||||
}
|
||||
122
packages/shared-hono/src/auth.ts
Normal file
122
packages/shared-hono/src/auth.ts
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
/**
|
||||
* JWT authentication middleware for Hono servers.
|
||||
*
|
||||
* Verifies EdDSA JWTs from mana-core-auth via JWKS (cached).
|
||||
* Drop-in replacement for @manacore/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';
|
||||
|
||||
const AUTH_URL = () => process.env.MANA_CORE_AUTH_URL ?? 'http://localhost:3001';
|
||||
const SERVICE_KEY = () => process.env.MANA_CORE_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_CORE_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');
|
||||
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 ?? 'manacore';
|
||||
|
||||
const { payload } = await jwtVerify(token, jwks, {
|
||||
issuer: getIssuers(),
|
||||
audience,
|
||||
});
|
||||
|
||||
if (!payload.sub) {
|
||||
throw new HTTPException(401, { message: 'Token missing subject claim' });
|
||||
}
|
||||
|
||||
c.set('userId', payload.sub);
|
||||
c.set('userEmail', (payload as Record<string, unknown>).email ?? '');
|
||||
c.set('userRole', (payload as Record<string, unknown>).role ?? 'user');
|
||||
c.set('sessionId', (payload as Record<string, unknown>).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-core-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();
|
||||
};
|
||||
}
|
||||
49
packages/shared-hono/src/db.ts
Normal file
49
packages/shared-hono/src/db.ts
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
/**
|
||||
* Drizzle ORM database connection factory for Hono servers.
|
||||
*
|
||||
* Provides a lightweight connection with sensible defaults.
|
||||
* Each server defines its own minimal schema (only tables it needs).
|
||||
*/
|
||||
|
||||
import { drizzle } from 'drizzle-orm/postgres-js';
|
||||
import postgres from 'postgres';
|
||||
|
||||
export interface DbOptions {
|
||||
/** PostgreSQL connection URL */
|
||||
url?: string;
|
||||
/** Max connections (default: 5) */
|
||||
maxConnections?: number;
|
||||
/** Idle timeout in seconds (default: 20) */
|
||||
idleTimeout?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a Drizzle database instance with postgres.js driver.
|
||||
*
|
||||
* Usage:
|
||||
* ```ts
|
||||
* import { createDb } from '@manacore/shared-hono/db';
|
||||
* import { tasks, projects } from './schema';
|
||||
*
|
||||
* const db = createDb({
|
||||
* schema: { tasks, projects },
|
||||
* });
|
||||
* ```
|
||||
*/
|
||||
export function createDb<TSchema extends Record<string, unknown>>(
|
||||
opts?: DbOptions & { schema?: TSchema }
|
||||
) {
|
||||
const url =
|
||||
opts?.url ??
|
||||
process.env.DATABASE_URL ??
|
||||
'postgresql://manacore:devpassword@localhost:5432/mana';
|
||||
|
||||
const connection = postgres(url, {
|
||||
max: opts?.maxConnections ?? 5,
|
||||
idle_timeout: opts?.idleTimeout ?? 20,
|
||||
});
|
||||
|
||||
return drizzle(connection, {
|
||||
schema: opts?.schema as TSchema,
|
||||
});
|
||||
}
|
||||
47
packages/shared-hono/src/error.ts
Normal file
47
packages/shared-hono/src/error.ts
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
/**
|
||||
* Error handling middleware for Hono servers.
|
||||
*
|
||||
* Catches unhandled errors and returns consistent JSON responses.
|
||||
*/
|
||||
|
||||
import type { Context } from 'hono';
|
||||
import { HTTPException } from 'hono/http-exception';
|
||||
|
||||
/**
|
||||
* Global error handler — register with `app.onError(errorHandler)`.
|
||||
*
|
||||
* Usage:
|
||||
* ```ts
|
||||
* import { errorHandler } from '@manacore/shared-hono/error';
|
||||
* const app = new Hono();
|
||||
* app.onError(errorHandler);
|
||||
* ```
|
||||
*/
|
||||
export function errorHandler(err: Error, c: Context) {
|
||||
if (err instanceof HTTPException) {
|
||||
return c.json(
|
||||
{
|
||||
error: err.message,
|
||||
status: err.status,
|
||||
},
|
||||
err.status
|
||||
);
|
||||
}
|
||||
|
||||
console.error('[error]', err);
|
||||
|
||||
return c.json(
|
||||
{
|
||||
error: 'Internal server error',
|
||||
status: 500,
|
||||
},
|
||||
500
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Not-found handler — register with `app.notFound(notFoundHandler)`.
|
||||
*/
|
||||
export function notFoundHandler(c: Context) {
|
||||
return c.json({ error: 'Not found', status: 404 }, 404);
|
||||
}
|
||||
36
packages/shared-hono/src/health.ts
Normal file
36
packages/shared-hono/src/health.ts
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
/**
|
||||
* Health check route for Hono servers.
|
||||
*
|
||||
* Returns JSON compatible with the NestJS HealthModule format
|
||||
* so monitoring/health-checks work without changes.
|
||||
*/
|
||||
|
||||
import { Hono } from 'hono';
|
||||
|
||||
const startTime = Date.now();
|
||||
|
||||
/**
|
||||
* Create a health check route.
|
||||
*
|
||||
* Usage:
|
||||
* ```ts
|
||||
* import { healthRoute } from '@manacore/shared-hono/health';
|
||||
* app.route('/health', healthRoute('calendar-server'));
|
||||
* ```
|
||||
*/
|
||||
export function healthRoute(serviceName: string, version?: string): Hono {
|
||||
const route = new Hono();
|
||||
|
||||
route.get('/', (c) =>
|
||||
c.json({
|
||||
status: 'ok',
|
||||
service: serviceName,
|
||||
runtime: 'bun',
|
||||
timestamp: new Date().toISOString(),
|
||||
uptime: Math.floor((Date.now() - startTime) / 1000),
|
||||
...(version ? { version } : {}),
|
||||
})
|
||||
);
|
||||
|
||||
return route;
|
||||
}
|
||||
41
packages/shared-hono/src/index.ts
Normal file
41
packages/shared-hono/src/index.ts
Normal file
|
|
@ -0,0 +1,41 @@
|
|||
/**
|
||||
* @manacore/shared-hono — Shared infrastructure for Hono + Bun compute servers.
|
||||
*
|
||||
* Replaces NestJS boilerplate (Module, Controller, Guard, HealthModule, MetricsModule)
|
||||
* with lightweight Hono equivalents.
|
||||
*
|
||||
* Usage:
|
||||
* ```ts
|
||||
* import { Hono } from 'hono';
|
||||
* import { cors } from 'hono/cors';
|
||||
* import { logger } from 'hono/logger';
|
||||
* import { authMiddleware, serviceAuthMiddleware } from '@manacore/shared-hono/auth';
|
||||
* import { createDb } from '@manacore/shared-hono/db';
|
||||
* import { healthRoute } from '@manacore/shared-hono/health';
|
||||
* import { adminRoutes } from '@manacore/shared-hono/admin';
|
||||
* import { errorHandler, notFoundHandler } from '@manacore/shared-hono/error';
|
||||
*
|
||||
* const app = new Hono();
|
||||
* app.onError(errorHandler);
|
||||
* app.notFound(notFoundHandler);
|
||||
* app.use('*', logger());
|
||||
* app.use('*', cors({ origin: process.env.CORS_ORIGINS?.split(',') ?? ['http://localhost:5173'] }));
|
||||
*
|
||||
* app.route('/health', healthRoute('my-server'));
|
||||
* app.use('/api/*', authMiddleware());
|
||||
* app.route('/api/v1/admin', adminRoutes(db, userTables));
|
||||
*
|
||||
* // App-specific compute routes
|
||||
* app.route('/api/v1/compute', myRoutes);
|
||||
*
|
||||
* export default { port: Number(process.env.PORT ?? 3019), fetch: app.fetch };
|
||||
* ```
|
||||
*/
|
||||
|
||||
export { authMiddleware, serviceAuthMiddleware } from './auth';
|
||||
export { createDb } from './db';
|
||||
export type { DbOptions } from './db';
|
||||
export { healthRoute } from './health';
|
||||
export { adminRoutes } from './admin';
|
||||
export { errorHandler, notFoundHandler } from './error';
|
||||
export type { CurrentUserData, AuthVariables } from './types';
|
||||
20
packages/shared-hono/src/types.ts
Normal file
20
packages/shared-hono/src/types.ts
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
/**
|
||||
* User data extracted from a verified JWT token.
|
||||
* Compatible with @manacore/shared-nestjs-auth CurrentUserData.
|
||||
*/
|
||||
export interface CurrentUserData {
|
||||
userId: string;
|
||||
email: string;
|
||||
role: string;
|
||||
sessionId?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hono context variables set by auth middleware.
|
||||
*/
|
||||
export interface AuthVariables {
|
||||
userId: string;
|
||||
userEmail: string;
|
||||
userRole: string;
|
||||
sessionId?: string;
|
||||
}
|
||||
14
packages/shared-hono/tsconfig.json
Normal file
14
packages/shared-hono/tsconfig.json
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"compilerOptions": {
|
||||
"target": "ES2022",
|
||||
"module": "ES2022",
|
||||
"moduleResolution": "bundler",
|
||||
"strict": true,
|
||||
"esModuleInterop": true,
|
||||
"skipLibCheck": true,
|
||||
"outDir": "dist",
|
||||
"declaration": true,
|
||||
"types": ["node"]
|
||||
},
|
||||
"include": ["src/**/*.ts"]
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue