Skip to content
Deepcode007Public

About

Trello Kanban Board Clone Project

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

ย 

History

151 Commits

Folders and files

NameName
Last commit message
Last commit date
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐Ÿ“‹ Kanban Board (Trello Clone Monorepo)

A high-performance, real-time Kanban project management system built with Bun, Turborepo, TypeScript, Express 5, Prisma ORM, and PostgreSQL.

Designed for agile teams and organizations, this platform provides hierarchical workspace management, dynamic Kanban boards, customizable workflow columns, issue tracking with GitHub integration, nested threaded discussions, and a dedicated native WebSocket engine for real-time collaboration and presence tracking.


๐Ÿš€ Tech Stack

Domain Technologies
Runtime & Package Manager Bun (v1.3+ / v1.4+)
Monorepo Engine Turborepo (v2)
Language TypeScript (Strict typing across all workspaces)
Frontend Framework React 19 + Vite (High-performance SPA)
Frontend State & Cache TanStack Query v5, Zustand
Frontend Drag & Drop @dnd-kit (core + sortable)
Frontend UI & Styling Tailwind CSS, Radix UI Primitives, Lucide React
Backend Framework Express 5 on Bun runtime
Real-Time Engine Native Bun WebSockets (Multiplexed board & user topics, presence, app socket manager)
Database & ORM PostgreSQL with Prisma ORM (@prisma/adapter-pg)
Authentication & Security JWT (jsonwebtoken), bcrypt password hashing, Role-Based Access Control (RBAC)
Validation Zod schema validation for requests and environment configurations
Testing Bun Test runner (bun:test), Supertest, custom component, unit & live DB test suites (1,049 fast tests in ~2.1s, 1,288+ full suite tests)

โœจ Features

๐Ÿข Organization & Multi-Tenancy

  • Organization Workspaces: Create, edit, and manage multiple team workspaces with custom visibility settings.
  • Role-Based Access Control (RBAC): Support for admin, employee, and contributor roles with strict route and UI enforcement.
  • Invitation Lifecycle & Concurrency: Invite members with optional role parameter (admin, employee, contributor, defaults to contributor). Concurrency-safe mutations using PostgreSQL advisory locks (pg_advisory_xact_lock(hashtext(orgId))) without board outbox overhead. Ability for admins to revoke or cancel pending invitations (DELETE /api/orgs/:orgId/members).
  • Member Search Autocomplete: Search accepted organization members (GET /api/orgs/:orgId/members/search?q=...) for mention and assignment autocompletion.

๐Ÿ”” User-Targeted Notifications & Real-Time Alerts

  • Dedicated Notification Persistence: Stored in a separate notifications table (with read boolean state and composite indexes) isolated from board outbox events.
  • Rich Notification Types: Automatic alerts for org:invitation_received, org:invitation_accepted, org:role_changed, org:member_removed, mention:comment, comment:reply, and card:assigned.
  • Real-Time User Delivery: Notifications are dispatched over user-specific WebSocket topics (user_<userId>) via /internal/notify-users.
  • Notification REST API: Cursor-paginated notification feed (GET /api/notifications), unread count (GET /api/notifications/unread-count), single mark-as-read (PATCH /:notificationId/read), and mark-all-read (PATCH /read-all).
  • Interactive Notification UI: NotificationBell with live unread counter badge, NotificationDropdown, infinite-scroll NotificationList, NotificationItem, click-to-navigate card routing, and real-time desktop toast alerts.

๐Ÿ’ฌ Threaded Discussions & Mentions

  • Hierarchical Comment Tree: Infinite-depth nested replies powered by an optimized recursive tree algorithm (commentTree).
  • Rich @ Mention Autocomplete: MentionInput component triggers search dropdown on typing @, inserting canonical markup @[Display Name](user:userId).
  • Server-Side Mention Validation: validateMentions verifies mentioned users exist, belong to the organization, and have accepted memberships (filters self-mentions and pending members, capped at 20 per comment).
  • Mention Diffing & Pruning: Editing comments diffs mentions (creates notifications for newly added mentions, removes stale unread notifications for removed mentions). Deleting comments prunes unread mention notifications atomically.
  • Safe Mention Rendering: MentionDisplay component parses canonical markup into styled React tags safely without dangerouslySetInnerHTML.
  • Audit & Editing Policies: 24-hour edit/delete window enforcement for authors; admins can delete comments at any time. Soft-deletion re-parents child replies to maintain thread integrity.

๐Ÿ“Š Kanban Boards & Workflows

  • Dynamic Boards: Create, rename (PUT /api/boards/:boardId), and organize multiple boards per organization.
  • Customizable Sections (Columns): Build flexible workflow pipelines (e.g., Backlog, In Progress, In Review, Done).
  • Position Offsets & Auto-Spacing: Section and card positions automatically calculate based on maximum existing offsets (max(position) + 1000) to prevent position collisions.
  • Column Lifecycle & Reordering: Reorder, rename (PUT / PATCH), or safely delete sections. Column positions (position) are persisted to the database and indexed. Deleting a non-empty section requires specifying a targetSectionId on the same board to reassign issues; if a section is the only one remaining on the board and contains issues, deletion is blocked until issues are manually handled.

๐Ÿ“ Issue / Card Management

  • Rich Task Cards: Create issues with descriptions, metadata, priority levels (low, medium, high, urgent), start/due dates, and optional GitHub links (gh_url).
  • Flexible Movement: Move cards seamlessly across sections or reorder positions within a section (PATCH /api/cards/:id/move or /api/cards/:id).
  • RESTful Card Aliases: Full support for /api/cards/* routes alongside /api/issues/*.
  • Deduplicated Team Assignments: Assign and unassign single or multiple team members to any card (issue_mapping) with automatic recipient deduplication.
  • Labels & Checklists: Full support for board-scoped labels (/api/boards/:boardId/labels, card label attachments) and nested checklists with subtask items (/api/issues/:issueId/checklists).

๐Ÿ–ฅ๏ธ Modern React 19 Frontend SPA (apps/frontend)

  • Interactive Kanban Canvas: Fluid drag-and-drop powered by @dnd-kit with midpoint position calculations (dnd-math.ts) for cards and columns, elevated drag overlays, droppable empty column placeholders, and optimistic updates with automatic rollback on mutation failure.
  • Single Multiplexed App WebSocket: Centralized AppSocketManager singleton exposed via SocketProvider / SocketContext. Maintains a single long-lived WebSocket connection that multiplexes personal notifications (user_<userId> via subscribe_user) and board rooms (board_<boardId> via join), providing reconnect resilience with automatic resubscription.
  • Real-Time Board Synchronization: useBoardSocket registers with the shared app socket, collaborator presence displays active avatars, and synchronous in-memory event reducers update TanStack Query caches instantly for moves, edits, labels, checklists, and comments with zero full-page refetches.
  • Multi-Criteria Board Search & Filtering: Fast client-side filtering across text query (title/description), priority level, assignee (all, me, unassigned, or specific user), labels, and due date urgency. Displays active filter metrics and matching/total card ratios while keeping column WIP limit warnings calculated against total column cards so active filters never mask WIP limit violations.
  • Timezone-Safe Due Date Urgency System: Custom parser (parseDateParts) handles calendar-only dates and midnight UTC ISO strings without premature overdue alerts on the due date or negative-timezone day shifts. Dynamically renders urgency badges (overdue, due-today, due-soon, upcoming, and normal).
  • Theme & Dark Mode Engine: Persistent theme store (light, dark, system) with multi-tab storage synchronization, system preference change listeners, and an inline <head> script in index.html preventing flash of unstyled content (FOUC).
  • Responsive Mobile Layout: Mobile navigation hamburger drawer, collapsible mobile board filter drawer, responsive column widths (w-[82vw] sm:w-72), and smooth horizontal touch-scrolling canvas.
  • Safety & Modal Guardrails: Guarded column deletion requiring issue reassignment when cards exist, destination column selection stability against background query refetches, and rich card detail modal (checklists with completion ratios, label picker, mention-enabled threaded discussions).

โšก Real-Time Collaboration & Presence (WebSockets)

  • Native Multiplexed Pub/Sub Engine: Native Bun WebSocket server (Bun.serve) managing topic subscriptions for both board rooms (board_<boardId>) and personal user topics (user_<userId>) over a single client connection.
  • Ordered Event Sourcing & Advisory Locks: Outbox event recording (board_events) using PostgreSQL transaction-level advisory locks (pg_advisory_xact_lock) ensuring strictly sequential, non-colliding event numbering across concurrent workers.
  • Transactional Outbox & Worker Leases: Atomic DB mutations and event writes via executeWithOutbox. Resilient background outbox worker (claimedBy, claimExpiresAt leases) ensures safe, at-least-once event delivery across multiple backend instances without duplicate dispatch.
  • Catch-up Sync API: Clients query /api/boards/:boardId/events?sinceSeq=<sequence> to sync missing events after reconnecting.
  • Server-Side Heartbeat & Zombie Pruning: Recurring ping/pong health checks (default 30s) automatically detect inactive sockets, respond to client heartbeat pings/pongs, and terminate dead zombie connections with presence broadcast updates.
  • Live Event Broadcasting: Instant updates for card moves, creation, edits, deletions, checklist changes, labels, and column changes.
  • Presence Tracking & Targeted Eviction: Real-time user:joined and user:left events with automatic connection-drop cleanup and administrative user/session eviction hooks (/internal/evict-user).
  • In-Memory Membership Registry & Fast-Path Eviction: WebSocket server maintains an in-memory membership cache (userOrgMembership, boardOrgMap, userOrgRole, userBoardRole) for zero-latency join verification and fast-path multi-board/org socket eviction without repeated database lookups.
  • Internal HTTP IPC Interface: Backend communicates with WebSockets over authenticated HTTP bridge: /internal/broadcast, /internal/evict-user, /internal/notify-users, and /internal/update-role.
  • Flexible Authentication: Handshake-level JWT validation supporting headers, cookies, URL query parameters, and subprotocols.
  • Timing-Attack Resilient Auth: Login handler utilizes constant-time dummy bcrypt hashing to prevent user enumeration and timing attacks.

๐Ÿ—„๏ธ Database Optimization

  • Composite Indexing: Optimized indexes on [boardId, sectionId], [userId, orgId], [boardId, sequence], [recipientId, read, createdAt(sort: Desc)], [commentId, userId], and foreign key cascades.
  • Prisma Client Generation: Localized client generation with @prisma/adapter-pg driver adapter for native pooling performance.

๐Ÿ—๏ธ Repository Architecture

trello/
โ”œโ”€โ”€ apps/
โ”‚   โ”œโ”€โ”€ backend/               # Express 5 REST API server running on Bun
โ”‚   โ”‚   โ”œโ”€โ”€ src/
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ controllers/   # Auth, Org, Board, Section, Issue, Comment, & Notification handlers
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ helpers/       # Comment tree builder, mentions parser/validator, async wrappers, error classes
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ middlewares/   # JWT authentication & token generation
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ models/        # Zod schemas for input validation
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ routes/        # Express route definitions (cards, sections, notifications, orgs)
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ services/      # wsBroadcaster, Outbox Worker, & NotificationService
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ types/         # TypeScript environment and entity typings
โ”‚   โ”‚   โ””โ”€โ”€ tests/             # Unit (268 tests across 14 files) & live database integration test suites (507 total backend tests across 25 files)
โ”‚   โ”‚
โ”‚   โ”œโ”€โ”€ websockets/            # Native Bun WebSocket collaborative server (Port 3001)
โ”‚   โ”‚   โ”œโ”€โ”€ src/
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ auth/          # Handshake authentication & token extraction strategies
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ server.ts      # Bun.serve WebSocket server, upgrade handler, IPC endpoints, heartbeat
โ”‚   โ”‚   โ”‚   โ”œโ”€โ”€ services/      # wsBroadcaster singleton & in-memory membership/role cache
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ types/         # Client actions, server events, & payload interfaces
โ”‚   โ”‚   โ””โ”€โ”€ tests/             # WebSocket test suites (166 tests: 164 passing, 2 skipped across 9 files)
โ”‚   โ”‚
โ”‚   โ””โ”€โ”€ frontend/              # High-performance React 19 + Vite Kanban SPA
โ”‚       โ”œโ”€โ”€ src/
โ”‚       โ”‚   โ”œโ”€โ”€ components/    # Board canvas, columns, cards, filter bar, modals, notifications, mentions
โ”‚       โ”‚   โ”œโ”€โ”€ context/       # SocketContext & SocketProvider (app-level shared socket manager)
โ”‚       โ”‚   โ”œโ”€โ”€ hooks/         # useAppSocket, useBoardSocket, useNotificationQueries, useRole, query hooks
โ”‚       โ”‚   โ”œโ”€โ”€ lib/           # board-filters, date-urgency, dnd-math, kanban-api, org-api, notification-api
โ”‚       โ”‚   โ”œโ”€โ”€ pages/         # BoardCanvasPage, LoginPage, SignupPage
โ”‚       โ”‚   โ”œโ”€โ”€ store/         # useAuthStore, useBoardStore, useOrgStore, useThemeStore (Zustand)
โ”‚       โ”‚   โ””โ”€โ”€ tests/         # Unit, component, optimistic rollback, notifications, mentions (617 tests across 45 files)
โ”‚       โ””โ”€โ”€ index.html         # SPA entrypoint with FOUC prevention script
โ”‚
โ”œโ”€โ”€ packages/
โ”‚   โ”œโ”€โ”€ db/                    # Prisma schema, migrations, and PostgreSQL client
โ”‚   โ”‚   โ”œโ”€โ”€ prisma/            # schema.prisma (15 models including notifications & mentions)
โ”‚   โ”‚   โ”œโ”€โ”€ scripts/           # Database utilities (clearDB.ts with atomic TRUNCATE CASCADE)
โ”‚   โ”‚   โ””โ”€โ”€ db.ts              # Prisma client instance with @prisma/adapter-pg
โ”‚   โ”œโ”€โ”€ realtime/              # Shared real-time event definitions, types, and topic helpers
โ”‚   โ”‚   โ”œโ”€โ”€ src/
โ”‚   โ”‚   โ”‚   โ””โ”€โ”€ index.ts       # BroadcastEvent, payloads, formatBoardTopic, formatUserTopic, topic helpers
โ”‚   โ”‚   โ””โ”€โ”€ package.json
โ”‚   โ”œโ”€โ”€ ui/                    # Shared React component library
โ”‚   โ”œโ”€โ”€ eslint-config/         # Monorepo-wide ESLint configurations
โ”‚   โ””โ”€โ”€ typescript-config/     # Base and framework-specific tsconfig definitions
โ”‚
โ”œโ”€โ”€ package.json               # Workspace root configuration
โ”œโ”€โ”€ turbo.json                 # Turborepo task pipeline definition
โ””โ”€โ”€ bun.lock                   # Bun lockfile

๐Ÿ—„๏ธ Data Model

erDiagram
    user ||--o{ membership : "has"
    user ||--o{ issue_mapping : "assigned to"
    user ||--o{ comments : "writes"
    user ||--o{ notifications : "receives"
    user ||--o{ mentions : "mentioned in"

    orgs ||--o{ membership : "contains"
    orgs ||--o{ boards : "owns"

    boards ||--o{ sections : "contains"
    boards ||--o{ issues : "contains"
    boards ||--o{ labels : "has"
    boards ||--o{ board_events : "records"

    sections ||--o{ issues : "categorizes"

    issues ||--o{ issue_mapping : "assigned to"
    issues ||--o{ comments : "has"
    issues ||--o{ checklists : "has"
    issues ||--o{ issue_labels : "labeled with"

    labels ||--o{ issue_labels : "applied to"
    checklists ||--o{ checklist_items : "contains"

    comments ||--o{ comments : "replies to"
    comments ||--o{ mentions : "contains"

    user {
        string id PK
        string email UK
        string username
        string password
    }

    orgs {
        string id PK
        string name
        string description
        boolean visible
    }

    membership {
        string id PK
        Role role "admin | employee | contributor"
        boolean accepted
        string userId FK
        string orgId FK
    }

    boards {
        string id PK
        string title
        string description
        string color
        boolean isArchived
        string orgId FK
    }

    sections {
        string id PK
        string title
        float position
        int wipLimit
        boolean isArchived
        string boardId FK
    }

    issues {
        string id PK
        string title
        string description
        float position
        Priority priority "low | medium | high | urgent"
        datetime dueDate
        datetime startDate
        boolean isArchived
        string gh_url
        string boardId FK
        string sectionId FK
    }

    issue_mapping {
        string id PK
        string userId FK
        string issueId FK
    }

    comments {
        string id PK
        string description
        string issueId FK
        string userId FK
        string parentId FK
        datetime createdAt
        datetime deletedAt
    }

    labels {
        string id PK
        string name
        string color
        string boardId FK
    }

    issue_labels {
        string id PK
        string issueId FK
        string labelId FK
    }

    checklists {
        string id PK
        string title
        float position
        string issueId FK
    }

    checklist_items {
        string id PK
        string content
        boolean isCompleted
        float position
        datetime dueDate
        string checklistId FK
    }

    board_events {
        string id PK
        string boardId FK
        bigint sequence
        string eventType
        json payload
        boolean published
        datetime publishedAt
        string claimedBy
        datetime claimExpiresAt
        datetime createdAt
    }

    notifications {
        string id PK
        string recipientId FK
        string type
        json data
        boolean read
        datetime createdAt
    }

    mentions {
        string id PK
        string commentId FK
        string userId FK
        datetime createdAt
    }
Loading

๐ŸŒ Real-Time WebSocket Protocol

The WebSocket server provides real-time event distribution and presence tracking across board collaborators.

Connecting to WebSockets

  • Default URL: ws://localhost:3001
  • Authentication: JWT token must be provided through any of the following strategies:
    1. Query Parameter: ws://localhost:3001?token=<JWT> or ?access_token=<JWT>
    2. Authorization Header: Authorization: Bearer <JWT>
    3. Cookie: Cookie: token=<JWT> or auth_token=<JWT>
    4. Subprotocol: Sec-WebSocket-Protocol: bearer, <JWT>

Unauthenticated connections are rejected at the HTTP handshake stage with HTTP 401 Unauthorized.

Client-to-Server Actions

Send JSON frames over the WebSocket connection:

// 1. Join / Subscribe to a board room
{
  "action": "join", // or "subscribe"
  "boardId": "board-uuid"
}

// 2. Leave / Unsubscribe from a board room
{
  "action": "leave", // or "unsubscribe"
  "boardId": "board-uuid"
}

// 3. Heartbeat Ping / Pong
{
  "action": "ping" // or "heartbeat"
}
{
  "action": "pong" // or "heartbeat_ack"
}

// 4. Subscribe to Personal User Topic (for notifications)
{
  "action": "subscribe_user",
  "userId": "user-uuid"
}

Note

The client connects using a single shared AppSocketManager connection at the application root. Upon connection, it sends subscribe_user to listen for personal notifications on user_<userId>, and dynamically multiplexes board rooms (board_<boardId>) using join and leave without reconnecting. The WebSocket server automatically runs server-side heartbeat intervals (default 30s); inactive zombie connections are pruned and trigger user:left presence updates.

Server-to-Client Broadcast Events

When actions occur via REST API or other clients, events are published to board room topics (board_<boardId>) or personal user topics (user_<userId>):

Event Type Payload Fields Description
user:joined { userId, name, email, boardId } Collaborator entered the board
user:left { userId, name, email, boardId } Collaborator left or disconnected
board:member_evicted { userId, orgId, boardId } Member removed from organization
board:evicted { boardId, reason } Direct socket notification of eviction
card:created { cardData: Issue } New card added to a column
card:updated { cardId, updates: { ... } } Card metadata, title, or fields modified
card:moved { cardId, sourceList, destList, position } Card dragged across columns or reordered
card:deleted { cardId } Card removed from the board
card:label_attached { issueId, labelId, label } Label attached to card
card:label_removed { issueId, labelId } Label removed from card
checklist:created { checklist } Checklist added to card
checklist:deleted { checklistId, issueId } Checklist deleted
checklist_item:created { item } Item added to checklist
checklist_item:updated { item } Checklist item toggled or updated
comment:created { comment, issueId, boardId } New comment posted on card
comment:updated { comment, issueId, boardId } Comment edited
comment:deleted { commentId, issueId, boardId } Comment soft-deleted
list:created { listData: Section } New column added to the board
list:updated { listId, title, wipLimit?, isArchived? } Column renamed or updated
list:reordered { listId, newPosition } Column reordered
list:deleted { listId } Column deleted
user:notification { notification: NotificationRecord } Direct personal notification
user:org_board_created { board: Board } Dashboard real-time board creation
user:org_board_deleted { boardId, orgId } Dashboard real-time board deletion

HTTP Endpoints on WebSocket Server

  • GET /health or GET /api/health: Health status and port inspection.
  • POST /internal/broadcast: Inter-process broadcast hook used by Express backend to dispatch real-time events to connected board subscribers. Authenticated via x-internal-secret: <INTERNAL_BROADCAST_SECRET> (falls back to jwt_key).
  • POST /internal/evict-user: Inter-process user socket eviction endpoint used upon member removal or privilege revocation to close active connections or unsubscribe from revoked boards. Authenticated via x-internal-secret.
  • POST /internal/notify-users: Inter-process user notification delivery endpoint used by Express backend to publish direct notification and workspace events to user_<userId> topics. Authenticated via x-internal-secret.
  • POST /internal/update-role: Inter-process role update endpoint used to update in-memory membership and board role caches for instantaneous permission changes. Authenticated via x-internal-secret.

๐Ÿ“ก REST API Reference

All protected routes require a Bearer token in the Authorization header: Authorization: Bearer <jwt_token>

๐Ÿ” Authentication & Profile

Method Endpoint Description Access
POST /api/auth/signup Register a new user Public
POST /api/auth/login Authenticate user (timing-attack resistant) and receive JWT Public
GET /api/users/me Fetch authenticated user profile Authenticated

๐Ÿข Organizations & Memberships

Method Endpoint Description Access
GET /api/orgs List all organizations for current user Authenticated
POST /api/orgs Create a new organization Authenticated
GET /api/orgs/:orgId Get details of a specific organization Member
PUT /api/orgs/:orgId Update organization details Org Admin
DELETE /api/orgs/:orgId Delete organization Org Admin
GET /api/orgs/:orgId/members List members and their roles (Member only, 200 OK) Member
POST /api/orgs/:orgId/members Invite user by email with optional role (admin/employee/contributor) Org Admin
PUT /api/orgs/:orgId/accept Accept an organization invitation Invitee
PUT /api/orgs/:orgId/members Update a member's role Org Admin
DELETE /api/orgs/:orgId/members Remove user, leave org, or cancel/revoke pending invitations Member / Admin
GET /api/orgs/:orgId/members/search Search accepted org members (?q=&limit=) for mentions and assignments Member

๐Ÿ“‹ Boards & Event Sync

Method Endpoint Description Access
GET /api/orgs/:orgId/boards List all boards in an organization Member
POST /api/orgs/:orgId/boards Create a new board Member
GET /api/boards/:boardId Get board details with sections and issues Member
PUT /api/boards/:boardId Rename / update board details Member
DELETE /api/boards/:boardId Delete board and associated data Org Admin
GET /api/boards/:boardId/events
/api/boards/:id/events
Catch-up sync missed board events (?sinceSeq=&limit=) Member

๐Ÿ“‘ Sections (Columns)

Method Endpoint Description Access
GET /api/boards/:boardId/sections List sections for a board (sorted by position) Member
POST /api/boards/:boardId/sections Create a new section (list:created, auto-spaced position) Member
PUT / PATCH /api/sections/:sectionId Rename (title), set wipLimit, archive, or reorder (position / newPosition) Member
DELETE /api/sections/:sectionId Delete section; requires targetSectionId if section has issues (list:deleted) Org Admin

๐Ÿ“Œ Issues (Cards) & Assignments

Method Endpoint Description Access
GET /api/sections/:sectionId/issues
/api/sections/:sectionId/cards
List cards in a section Member
POST /api/sections/:sectionId/issues
/api/sections/:sectionId/cards
Create a card (card:created, auto-spaced position) Member
GET /api/issues/:issueId
/api/cards/:issueId / :id
Get full card details Member
PATCH /api/issues/:issueId
/api/cards/:issueId / :id
Update card title, priority, due date, start date, archive status, or move Member
PATCH /api/cards/:issueId/move
/api/cards/:id/move
Explicitly move card across sections or positions (card:moved) Member
DELETE /api/issues/:issueId
/api/cards/:issueId / :id
Delete card (card:deleted) Member
POST /api/issues/:issueId/assignees Assign users to card with email deduplication Member
DELETE /api/issues/:issueId/assignees Remove user assignment Member

๐Ÿท๏ธ Labels

Method Endpoint Description Access
POST /api/boards/:boardId/labels Create a new label on a board Member
GET /api/boards/:boardId/labels List all labels defined on a board Member
POST /api/issues/:issueId/labels Attach a label to an issue/card Member
DELETE /api/issues/:issueId/labels/:labelId Detach a label from an issue/card Member

โœ… Checklists & Subtasks

Method Endpoint Description Access
POST /api/issues/:issueId/checklists Create a checklist on a card Member
POST /api/checklists/:checklistId/items Add an item/subtask to a checklist Member
PATCH /api/checklists/items/:itemId Update checklist item content, completion, or due date Member
DELETE /api/checklists/:checklistId Delete an entire checklist Member

๐Ÿ’ฌ Threaded Comments

Method Endpoint Description Access
GET /api/issues/:issueId/comments Get nested comment tree for an issue Member
POST /api/issues/:issueId/comments Post comment/reply with optional @[Display Name](user:userId) mentions (creates & dispatches alerts) Member
PUT /api/comments/:commentId Edit comment (24h limit, diffs mentions, removes stale unread notifications, notifies new ones) Author
DELETE /api/comments/:commentId Soft-delete comment (24h for author, any time for admin; reparents replies and prunes unread notifications) Author / Admin

๐Ÿ”” Notifications

Method Endpoint Description Access
GET /api/notifications Fetch paginated notifications for current user (?cursor=&limit=) Authenticated
GET /api/notifications/unread-count Get total count of unread notifications ({ count }) Authenticated
PATCH /api/notifications/:notificationId/read Mark a single notification as read (returns 403 if not recipient) Recipient
PATCH /api/notifications/read-all Mark all notifications as read for current user Authenticated

๐Ÿ› ๏ธ Getting Started

Prerequisites

1. Clone & Install Dependencies

git clone <repository-url>
cd trello
bun install

2. Configure Environment Variables

Create .env configuration files:

packages/db/.env:

DATABASE_URL="postgresql://<user>:<password>@localhost:5432/<database_name>"

apps/backend/.env:

port="3000"
jwt_key="your-super-secret-jwt-key"
ws_port="3001"
WS_INTERNAL_URL="http://127.0.0.1:3001"
INTERNAL_BROADCAST_SECRET="your-internal-service-secret"

# Optional Outbox worker configuration
OUTBOX_RETRY_INTERVAL_MS="5000"
OUTBOX_LEASE_MS="30000"

apps/websockets/.env:

ws_port="3001"
jwt_key="your-super-secret-jwt-key"
INTERNAL_BROADCAST_SECRET="your-internal-service-secret"
WS_IDLE_TIMEOUT="60"
WS_HEARTBEAT_INTERVAL="30000"

Important

The jwt_key values must match for WebSocket JWT validation. Set the same INTERNAL_BROADCAST_SECRET in both apps for internal HTTP calls; when omitted, the JWT secret is used as a compatibility fallback. WS_INTERNAL_URL should point from backend to the WebSocket service.

3. Setup the Database

Generate Prisma Client and apply migrations:

# Apply migrations and generate Prisma client
bun run db:migrate # or: bun --filter db migrate:dev
bun run db:generate # or: bun --filter db generate

4. Run Development Servers

Start the two apps as separate processes. They can run on the same machine initially; backend sends broadcasts to the WebSocket service over HTTP.

For local development, from the repo root:

bun run dev --filter=backend
bun run dev --filter=websockets

Run each command in its own terminal. Configure both apps with matching jwt_key values. Set the same INTERNAL_BROADCAST_SECRET in both, and set the backendโ€™s WS_INTERNAL_URL to the WebSocket service address, for example http://127.0.0.1:3001. The internal secret can fall back to the JWT secret, but configuring it separately is preferable.

(Alternatively, you can start both services concurrently from the repo root with bun run dev)


๐Ÿ”„ How events flow

  1. A client makes a change through the backend API.
  2. The backend writes the change and its event to the database outbox.
  3. The backend publisher sends the event to WS_INTERNAL_URL/internal/broadcast.
  4. The WebSocket service publishes it to connected clients subscribed to that board.
  5. If delivery fails, the outbox leaves the event pending for retry.

This works whether the two processes are on the same machine or separate machines; the URL and network access are the difference.

๐Ÿ›ก๏ธ Outbox Delivery Resilience & Offline Fail-Safety

In production, network boundaries and service lifecycles can decouple:

  • Startup Race Conditions & Restarts: When backend containers boot before the WebSocket service, or during rolling updates and transient network partitions, the WebSocket HTTP bridge may be temporarily unreachable.
  • Graceful Fail-Safe Delivery: WebSocketBroadcaster.broadcast() catches connection and transport errors cleanly without throwing unhandled exceptions or crashing the backend process. Local in-process EventEmitter listeners still receive the broadcast (emitted = true), and the method returns false.
  • Transactional Outbox Coordination: The transactional outbox worker explicitly checks this false return value. Rather than dropping the event or assuming delivery, it retains the event in published: false status, allowing the background lease worker to reliably retry delivery via retryPendingEvents() once the WebSocket service is back online.
  • Port Override Precedence for Test & Multi-Instance Isolation: Calling broadcaster.setPort(port) explicitly sets customPort = true, guaranteeing that explicit port assignments take precedence over static env.WS_INTERNAL_URL defaults. This enables isolated automated testing against unused ports (e.g., verifying offline fail-safety without interference from local running dev servers) and supports custom multi-port internal routing.

๐Ÿ“ˆ Scaling

Initially: run one backend and one WebSocket process. They may share a machine, but the HTTP boundary stays the same.

More backend capacity: run multiple backend processes against the shared database. The outbox lease mechanism coordinates event delivery so workers can claim pending events safely. Ensure all backends use the same WebSocket URL and internal secret.

More WebSocket capacity: the current HTTP endpoint reaches one WebSocket service target. Before running multiple WebSocket replicas, add a broker such as Redis Pub/Sub so an event reaches every replica; otherwise clients connected to other replicas can miss updates. Keep the backend publishing through the same service boundary, then have the WebSocket instances consume the broker and publish to their own local clients.

One caveat: user eviction also currently uses the single WebSocket HTTP target, so with multiple WebSocket replicas that operation will need broker fan-out too.


๐Ÿงช Testing

The repository features comprehensive automated testing using Bun's native test runner (bun:test). The fast hermetic suite executes 1,049 tests in ~2.1 seconds across 68 files with zero external dependencies (with the full suite covering 1,288+ passing tests across 79 files):

# 1. Run the fast hermetic test suite (1,049 passed, 2 skipped, 0 failed across 68 files in ~2.1s)
bun test apps/websockets apps/frontend packages apps/backend/tests/unit

# 2. Run Frontend unit, component, optimistic rollback, & adversarial tests (617 tests across 45 files)
bun test apps/frontend

# 3. Run WebSocket unit and protocol tests (166 tests: 164 passed, 2 skipped across 9 files)
bun test apps/websockets

# 4. Run Backend unit tests (helpers, middleware, mentions, notifications, IPC) (268 tests across 14 files)
bun test apps/backend/tests/unit

# 5. Type check all monorepo packages (5 packages with zero errors)
bun x turbo run check-types --force

# 6. Run Full Backend integration tests (requires running PostgreSQL test database; 507 tests across 25 files)
RUN_DB_TESTS=1 bun test apps/backend/tests

Note

Database integration tests depend on packages/db/scripts/clearDB.ts (configured in turbo.json) to automatically truncate all 15 public schema tables before runs in the test database (trello_test).


๐Ÿ—บ๏ธ Roadmap

  • Monorepo orchestration with Turborepo & Bun
  • Relational schema design with Prisma & PostgreSQL
  • Authentication & Role-Based Access Control (RBAC) with timing-attack prevention
  • Multi-tenant organization & membership management with pending invitation revoking
  • Board and workflow section (column) management with auto-spaced positions
  • Issue lifecycle, movement across columns, and position reordering
  • RESTful Card and Section aliases (/api/cards/*, PATCH /move)
  • Multi-user card assignments (issue_mapping) with email deduplication
  • Card labels & checklist subtasks with position ordering
  • Threaded nested comment tree with edit time limits (200 OK responses)
  • Canonical @ mentions (@[Display Name](user:userId)) with server validation and mention diffing
  • Dedicated notifications table and real-time delivery over user topics (user_<userId>)
  • Notification UI (NotificationBell, NotificationDropdown, NotificationList, and toast alerts)
  • Native WebSocket server with multiplexed board (board_<boardId>) and user (user_<userId>) topics
  • Single app-level shared WebSocket connection (useAppSocket, SocketProvider) with automatic resubscriptions
  • Event sourcing with advisory locks (pg_advisory_xact_lock) and catch-up event sync
  • Transactional outbox pattern with worker leasing (claimedBy, claimExpiresAt) and guaranteed event publishing
  • Shared real-time event contract package (packages/realtime)
  • In-memory membership registry & fast-path join/eviction handling
  • Server-side heartbeat intervals and automatic zombie socket cleanup
  • Multi-strategy handshake authentication (Headers, Cookies, Query, Subprotocol)
  • Real-time presence tracking (user:joined, user:left) and targeted member eviction
  • Automatic WebSocket disconnect cleanup
  • Inter-process event synchronization (WebSocketBroadcaster with HTTP bridge)
  • React 19 frontend SPA with drag-and-drop Kanban board (dnd-kit), optimistic updates, and WebSocket synchronization
  • Multi-criteria board search, filter bar, and timezone-safe due date urgency system
  • Theme engine with dark mode, system preference detection, and FOUC prevention
  • Comprehensive test suites (1,049 fast hermetic tests across 68 files; 1,288+ full suite tests across 79 files)
  • GitHub webhook integration for automated card syncing
  • Card activity log and audit history
  • File attachments

About

Trello Kanban Board Clone Project

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages