Skip to content
Projects

About

防代码腐化的 AI 时代 TypeScript 全栈模板:契约先行、架构机械护栏,基于 Fastify 5 + Effect 4 + React 19 + PostgreSQL 18,内置 15 大后台模块开箱即用。演示地址:https://demo.zheqi.mom/

Web & App Development

How these counts are measured

Measured star growth

in 24h
0
in 7 days
Collecting history
in 15 days
Collecting history
in 1 month
Collecting history

Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.

README.en.md

Original

Verluma — A Full-Stack TypeScript Template Designed for AI-Assisted Development

English | 简体中文

license node typescript Fastify 5 Effect 4


Verluma pairs a Fastify API with a React admin console in a TypeScript monorepo. A shared Zod contract drives the API documentation and gives the admin console typed requests and responses.

Verluma — Developer Platform

Quick Start · Why Verluma · Architecture · Key Capabilities · Deployment

Quick Start

Prerequisites

  • Node.js >= 26.0.0
  • pnpm 11.22.0 (install with npm install --global [email protected])
  • Docker (for local PostgreSQL 18, Valkey 8.1 (Redis-compatible), S3-compatible object storage, and the Hatchet Lite workflow engine)

Create a project from the template

From a local clone of Verluma, generate the full project and switch to its directory.

pnpm template create --out ../my-app
cd ../my-app

To omit the import and export modules, use --preset without-import-export. Add --dry-run to preview the preset and output path. Choose a new or empty directory outside the template repository. To try Verluma itself, run the steps below in the clone.

Preset differences and file selection

Both presets include accounts, permissions, file uploads and downloads, auditing, and webhooks. The smaller preset removes the import and export contracts, tasks, pages, dependencies, and demo data. It retains existing database migrations and blocks new download signatures for historical exports.

The generator copies working-tree contents from the Git file list and includes new TypeScript files in source directories. Add new configuration files, migrations, and assets to Git before generating. Local environment settings, editor settings, installed dependencies, logs, and template tools stay in the source repository. When maintaining the template, run pnpm template:check to validate both presets. Changes to shared files for the smaller preset live in scripts/template/without-import-export.patch.

Up and Running in 4 Steps

# 1. Install dependencies
pnpm install --frozen-lockfile

# 2. One-shot setup (.env generation -> Docker infra -> migrate & seed -> S3 bucket & CORS)
pnpm run setup --workflows

# 3. Verify environment and non-privileged DB role setup
pnpm doctor

# 4. Select the API server and admin console in the dev menu
pnpm dev

Once both apps are running, open the admin console. Choose a test account under 快速填入测试账号 on the sign-in page to fill in its credentials, then sign in. The development API starts at APP_PORT (default 3000) and tries the next port if it is occupied. The admin proxy follows the selected port. The API startup banner shows the interactive API reference on its docs line.

Local development and schema iteration

The dev menu defaults to both apps. Use the arrow keys to switch task logs in Turborepo and Ctrl+C to exit. In a non-interactive terminal, pnpm dev starts the API with streamed logs.

Using external Postgres/Redis instances? Run pnpm run setup --no-docker to skip local containers.

Iterating on the local schema

After pnpm run setup, set DATABASE_PUSH_URL in the root .env to the owner connection for your disposable development database. Run pnpm --filter @verluma/db db:push as you edit the Drizzle schema. Repeated pushes create no migration files.

When the feature is ready, run pnpm --filter @verluma/db db:generate, review the SQL, add any data backfill, and run pnpm --filter @verluma/db db:check-ddl. Point DATABASE_MIGRATE_URL at a separate database on the previous version and run pnpm --filter @verluma/db db:migrate to verify the upgrade. A pushed database has no journal entry for the new migration, so replaying it there can encounter existing tables or columns.

Why Verluma

Verluma grew out of clhoria-template and over a year of using it in production.

In fast-moving codebases built alongside AI coding agents, entropy tends to creep in through four failure modes: contract drift (backend, docs, and frontend types falling out of sync), layer leakage (SQL in services, cross-slice table coupling, side effects inside pure logic), silent defects (Effect/async misuse, non-atomic state transitions, weak tests tailored to buggy code), and unsafe operations (destructive DDL, missing permission checks, or CSRF exposure).

  • Contract as Single Source of Truth: @verluma/contract defines domain-scoped procedures and permissions once in Zod v4. From that single source, Verluma derives oRPC RPC handlers, OpenAPI 3.1 + Scalar docs, MCP tools (/api/mcp), typed frontend clients, and <Can /> UI guards.
  • Architecture checks (Harness-Engineered): Importing drizzle-orm in a service.ts file or importing another feature slice’s repo.ts triggers a lint error. CI also checks destructive DDL and Cedar policies. Property tests and incremental mutation testing cover the functional core.
  • Production-Ready Out of the Box: Ships with 15 complete system domains, dual-role PostgreSQL isolation, structured Wide Events observability, Hatchet v1 workflows, S3 presigned uploads, real-time SSE inbox notifications, and a decoupled admin console.

Architecture

FCIS + Hexagonal Vertical Slices

Every backend feature slice is split into four files with strict dependency boundaries enforced mechanically by oxlint:

File Architectural Role Allowed Dependencies Mechanically Forbidden
logic.ts Functional Core @verluma/contract, ts-pattern, pure helpers & types effect, #infra/*, @verluma/db*, node:*
service.ts Imperative Shell (Effect v4) effect, #shared/*, #infra/*.layer, logic.ts, repo.ts drizzle-orm, @verluma/db/schema, raw SQL assembly
repo.ts Driven Adapter drizzle-orm, @verluma/db/schema, #shared/scope-sql, DbService Cross-slice repo.ts imports, non-DB side-effect ports
router.ts / tasks.ts Driving Adapter @orpc/*, @verluma/contract, local service.ts Direct repo.ts SQL access, domain rule orchestration
Why TypeScript Instead of Another Backend Language?
  • Unified full stack and maximum AI leverage: TypeScript unifies the frontend and backend language and type system, letting contracts and data models be reused directly and sharply reducing the context-switching cost of full-stack work. More importantly, in the age of AI-assisted coding, TypeScript not only has the largest ecosystem and training corpus, but its strong static type system also acts as a built-in error guardrail, catching the vast majority of structural mistakes in AI-generated code at compile time.
  • Taking the "single-threaded" critique in stride: Most business systems are bottlenecked by I/O-bound work (database queries, cache reads/writes, network requests), not pure CPU computation. Node.js's event-loop-based, non-blocking async I/O model handles high-concurrency I/O with ease; in production, multi-process or multi-instance containers readily saturate multi-core CPUs, while native Worker Threads isolate routine background computation.
  • A smooth performance escape hatch (Rust + napi-rs / WASM): Choosing TypeScript does not mean giving up low-level performance. When a genuinely CPU-heavy hot spot appears (complex file parsing, encryption, image processing, and so on), there is no need to rewrite the whole backend stack for a local bottleneck — with mature napi-rs or WebAssembly, AI can cheaply write standalone Rust modules to take over the core computation, keeping TypeScript's high development velocity while approaching native execution limits.
Why a Modular Monolith Instead of Microservices?

A monolith is not the sin. Premature microservices are.

  • Lower cognitive overhead for development and operations: Until team size and business boundaries actually demand independent delivery from multiple teams, a monolith skips distributed transactions, cross-service tracing, and complex deployment orchestration. Local debugging, repo-wide refactors, and incident triage are far faster. Strict module boundaries keep the code clean without splitting services.
  • Microservices solve an organizational problem, not a silver bullet: Splitting too early usually lands you in a "distributed monolith" — all the complexity of a distributed system with none of the independent-evolution payoff.
  • A smooth scaling path: Keep the application layer stateless, scale horizontally across instances, and add caching, message queues, and read replicas; that covers the vast majority of high-concurrency workloads. If one module ever needs extreme resources or independent scaling, peel it off along the existing clear boundaries — far cheaper than going all-in on microservices from day one.
Why PostgreSQL 18, and Why We Hold Off on Sharding?
  • Feature-complete, fewer moving parts: PostgreSQL has a mature query optimizer, rigorous SQL standard support, and rich native and extension capabilities such as JSONB, arrays, full-text search, and even pgvector. In many cases you can avoid bolting on MongoDB or Elasticsearch, which meaningfully reduces architectural complexity. PostgreSQL 18 adds asynchronous I/O (AIO), native UUIDv7, and index skip scan, making single-node performance very strong on modern hardware.
  • No dogmatic early sharding: Many teams introduce sharding early out of habit from an era of weaker hardware. Shard too soon and you immediately give up cross-table JOINs, foreign-key constraints, and local ACID transactions, while development and operations costs multiply. In reality, database bottlenecks depend on hot-data volume and read/write concurrency, not raw row counts. On modern NVMe SSDs and large memory, a well-modeled and well-indexed single PostgreSQL node can comfortably handle tens of millions to hundreds of millions of rows.
  • A gradual capacity path: When a single table truly reaches the billion-row scale (especially time-series workloads such as logs and orders), reach first for PostgreSQL's native declarative partitioning, which addresses index bloat, declining hot-data cache hit rates, VACUUM maintenance cost, and cold-data archiving. Only when business growth pushes single-node physical I/O or write throughput to its real ceiling should you move to read replicas, vertical database splitting, or a distributed cluster — the pragmatic engineering choice.
Can You Run on PostgreSQL Alone?

For small teams, splitting PostgreSQL, Redis, object storage, and a workflow engine into four separately operated components adds real operational and billing overhead. Verluma agrees with the direction of “collapsing onto PostgreSQL where possible”, but the current boundary needs to be stated plainly: the default runtime is still PostgreSQL + Redis + S3-compatible storage + Hatchet + OTLP, and there is no out-of-the-box “PG-only” preset yet.

  • Already inside PostgreSQL: sessions, auditing, idempotency, business data, and Hatchet task state all live in PostgreSQL (Hatchet Lite reuses the same instance with a separate database). In development, HATCHET_PROVIDER=stub skips the workflow container, but the stub only records dispatches and does not execute tasks; production still requires real.
  • Not yet collapsed: Redis handles authorization caching, version INCR, cross-instance SSE Pub/Sub, and distributed locks; object storage uses the S3 protocol; observability requires an OTLP endpoint. All three are bound to production implementations by the composition root today; the in-memory/layerStub variants serve tests only.
  • The switchable boundary is already in place: RedisService, StorageService, and HatchetService are isolated as Effect services under apps/api/src/infra/, and business slices depend only on the interfaces. To actually build a “PG-only lite” profile, you can add PG table caching, LISTEN/NOTIFY, advisory locks, large objects/local disk, and SKIP LOCKED or pgmq for queues, then switch the composition root through a lightweight preset without touching business code.

In other words: PG-only is a low-cost evolution direction in the current architecture, not a shipped default. Teams optimizing for the smallest operational surface can use this to weigh cutting Redis / S3 / workflow components against what they give up.

Key Capabilities

1. Contract-First Protocols & Scoped Security Boundaries

  • Multi-Protocol Derivation: Contracts are organized into extensible domain scopes (shipping with admin, client, and public out of the box) with independent protocol exposure rules—by default, admin mounts exclusively at /api/rpc/admin/* (never exported to public REST), client and public expose both /api/rpc/* and OpenAPI 3.1 REST /api/v1/*, and procedures marked mcp: true are automatically exposed as MCP tools at /api/mcp.
  • Isolated AuthN & CSRF Protection: Powered by Better Auth (scrypt + bearer + username + twoFactor TOTP 2FA + Drizzle relations-v2 with joins: true single-SQL session lookups). Browser Cookie scopes enforce Origin / Sec-Fetch-Site and GET CSRF protection, while non-browser Bearer REST scopes strip Cookie headers before session resolution.
  • AWS Cedar Authorization & Row-Level Data Scope: ACTIONS serves as the single permission truth across backend authorize() and frontend <Can permission="..." />. Ships single-tenant by default with 5-level department-tree row visibility (ALL / DEPT_AND_CHILDREN / DEPT_ONLY / CUSTOM / SELF_ONLY), plus opt-in PostgreSQL multi-tenant RLS support.

2. PostgreSQL 18 Foundation & Migration Guardrails

  • Modern PG 18 Primitives: Native DEFAULT uuidv7() primary keys, pgInstant mapping to native Temporal.Instant, and conditional atomic SQL (UPDATE ... WHERE id = $1 AND status = $2 RETURNING *) for state transitions to eliminate read-then-write races.
  • Dual-Role Isolation: Migrations run under the owner account (DATABASE_MIGRATE_URL), while the API runtime connects as verluma_app (NOSUPERUSER, NOBYPASSRLS, no DDL privileges).
  • Database migrations: Personal development databases support Drizzle push. Shared environments apply Drizzle-generated SQL checked by Squawk (db:check-ddl), using Drizzle's official migrator wrapped with a session advisory lock and lock/statement timeouts. @verluma/db-comments syncs PostgreSQL comments incrementally.

3. 15 Built-in System Domains (End-to-End)

The system slices cover account security, organizational permissions, data governance, notifications, and operations.

View the module list
Module Description
auth Session snapshot (auth.me), profile & presigned avatar upload, audited password changes, and TOTP 2FA
users Full user lifecycle (status/soft-delete/batch ops), password reset, department binding, roles, and data scoping
roles Role definitions, permission sets, 5-level data scopes, built-in role guards, and role-side member management
departments Hierarchical org tree, ancestors path maintenance, department leaders, and child/member deletion guards
dicts Dictionary types & items with public vs. admin visibility separation
params System parameters demonstrating both Offset and Cursor ((sortByVal, id)) pagination
resources Private S3 / MinIO presigned direct uploads, confirmUpload, and presigned downloads
exports Asynchronous CSV export jobs via Hatchet v1 with progress tracking, completion notifications, and signed download
imports Asynchronous batch import jobs via Hatchet v1 with template downloads, presigned uploads, and error reports
notices System announcements (draft/published/revoked atomic transitions), pinning, targeted scopes, & read counts
notifications Unified user inbox (personal notifications + visible notices), unread counters, mark-read, and real-time SSE push
sessions Active session inspection and forced revocation (session:revoke)
audit-logs Structured administrative audit logs (before/after snapshots + traceId) and dedicated login logs
dashboard Live data-driven overview aggregation (7d/30d/90d trends, KPI deltas, module rankings, health radar, activity)
ops Operations console: runtime/health probes, Redis SCAN cache governance & authz purge, Webhook inspection/replay

4. Admin Console (apps/admin)

  • Modern Frontend Stack: React 19 (React Compiler enabled globally) + Vite 8 + TanStack Router / Query / Table / Form + Tailwind CSS v4 + Base UI (@base-ui/react) + Recharts + OKLCH light/dark semantic tokens.
  • Zero sys_menu Coupling: Routes and navigation are statically typed in the frontend and bound directly to Permission from @verluma/contract/permissions, with declarative <Can /> UI guards.
  • Cohesive UX & Error Mapping: Reusable ListPageShell, DetailDrawerShell, and DashboardShell with multi-tab navigation (TabBar), live SSE notification bell, real-data dashboard, and ops tooling; applyServerError() maps backend 400/422 validation issues directly onto TanStack Form fields with one-click traceId copy in toasts; backed by Playwright smoke E2E tests.

Verluma Admin Console — Dashboard Verluma Admin Console — User Management

5. Anti-Black-Box Observability & Runtime Resilience

  • Single Wide-Event Outlet: Fastify's default request logger is disabled in favor of Effect's WideEventCollector, emitting one structured, credential-redacted wide event per request/job. In development, events render as colorized terminal summaries plus .logs/dev.ndjson (with automatic suspected N+1 and slow-transaction warnings); in production, standard OTLP integrates cleanly (local Aspire Dashboard included).
  • Production Runtime Primitives: Zero-dependency /healthz and drain-aware /readyz (503 on shutdown), topology-reverse graceful shutdown via Effect bootstrap(Layer), HMAC-verified Webhook ingestion with SKIP LOCKED fallback, SSE real-time notifications, and Cap.js PoW captcha support.

Scripts Reference

View commands by task
Category Command Purpose
Development pnpm run setup / pnpm doctor Bootstrap local stack / check environment & non-privileged DB roles
pnpm dev Choose the API, admin console, or both
pnpm dev:api / pnpm dev:admin Start just the API or admin console
pnpm dev:all Start both apps directly
pnpm --filter @verluma/api dev:worker Run standalone Hatchet background worker
Quality Gates pnpm check Run typecheck + lint + format:check + test + knip
pnpm check:ci Local CI-equivalent gate (includes db:check-ddl and authz:validate)
pnpm mutation / pnpm mutation:all Incremental mutation testing against HEAD / full mutation run
pnpm --filter @verluma/admin test:e2e Run Playwright smoke E2E tests
AI & Scaffolds pnpm slice <name> --group <g> --wire Scaffold a pure FCIS vertical slice and wire it up (--dry-run supported)
pnpm logs -- --warnings Query .logs/dev.ndjson wide events (--trace, --errors, --job)
pnpm codemod -- --pattern ... Safe ast-grep AST search/rewrite (preview by default, --apply to write)
pnpm mcp:ts Run the local TypeScript 7 symbol MCP server
Rebranding pnpm rename <name> One-shot template de-branding (--dry-run supported)

Deployment

Generate an independent random BETTER_AUTH_SECRET of at least 32 characters for production. To enable webhooks, supply the same idempotent business processor to acquireCoreAppRuntime(env, { health, webhookProcessor }) in the API and worker, then set a separate WEBHOOK_HMAC_SECRET. Configuring the secret alone causes startup to fail with a missing-processor error. Run pnpm run setup only against development or test databases because it writes demo data.

  • API / Worker Image (Dockerfile): Built with tsdown into standalone dist/{server,worker,migrate}.js entrypoints for independent scaling:
    • Pre-deploy migrations: node apps/api/dist/migrate.js (never auto-migrated on server boot)
    • API server: APP_ROLE=api node apps/api/dist/server.js (or APP_ROLE=all for single-process deployment)
    • Background worker: docker build --target worker -t verluma-worker . builds the dedicated worker image. The HTTP health check applies to the API image.
  • Admin Image (apps/admin/Dockerfile): Nginx-hosted static SPA supporting --build-arg VITE_API_BASE_URL=... or same-origin /api/* reverse proxying.

Documentation

Optional external Agent Skills

Daily development relies on the bundled .agents/skills/; the following external skills can be added selectively when needed (see AI workflow for details):

  • Pre-release repository security audit (cloudflare/security-audit-skill): Keep daily PR reviews on the bundled adversarial-review. Before releases or after major changes to auth, Cedar policies, department data scopes, webhooks, or MCP/A2A endpoints, run Cloudflare's six-phase coverage-ledger and independent verifier pipeline inside an isolated sandbox, keeping generated audit artifacts out of the main branch.
  • Selective workflow helpers (mattpocock/skills): Avoid installing the full repo or running its setup script; pick individual skills in your personal global directory as needed:
    • grill-me / grill-with-docs: Interrogate edge cases, failure flows, and trade-offs down the design tree before starting a new domain or complex state machine.
    • handoff: Compress current state, decisions, pitfalls, and next steps into a structured handoff when spanning multiple sessions.
    • improve-codebase-architecture: Use occasionally as a read-only advisor to spot tight coupling or shallow modules while keeping refactors aligned with Verluma's FCIS boundaries and Rule of Three.

Contributing

Pushes and pull requests run secret scanning, static checks, environment and Redis regression tests, and DDL and authorization validation. A manual CI run or a v* tag runs the full suite, template checks, and production image builds.

Issues and Pull Requests are welcome. Before submitting a PR, please verify the full CI-equivalent gate locally:

pnpm check:ci

License

Verluma code is released under the MIT License. See the third-party notices for bundled materials, upstream licenses, and AI-generated image credits.

Explore related projects

Loading…