Skip to content
Octet3290Public

About

A production-grade multi-tenant project management SaaS featuring interactive $O(1)$ fractional Kanban reordering, strict RBAC tenant isolation, and Redis Cache-Aside analytics. Built with Next.js 15, TypeScript, PostgreSQL, Prisma, and Docker.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

⚡ TeamSync — Multi-Tenant Project Management & Collaboration SaaS

A production-grade project management and team collaboration SaaS platform inspired by Linear and Jira. Built from first principles with Next.js 15 (App Router), TypeScript (Strict Mode), PostgreSQL (Neon Serverless), Prisma ORM, Redis, and Docker.

CI Pipeline Tests Next.js TypeScript PostgreSQL Prisma Docker License: MIT


📑 Table of Contents


🏗️ System Architecture

TeamSync operates on a zero-trust, multi-tenant architecture. Every inbound HTTP request traverses strict middleware validation, cryptographic JWT session decoding, sliding-window rate limiting, and row-level tenant context injection before any database mutation can occur.

flowchart TD
    Client["Client Browser (React 19 / Next.js)"]

    subgraph Security_Perimeter ["Security and Traffic Ingress"]
        MW["Next.js Middleware<br/>JWT Signature & Session Cookie"]
        RL["Sliding-Window Rate Limiter<br/>5 req/60s on Auth Routes"]
        TenantGuard["Tenant Context Injector<br/>Resolves active organizationId"]
    end

    subgraph Application_Core ["Application Layer (Next.js 15 Server Actions)"]
        RBAC["RBAC Policy Guard<br/>OWNER / ADMIN / MEMBER / VIEWER"]
        Actions["Server Actions & Mutations<br/>Zod Schema Validation"]
        CacheLayer{"Redis Cache-Aside Layer<br/>TTL 60s + In-Memory Fallback"}
    end

    subgraph Data_Perimeter ["Data Persistence and Isolation Layer"]
        Tx["Prisma Transaction Boundary"]
        DB[("Neon Serverless PostgreSQL<br/>Connection Pooling & Composite Indexing")]
    end

    Client -->|"Encrypted HTTPS"| MW
    MW --> RL
    RL --> TenantGuard
    TenantGuard --> RBAC
    RBAC --> Actions
    Actions -->|"Read Heavy / Analytics"| CacheLayer
    CacheLayer -->|"Cache Miss"| DB
    CacheLayer -->|"Cache Hit"| Client
    Actions -->|"Write Mutation"| Tx
    Tx -->|"Atomic Commit & Invalidation"| DB
    Tx -.->|"Evict Key Pattern"| CacheLayer
Loading

🗄️ Data Model & ER Diagram

All workspace entities enforce compound foreign key relationships referencing organizationId. This structural constraint guarantees that queries are physically partitioned by tenant at the database level.

erDiagram
    User ||--o{ OrganizationMember : "belongs to"
    Organization ||--o{ OrganizationMember : "has members"
    Organization ||--o{ Project : "owns"
    Organization ||--o{ Task : "scopes"
    Organization ||--o{ Notification : "contains"
    Organization ||--o{ ActivityLog : "records"
    Project ||--o{ Task : "groups"
    Task ||--o{ Task : "subtasks"
    Task ||--o{ Comment : "has comments"
    Task ||--o{ ActivityLog : "triggers"
    User ||--o{ Comment : "authors"
    User ||--o{ Notification : "receives"
    User ||--o{ Task : "assigned to"

    User {
        string id PK
        string email UK
        string passwordHash
        string name
        datetime createdAt
    }

    Organization {
        string id PK
        string name
        string slug UK
        datetime createdAt
    }

    OrganizationMember {
        string id PK
        string organizationId FK
        string userId FK
        string role
    }

    Project {
        string id PK
        string key
        string name
        string organizationId FK
    }

    Task {
        string id PK
        string title
        string status
        string priority
        float position
        string organizationId FK
        string projectId FK
        string parentTaskId FK
    }
Loading

🌟 Key Engineering Highlights

1. 🛡️ Multi-Tenant Isolation & Zero-Trust RBAC

  • Row-Level Partitioning: Every single Prisma query strictly bounds its where clause with organizationId. Cross-tenant data inspection via manipulated IDs is mathematically impossible at the database query level (defeating Insecure Direct Object Reference / IDOR).
  • Hierarchical Role Verification: Access control follows a strict OWNER > ADMIN > MEMBER > VIEWER precedence graph. Privileged operations (project creation, member invitation, role modification, workspace deletion) are verified on the server before transaction execution.
  • Orphan Protection: Workspaces cannot be orphaned. An owner must explicitly transfer ownership before self-removing or deleting an organization.

2. ⚡ Interactive Kanban Board & $O(1)$ Fractional Positioning

Traditional Kanban systems re-index all subsequent tasks upon a move, inducing an $O(N)$ write penalty and acquiring multiple row locks across the table. TeamSync solves this with $O(1)$ Fractional Positioning:

$$\text{position}_{\text{new}} = \frac{\text{position}_{\text{prev}} + \text{position}_{\text{next}}}{2}$$

Before Move:
[ Task A (pos: 1000.0) ]  ──────>  [ Task B (pos: 2000.0) ]

Inserting Task C between A and B:
[ Task A (1000.0) ]  ───>  [ Task C (1500.0) ]  ───>  [ Task B (2000.0) ]
Metric Traditional Array Re-indexing TeamSync Fractional Positioning
Write Time Complexity $O(N)$ (Updates every task in column) $O(1)$ (Updates single moved task)
Database Row Locks Locks all sibling rows in column Locks exactly 1 row
Network Payload Large batch array mutation Single mutation packet
Optimistic UI Recovery Complex full-list diff reconciliation Instant client snapshot rollback
  • Precision Protection & Rebalancing: When gap margins between adjacent items drop below $\Delta &lt; 10^{-6}$, an automated asynchronous rebalancing routine re-indexes the column with uniform $1000.0$ intervals.
  • Optimistic Rollback: The client UI instantaneously renders card transitions using @hello-pangea/dnd. If the server action rejects or network connectivity drops, the UI recovers the exact prior state without page reloads.

3. 🚀 Redis Cache-Aside & Dynamic Invalidation

  • Cache-Aside Pattern (cache.remember): High-load dashboard analytics queries are cached with a 60-second TTL, bypassing repeated complex SQL aggregations.
  • Tenant-Scoped Invalidation: Whenever tasks or projects are created, updated, reordered, or deleted, the mutation triggers targeted prefix invalidation (delPrefix("workspace:analytics:<orgId>")).
  • High Availability In-Memory Fallback: When an external Redis instance is unavailable, the caching layer transparently falls back to an in-process LRU cache with identical semantics, preventing service degradation.

4. ⏱️ Sliding-Window Rate Limiting

  • Brute-Force & Credential-Stuffing Mitigation: Critical endpoints (/login and /register) are fortified by a sliding-window rate limiter enforcing a strict limit of 5 requests per 60 seconds per IP.
  • Header Transparency: Responses automatically attach standard rate-limiting headers:
    • X-RateLimit-Limit: 5
    • X-RateLimit-Remaining: <count>
    • X-RateLimit-Reset: <timestamp>

5. 💬 Real-Time Collaboration & Atomic Transactions

  • Atomic Integrity (db.$transaction): Submitting comments, writing immutable audit records (ActivityLog), and alerting stakeholders are bound in a single atomic database transaction.
  • Smart Alert Deduplication: Evaluates task assignees, reporters, and commenters using JavaScript Set mechanics, automatically suppressing self-notifications when the author acts on their own task.

6. 📊 Executive Analytics & SQL Aggregations

  • Parallelized Aggregations (Promise.all): Computes completion rates, task velocity, priority breakdown matrices, and member workload allocations concurrently over connection pools.
  • Division-by-Zero Safeguards: Math guards prevent runtime NaN or PostgreSQL ERROR: 22012: division by zero exceptions when new workspaces have zero tasks.

7. 🐳 Multi-Stage Docker Standalone Distribution

  • Next.js Standalone File Tracing: Leveraging output: "standalone" in next.config.ts, Next.js bundles only the exact production files and imported node_modules dependencies needed at runtime.
  • 92% Footprint Reduction: Container image size drops from ~1.5 GB down to ~120 MB on Alpine Linux.
  • Non-Root Execution: Runs under a locked-down, unprivileged system user (nextjs:nodejs, UID 1001).
  • Health Probe Endpoint: Exposes a production /api/health endpoint measuring active database ping latency for Kubernetes, ECS, or Docker Swarm orchestrators.

👮 Role-Based Access Control (RBAC) Matrix

TeamSync enforces strict server-side authorization guards across every workspace resource:

Feature / Action OWNER ADMIN MEMBER VIEWER
Delete Workspace ✅ ❌ ❌ ❌
Transfer Ownership ✅ ❌ ❌ ❌
Manage Billing & Settings ✅ ✅ ❌ ❌
Invite / Remove Members ✅ ✅ ❌ ❌
Update Member Roles ✅ ✅ ❌ ❌
Create / Archive Projects ✅ ✅ ❌ ❌
Create / Assign Tasks ✅ ✅ ✅ ❌
Update Task Status / Drag & Drop ✅ ✅ ✅ ❌
Post Comments ✅ ✅ ✅ ❌
View Analytics & Kanban Board ✅ ✅ ✅ ✅

🛠️ Technology Stack

Domain Technology Purpose & Rationale
Framework Next.js 15+ (App Router) Hybrid SSR/SSG, Server Actions, Route Handlers, Streaming Suspense
Language TypeScript 5 (Strict Mode) Complete end-to-end type safety, strict null checking, zero any leaks
Database PostgreSQL (Neon Serverless) ACID transactions, composite indexing, connection pooling (pgbouncer)
ORM Prisma ORM 6 Schema migrations, typed queries, atomic transactions
Caching Redis (with Memory Fallback) Cache-Aside pattern, sliding-window rate limiting
Authentication bcryptjs & jose Salted password hashing (factor 10), cryptographically signed JWT cookies
Validation Zod Runtime schema parsing and input sanitization for actions and forms
Testing Vitest Fast in-memory unit, integration, and E2E simulation suites
UI Components React 19 & Tailwind CSS 4 Component isolation, sleek dark mode, glassmorphism, responsive grids
Drag & Drop @hello-pangea/dnd Accessible, buttery-smooth client-side Kanban drag-and-drop
CI/CD GitHub Actions Automated matrix testing across Node.js 20 and 22
Container Docker (Alpine Multi-Stage) Minimal standalone distribution (~120MB), non-root security

📁 Repository Structure

TeamSync/
├── .github/
│   └── workflows/
│       └── ci.yml               # GitHub Actions CI matrix pipeline (Node 20 & 22)
├── prisma/
│   ├── schema.prisma            # Relational schema with composite indexes & enums
│   ├── migrations/              # Immutable SQL migration track
│   └── seed.ts                  # Idempotent demo data seeder
├── src/
│   ├── app/                     # Next.js 15 App Router architecture
│   │   ├── (auth)/              # Public authentication routes (login, register)
│   │   ├── (dashboard)/         # Protected workspace application routes
│   │   │   ├── dashboard/       # High-performance analytics dashboard
│   │   │   ├── projects/        # Project index & dynamic [id] Kanban board
│   │   │   └── settings/        # Workspace member management & RBAC controls
│   │   ├── api/
│   │   │   └── health/          # Orchestration live health probe endpoint
│   │   ├── layout.tsx           # Root HTML layout with font optimization
│   │   └── page.tsx             # Marketing landing page & gateway
│   ├── components/              # Modular React 19 UI components
│   │   ├── kanban/              # Kanban board, columns, and draggable cards
│   │   ├── tasks/               # Task detail slide-over drawer, creation modals
│   │   └── ui/                  # Design primitives (buttons, badges, inputs)
│   ├── lib/                     # Core system utilities & singletons
│   │   ├── auth.ts              # JWT signing, cookie management, session decoding
│   │   ├── cache.ts             # Cache-Aside pattern with Redis & in-memory fallback
│   │   └── rate-limit.ts        # Sliding-window rate limiter implementation
│   ├── server/                  # Server Actions & persistence layer
│   │   ├── actions/             # Business logic (auth, projects, tasks, analytics)
│   │   └── db.ts                # PrismaClient singleton with connection pooling
│   └── middleware.ts            # Route protection, JWT validation, security guards
├── tests/                       # 62 Vitest automated test suites
│   ├── analytics.test.ts        # Parallel SQL aggregation math & division guards
│   ├── auth.test.ts             # Cryptographic password hashing & JWT verification
│   ├── collaboration.test.ts    # Comments, activity audit logs & notifications
│   ├── e2e-workflow.test.ts     # Multi-phase end-to-end lifecycle verification
│   ├── kanban.test.ts           # Fractional positioning math & precision limits
│   ├── projects-tasks.test.ts   # CRUD operations, composite key uniqueness
│   ├── redis-ratelimit.test.ts  # Cache TTLs, invalidation & sliding-window thresholds
│   └── tenant-isolation.test.ts # Row-level cross-tenant security & IDOR defense
├── Dockerfile                   # Multi-stage standalone Alpine container build
├── next.config.ts               # Standalone output mode & enterprise HTTP headers
├── tsconfig.json                # TypeScript strict mode configuration
└── package.json                 # Dependency manifests & npm scripts

🚦 Getting Started Locally

Prerequisites

  • Node.js: >= 20.x
  • npm: >= 10.x
  • PostgreSQL: A running instance (e.g., Neon Serverless, Supabase, or local Docker)

1. Clone the Repository

git clone https://github.com/Octet3290/TeamSync.git
cd TeamSync

2. Install Dependencies

npm install

3. Configure Environment Variables

Create a .env file in the project root:

cp .env.example .env
Variable Required Description Example
DATABASE_URL Yes PostgreSQL connection string postgresql://user:pass@ep-host.neon.tech/neondb?sslmode=require
SESSION_SECRET Yes 32+ character random secret for signing JWTs a-cryptographically-secure-random-32-byte-secret-key
REDIS_URL No Redis connection URL (falls back to memory if omitted) redis://default:password@host:6379
NODE_ENV No Execution environment development or production

4. Initialize Database & Seed Starter Data

# Push database schema migrations
npx prisma migrate dev

# Seed demo users, organizations, and initial backlog tasks
npm run db:seed

5. Launch the Development Server

npm run dev

Open http://localhost:3000 in your browser.

Demo Credentials:

  • Email: demo@teamsync.io
  • Password: Password123!

🧪 Automated Testing Suite

TeamSync maintains a 100% test pass rate with 62 automated tests across 8 suites verifying every critical security, data integrity, and algorithmic constraint:

# Execute complete test suite
npm run test

# Run tests in watch mode
npx vitest
 ✓ tests/kanban.test.ts (6 tests)
 ✓ tests/redis-ratelimit.test.ts (9 tests)
 ✓ tests/collaboration.test.ts (11 tests)
 ✓ tests/tenant-isolation.test.ts (6 tests)
 ✓ tests/analytics.test.ts (5 tests)
 ✓ tests/projects-tasks.test.ts (10 tests)
 ✓ tests/e2e-workflow.test.ts (7 tests)
 ✓ tests/auth.test.ts (8 tests)

 Test Files  8 passed (8)
      Tests  62 passed (62)
   Duration  4.12s

Test Coverage Highlights

  • Auth & Cryptography: Tests password salt generation, constant-time verification, and tamper detection in JWT cookies.
  • Tenant Isolation: Verifies that requests with foreign organizationId values return 404/403 and never mutate or leak records.
  • Fractional Positioning: Validates midpoint calculations, top-of-column insertions, bottom-of-column appends, and rebalance triggers.
  • Collaboration & Audit Trail: Confirms comment creation automatically writes an activity log and dispatches deduplicated alerts.
  • Analytics Precision: Tests SQL aggregation math against edge cases, including empty workspaces with zero tasks.
  • E2E Simulation: Executes a full lifecycle flow: registration ➔ organization creation ➔ project initialization ➔ task movement ➔ comment ➔ completion.

🐳 Docker Deployment

The repository includes a production-hardened multi-stage Dockerfile utilizing Alpine Linux and Next.js standalone file tracing.

# Build the minimal multi-stage image (~120MB)
docker build -t teamsync:latest .

# Run the container
docker run -d \
  -p 3000:3000 \
  -e DATABASE_URL="postgresql://user:pass@host/db?sslmode=require" \
  -e SESSION_SECRET="your-32-character-session-secret" \
  --name teamsync-app \
  teamsync:latest

Container Health Check Probe

Container orchestrators (Kubernetes, AWS ECS) can monitor service health via:

curl -I http://localhost:3000/api/health

Response Payload (200 OK):

{
  "status": "healthy",
  "timestamp": "2026-10-22T07:12:00.000Z",
  "database": {
    "status": "connected",
    "latencyMs": 14
  },
  "uptime": 3600
}

🔒 Security Hardening & Enterprise Headers

  • Cryptographic Password Hashing: Passwords are salted and hashed via bcryptjs with salt work factor 10.
  • Constant-Time Verification: Password comparison uses constant-time string algorithms to prevent timing side-channel attacks.
  • Signed Stateless Sessions: JWT sessions are signed with HMAC-SHA256 (jose) and transmitted exclusively inside httpOnly, sameSite: "lax", and secure: true cookies.
  • Enterprise HTTP Security Headers configured in next.config.ts:
    • X-Frame-Options: DENY — Prevents iframe clickjacking attacks.
    • X-Content-Type-Options: nosniff — Prevents MIME-type sniffing.
    • Strict-Transport-Security: max-age=63072000; includeSubDomains; preload — Enforces 2-year HTTPS preload.
    • Referrer-Policy: origin-when-cross-origin — Protects internal URI parameters from leaking.
    • Permissions-Policy: camera=(), microphone=(), geolocation=() — Blocks unwanted device APIs.

💡 Technical Architecture FAQ (Interview Defense)

Q: Why use fractional positioning instead of an integer array index?

Answer: In a high-concurrency Kanban board, dragging a task from position 50 to position 1 using an integer indexing approach requires executing UPDATE tasks SET position = position + 1 WHERE position >= 1 AND position < 50. This issues an $O(N)$ database write, locks up to 50 rows in the database, and introduces write contention and transaction deadlocks. Fractional positioning computes $pos = (prev + next) / 2$, which is an $O(1)$ single-row update acquiring zero sibling locks.

Q: What happens when floating-point precision underflows in fractional indexing?

Answer: JavaScript numbers use IEEE 754 double-precision floats, providing 53 bits of precision (~15-17 significant decimal digits). You would need over 50 consecutive insertions between the same two items without reordering before reaching precision limits. TeamSync implements a proactive guard: when $\Delta pos &lt; 10^{-6}$, an asynchronous background routine rebalances the column with clean $1000.0$ step intervals.

Q: How do you guarantee tenant isolation without relying solely on application-level developer discipline?

Answer: We enforce compound unique constraints and compound foreign keys at the database schema level (@@unique([organizationId, key])). Every data-layer function accesses tables through wrapper queries that mandate organizationId as a parameter. An attacker guessing a valid UUID for a project or task cannot read or modify it without possessing an active membership session within that specific organizationId.

Q: Why did you choose Cache-Aside over Write-Through caching?

Answer: Analytics queries are read-heavy but expensive to compute (multi-table aggregations, workload calculations). With Cache-Aside, we cache on demand (cache.remember), ensuring we never compute cache keys that are never read. When task mutations occur, we issue a lightweight key deletion (delPrefix), ensuring zero stale-data anomalies while keeping mutation latency minimal.


📄 License

Distributed under the MIT License. See LICENSE for details.

About

A production-grade multi-tenant project management SaaS featuring interactive $O(1)$ fractional Kanban reordering, strict RBAC tenant isolation, and Redis Cache-Aside analytics. Built with Next.js 15, TypeScript, PostgreSQL, Prisma, and Docker.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages