mirror of
https://github.com/Memo-2023/mana-monorepo.git
synced 2026-05-17 12:29:40 +02:00
Pre-launch theme system audit found multiple parallel layers in themes.css
(--theme-X full hsl strings, --X partial shadcn aliases, --color-X populated
by runtime store with raw channels) plus dead-code companion files. The
inconsistency caused light-mode regressions when scoped-CSS consumers
wrote `var(--color-X)` standalone — the variable holds raw HSL channels
which is invalid as a color value, browser fell back to inherited (white).
Rewrite to one consistent layer:
- Source of truth: --color-X defined as raw HSL channels (e.g.
`0 0% 17%`) in :root, .dark, and all variant [data-theme="..."]
blocks. Matches the format the runtime store
(@mana/shared-theme/src/utils.ts) writes, eliminating the
static-fallback-vs-runtime mismatch and the corresponding flash
of unstyled content on hydration.
- @theme inline uses self-reference + Tailwind v4 <alpha-value>
placeholder so utility classes generate correctly AND opacity
modifiers work: `text-foreground/50` → `hsl(var(--color-foreground) / 0.5)`.
- @layer components (.btn-primary, .card, .badge, etc.) wraps
var(--color-X) refs with hsl() — they were broken in light mode
too for the same reason.
Convention going forward (also documented in the file header):
1. Markup: use Tailwind utility classes (text-foreground, bg-card, …)
2. Scoped CSS: hsl(var(--color-X)) — always wrap with hsl()
3. NEVER raw var(--color-X) in CSS — that's the bug pattern
Net file: 692 → 580 LOC. Single source layer, no indirection.
Also delete dead companion files (zero imports anywhere):
- tailwind-v4.css (had broken self-reference, never imported)
- theme-variables.css (legacy hex-based palette)
- components.css (legacy component utilities)
- index.js / preset.js / colors.js (Tailwind v3 preset format,
irrelevant under Tailwind v4)
package.json exports map shrinks accordingly to just `./themes.css`.
Consumers using `hsl(var(--color-X))` (~379 files across mana-web,
manavoxel-web, arcade-web) keep working unchanged — the public API
name `--color-X` is preserved. Only the broken pattern `var(--color-X)`
(~61 files) needs a follow-up sweep, handled in a separate commit.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
147 lines
7 KiB
TypeScript
147 lines
7 KiB
TypeScript
/**
|
|
* mana-auth — Central authentication service
|
|
*
|
|
* Hono + Bun runtime. Replaces NestJS-based mana-auth.
|
|
* Uses Better Auth natively (fetch-based handler, no Express conversion).
|
|
*/
|
|
|
|
import { Hono } from 'hono';
|
|
import { cors } from 'hono/cors';
|
|
import { loadConfig } from './config';
|
|
import { getDb } from './db/connection';
|
|
import { createBetterAuth } from './auth/better-auth.config';
|
|
import { serviceErrorHandler as errorHandler } from '@mana/shared-hono';
|
|
import { jwtAuth } from './middleware/jwt-auth';
|
|
import { serviceAuth } from './middleware/service-auth';
|
|
import { SecurityEventsService, AccountLockoutService } from './services/security';
|
|
import { SignupLimitService } from './services/signup-limit';
|
|
import { ApiKeysService } from './services/api-keys';
|
|
import { UserDataService } from './services/user-data';
|
|
import { EncryptionVaultService } from './services/encryption-vault';
|
|
import { loadKek } from './services/encryption-vault/kek';
|
|
import { createAuthRoutes } from './routes/auth';
|
|
import { createGuildRoutes } from './routes/guilds';
|
|
import { createApiKeyRoutes, createApiKeyValidationRoute } from './routes/api-keys';
|
|
import { createMeRoutes } from './routes/me';
|
|
import { createEncryptionVaultRoutes } from './routes/encryption-vault';
|
|
import { createSettingsRoutes } from './routes/settings';
|
|
import { createAdminRoutes } from './routes/admin';
|
|
|
|
// ─── Bootstrap ──────────────────────────────────────────────
|
|
|
|
const config = loadConfig();
|
|
const db = getDb(config.databaseUrl);
|
|
const auth = createBetterAuth(config.databaseUrl);
|
|
|
|
// Load the Key Encryption Key before any vault operation can run.
|
|
// Top-level await is supported by Bun. Throws if MANA_AUTH_KEK is
|
|
// missing in production or malformed in any environment.
|
|
await loadKek(config.encryptionKek);
|
|
|
|
// Initialize services
|
|
const security = new SecurityEventsService(db);
|
|
const lockout = new AccountLockoutService(db);
|
|
const signupLimit = new SignupLimitService(db);
|
|
const apiKeysService = new ApiKeysService(db);
|
|
const userDataService = new UserDataService(db, config);
|
|
const encryptionVaultService = new EncryptionVaultService(db);
|
|
|
|
// ─── App ────────────────────────────────────────────────────
|
|
|
|
const app = new Hono();
|
|
|
|
app.onError(errorHandler);
|
|
app.use(
|
|
'*',
|
|
cors({
|
|
origin: config.cors.origins,
|
|
credentials: true,
|
|
allowHeaders: ['Content-Type', 'Authorization', 'X-Service-Key', 'X-App-Id'],
|
|
exposeHeaders: ['Set-Cookie'],
|
|
})
|
|
);
|
|
|
|
// ─── Health ─────────────────────────────────────────────────
|
|
|
|
app.get('/health', (c) =>
|
|
c.json({ status: 'ok', service: 'mana-auth', timestamp: new Date().toISOString() })
|
|
);
|
|
|
|
// ─── Better Auth Native Handler ─────────────────────────────
|
|
|
|
app.all('/api/auth/*', async (c) => auth.handler(c.req.raw));
|
|
app.get('/.well-known/openid-configuration', async (c) => auth.handler(c.req.raw));
|
|
|
|
// ─── Custom Auth Endpoints ──────────────────────────────────
|
|
|
|
app.route('/api/v1/auth', createAuthRoutes(auth, config, security, lockout, signupLimit));
|
|
|
|
// ─── Guilds ─────────────────────────────────────────────────
|
|
|
|
app.use('/api/v1/gilden/*', jwtAuth(config.baseUrl));
|
|
app.route('/api/v1/gilden', createGuildRoutes(auth, config));
|
|
|
|
// ─── API Keys ───────────────────────────────────────────────
|
|
|
|
app.use('/api/v1/api-keys/*', jwtAuth(config.baseUrl));
|
|
app.route('/api/v1/api-keys', createApiKeyRoutes(apiKeysService));
|
|
app.route('/api/v1/api-keys', createApiKeyValidationRoute(apiKeysService));
|
|
|
|
// ─── Me (GDPR) ──────────────────────────────────────────────
|
|
|
|
app.use('/api/v1/me/*', jwtAuth(config.baseUrl));
|
|
app.route('/api/v1/me', createMeRoutes(userDataService));
|
|
|
|
// ─── Encryption vault (per-user master key custody) ────────
|
|
// Mounted under /me so it inherits the JWT middleware above and shows
|
|
// up in the same self-service surface as the GDPR endpoints.
|
|
app.route('/api/v1/me/encryption-vault', createEncryptionVaultRoutes(encryptionVaultService));
|
|
|
|
// ─── Settings ──────────────────────────────────────────────
|
|
|
|
app.use('/api/v1/settings/*', jwtAuth(config.baseUrl));
|
|
app.use('/api/v1/settings', jwtAuth(config.baseUrl));
|
|
app.route('/api/v1/settings', createSettingsRoutes(db));
|
|
|
|
// ─── Admin ──────────────────────────────────────────────────
|
|
|
|
app.use('/api/v1/admin/*', jwtAuth(config.baseUrl));
|
|
app.route('/api/v1/admin', createAdminRoutes(db, userDataService));
|
|
|
|
// ─── Internal API ───────────────────────────────────────────
|
|
|
|
app.use('/api/v1/internal/*', serviceAuth(config.serviceKey));
|
|
|
|
app.get('/api/v1/internal/org/:orgId/member/:userId', async (c) => {
|
|
const { orgId, userId } = c.req.param();
|
|
const { members } = await import('./db/schema/organizations');
|
|
const { eq, and } = await import('drizzle-orm');
|
|
const [member] = await db
|
|
.select()
|
|
.from(members)
|
|
.where(and(eq(members.organizationId, orgId), eq(members.userId, userId)))
|
|
.limit(1);
|
|
return c.json({ isMember: !!member, role: member?.role || '' });
|
|
});
|
|
|
|
// ─── Login Page (OIDC) ─────────────────────────────────────
|
|
|
|
app.get('/login', (c) => {
|
|
const q = c.req.query();
|
|
return c.html(`<!DOCTYPE html>
|
|
<html><head><title>Mana Login</title></head>
|
|
<body style="font-family:system-ui;max-width:400px;margin:80px auto;padding:20px;">
|
|
<h1>Mana Login</h1>
|
|
<form method="POST" action="/api/auth/sign-in/email">
|
|
<input type="hidden" name="callbackURL" value="${q.callbackURL || '/'}" />
|
|
<label>Email<br><input type="email" name="email" required style="width:100%;padding:8px;margin:4px 0 12px;"></label>
|
|
<label>Password<br><input type="password" name="password" required style="width:100%;padding:8px;margin:4px 0 12px;"></label>
|
|
<button type="submit" style="width:100%;padding:10px;background:#3b82f6;color:white;border:none;cursor:pointer;">Login</button>
|
|
</form></body></html>`);
|
|
});
|
|
|
|
// ─── Start ──────────────────────────────────────────────────
|
|
|
|
console.log(`mana-auth starting on port ${config.port}...`);
|
|
|
|
export default { port: config.port, fetch: app.fetch };
|