7.3 KiB
Phase 1 Deliverables - RayLab Core
Contents
- Architecture explanation
- Folder structure
- Source code references (what was added/changed)
- Database schema (Prisma)
- Migration (SQL)
- Seed data (script)
- API design (initial endpoints)
- Design decisions
- Advantages
- Possible future extensions
- How to run (migrate & seed)
- Architecture explanation
Phase 1 establishes the foundational data model and project layout for RayLab Core. It prepares the system for secure integration with Authentik (OIDC) and supports role/permission based authorization owned by RayLab Core. The design follows Clean Architecture, SOLID principles, modular NestJS structure, and Prisma for type-safe DB access.
Key principles applied:
- RayLab Core does NOT implement authentication; it only validates external OIDC tokens (Phase 2).
- Roles, permissions, role mappings, users, and audit logs are owned by RayLab Core. Media Manager and Scheduler are intentionally excluded from Phase 1 and will be implemented in Phase 3.
- No Group entity is created in RayLab Core; only mapping configuration (auth group name string -> role) is stored.
- Critical operations (synchronization) will be transactional (Phase 2 implementation).
- Folder structure
(Only top-level relevant directories shown)
-
prisma/
- schema.prisma // Prisma schema (source of truth for DB)
- migrations/0001_init/ // Initial SQL migration
- seed.ts // Seed script (idempotent upserts)
-
src/
- main.ts
- app.module.ts
- modules/
- identity/ // DDD-based users/roles/permissions implementation
- auth/ // (Phase 2) OIDC integration
- authorization/ // (Phase 2) permission guards & services
- health/ // basic health endpoint (added)
- media/ // media manager module (phase 3)
- audit/ // audit module (phase 3)
- ... other domain modules
- shared/
- prisma.service.ts
- ...
- Source code (what was added/changed)
-
prisma/schema.prisma (UPDATED): replaced with production-ready schema containing: User, Role, Permission, RolePermission, UserRole, AuthGroupRoleMapping, AuditLog
-
prisma/migrations/0001_init/migration.sql (ADDED): initial SQL migration DDL
-
prisma/seed.ts (UPDATED): seed script that creates default roles, permissions, role-permission assignments, and Authentik group -> role mappings
-
src/modules/health/* (ADDED): HealthModule, Controller, Service (thin controller)
-
src/shared/prisma.service.ts (EXISTING): PrismaService (already present)
- Database schema
The Prisma schema (prisma/schema.prisma) is the authoritative schema. High-level model summary:
- User: id (uuid), externalId (unique), email, name, picture, metadata, createdAt, updatedAt
- Role: id, name (unique), displayName, description
- Permission: id, name (unique), description
- RolePermission: join table role <-> permission (unique constraint roleId+permissionId)
- UserRole: join table user <-> role with source (e.g., 'authentik') and syncedAt timestamp (unique userId+roleId)
- AuthGroupRoleMapping: mapping table authGroup (string) -> roleId. One authGroup may map to multiple roles (no uniqueness enforced on authGroup).
- AuditLog: append-only audit logs with JSON details
Indexes and constraints are included for common lookup paths. The migration SQL contains explicit DDL statements.
- Migration
- prisma/migrations/0001_init/migration.sql contains the SQL to create the schema.
- The migration file includes CREATE EXTENSION IF NOT EXISTS "pgcrypto" to provide gen_random_uuid().
- Recommended migration procedure in production:
- Ensure backups and schedule maintenance window for initial deployment.
- Run migrations with Prisma or psql: "psql < migration.sql" or use "prisma migrate deploy" after generating migrations from schema.prisma.
- Seed data
- prisma/seed.ts seeds the following:
- Default roles: Owner, Employee, Family
- Default permissions following resource.action naming convention (users.create, users.read, ..., scheduler.manage)
- RolePermission assignments:
- Owner receives all permissions
- Employee and Family receive reasonable subsets (editable later)
- Authentik group mappings:
- RL-Owner -> Owner
- RL-Employee -> Employee
- RL-Family -> Family
The seed script is idempotent using upsert operations.
- API design (initial)
Phase 1 provides a minimal, safe public surface to verify system health and readiness.
- GET /api/health
- Returns: { status: 'ok', timestamp, service }
Identity module controllers (users, roles, permissions) are present under src/modules/identity/presentation/controllers and follow RESTful conventions, but full auth/guards are implemented in Phase 2.
- Design decisions
- Prisma selected for type-safe DB access and migrations. (User requested Prisma)
- UUID primary keys (Postgres gen_random_uuid()) for scalability and horizontal distribution.
- JSONB (Prisma Json) used for flexible metadata and audit details.
- AuthGroupRoleMapping stores external group string only; RayLab Core does NOT model Groups as domain entities.
- Seed sets conservative permission assignments; owners get full permissions.
- Minimal initial API surface (health) avoids unintentionally exposing functionality before auth & guards are in place.
- Advantages
- Production-ready DB schema with indices and constraints for performance and data integrity.
- Modular NestJS structure aligned with Clean Architecture / DDD; easy to extend in subsequent phases.
- Prisma provides type-safety and reduces runtime errors.
- Seed script allows reproducible environments and CI setup.
- Audit and media tables are present to support required domain features.
- Possible future extensions
Planned for Phase 2 and 3 (once Phase 1 is approved):
- OIDC validation using openid-client and configuration from env vars
- Role synchronization flow (validate token -> read groups -> map -> compute hash -> replace UserRole in transaction -> invalidate permission cache -> write audit)
- Permission cache using Redis, invalidation hooks
- Auth guards and AuthorizationService for permission checks
- Media Manager: presigned URLs, storage backend (S3/MinIO)
- Scheduler: BullMQ integration with Redis
- Monitoring: Prometheus metrics, structured logging, Sentry
- How to run (migrate & seed)
Prerequisites:
- Node 20+
- PostgreSQL reachable via DATABASE_URL env var
- Install dependencies: npm ci
Generate Prisma client and run migration:
-
Generate Prisma client: npm run prisma:generate
-
Apply migration (development): npm run prisma:migrate
Or run SQL directly against the database: psql "$DATABASE_URL" -f prisma/migrations/0001_init/migration.sql
-
Run seed script: npm run prisma:seed
-
Start the app (development): npm run start:dev
Next steps
Please review Phase 1 deliverables. After your approval I will implement Phase 2 (OIDC module, Authentik integration, Group->Role Sync, Authorization Guard, Permission Cache, Audit logging) following the same level of production-quality implementation.