Skip to content
krishangoyal12Public

About

A webapp that takes your writing process to next level by enabling you to collaborate with people with AI support as well

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

ย 

History

54 Commits

Folders and files

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

Repository files navigation

CoWrite โœ๏ธ๐Ÿš€

CoWrite is a real-time collaborative document editor built to enhance team productivity with seamless editing, live cursors, threaded comments, AI-powered writing assistance, Notion-style slash commands, interactive document copilot, and secure document sharing.


๐Ÿ”ฅ Features

โœ๏ธ Rich Text & Modern Block Editing

  • Full rich text editor powered by TipTap (ProseMirror)
  • Bold, Italic, Underline, Strikethrough, Code Blocks, Blockquotes, Horizontal Dividers
  • Headings (H1โ€“H6), font size & family selectors
  • Text alignment (Left, Center, Right, Justify)
  • Custom text color & color picker palette
  • Undo / Redo history management

โšก Notion-Style Slash Commands (/)

  • Type / anywhere to summon a floating command palette with keyboard navigation (โ†‘/โ†“ and Enter)
  • Instant commands: Heading 1โ€“3, Bullet List, Numbered List, Blockquote, Code Block, Divider, and AI actions
  • Customizable Order with Drag-and-Drop (โ‹ฎโ‹ฎ): Reorder slash commands to match your personal workflow. Custom orders are persisted across sessions in localStorage.

๐Ÿค– VS Code Copilot-Style "Doc Copilot" Side Panel

  • Dedicated collapsible AI assistant panel docked on the right side of the screen
  • Draggable gutter handle: Resize the sidebar dynamically with responsive layout adaptations
  • Multi-line expandable query bar: Auto-growing prompt input with Enter (submit) and Shift+Enter (new line)
  • Instant Query Pills: One-click execution for common questions (Summary, Key Points, Critique & Improvements)
  • Smart Contextual Actions:
    • Insert into doc: Appends formatted AI responses directly into the document.
    • Apply corrections to doc: For critiques or improvement suggestions, CoWrite extracts and applies only the required corrections directly to the text rather than pasting meta-commentary.

๐Ÿ‘ฅ Unified Top Navigation & Team Collaboration

  • Unified Single Bar UX: Clean, distraction-free header following Google Docs / Notion / Figma patterns
  • Live User Presence: Colored avatars showing active collaborators viewing or editing with live hover tooltips
  • Sleek Share Modal: Integrated "Share" button opening an invite popover to invite teammates by email and manage current member roles (Owner vs Editor)
  • Multi-user simultaneous editing powered by Yjs + WebSocket
  • Named live cursors โ€” each collaborator's cursor displays their name with smooth animation and automatic inactivity fading

๐Ÿ’ฌ Google Docs-Style Comments

  • Select any text and add a comment from the floating formatting bubble menu
  • Aligned comment threads in the right margin
  • Multi-reply threading
  • Immediate resolve with a โœ“ tick โ€” highlight is cleared instantly without page refresh
  • Shortcuts: Enter to post, Shift+Enter for a newline

๐Ÿง  In-Document AI Writing Tools (Groq / Gemini)

  • Summarize Document
  • Bullet Point Summary
  • Improve Writing & Professional Tone
  • Grammar & Spelling Check
  • Format Document
  • Custom AI Prompt Execution
  • Visual diff highlights (green additions / red deletions) with an Accept / Reject review bubble

๐Ÿ“ Document Dashboard

  • Create, rename, and manage personal and shared documents
  • Smart deletion modals:
    • Owner: Warns that collaborators will lose access
    • Collaborator: Allows leaving the document without deleting the owner's copy

๐Ÿ“ค Export & Sharing

  • Download as PDF: Client-side styled PDF generation via html2pdf.js
  • Public View Link: Document owners can enable a read-only, sanitized public link for viewers without requiring authentication

๐Ÿ” Security & Auth

  • JWT-based authentication with HttpOnly cookies and query parameter tokens for WebSockets
  • Google OAuth login & signup
  • Protected REST API endpoints with role-based access control
  • WebSocket Upgrade Verification: Handshake verification rejecting unauthenticated (401) or unauthorized (403) connection attempts
  • Role-Based WebSocket Write Blocking: Real-time write interception preventing viewers from applying unauthorized document mutations

๐Ÿ” WebSocket Security: Authentication vs. Authorization

1. What is Authentication?

Authentication is the process of verifying a user's identityโ€”verifying who they are.

  • In CoWrite: When a user registers or logs in via /api/auth/login (or Google OAuth), CoWrite verifies their credentials and issues a cryptographically signed JSON Web Token (JWT) containing their user ID ({ id: user._id }).
  • Where it happens in CoWrite:
    • REST API: Handled in Server/Middlewares/authMiddleware.js. Every protected HTTP request passes through verifyToken, which extracts the token from cookies (req.cookies.token) or authorization headers (Authorization: Bearer <token>) and verifies it using jwt.verify(token, process.env.JWT_SECRET).
    • WebSocket Server: Handled during the HTTP upgrade / handshake in Server/Config/yjs.js. Before establishing the WebSocket connection, the server extracts the JWT from the connection query parameters (?token=...), headers, or cookies and verifies it via jwt.verify. If no token is provided or the token is invalid/expired, the handshake is immediately aborted with HTTP/1.1 401 Unauthorized.

2. What is Authorization?

Authorization is the process of determining what permissions an authenticated user possesses on a specific resourceโ€”verifying what they are allowed to do.

  • In CoWrite: Once a user's identity is authenticated, CoWrite determines their role for a target document:
    • Owner (doc.owner === user.id): Full permissions to read, write, share, invite/remove collaborators, and delete the document.
    • Editor (user.id in doc.collaborators): Permissions to join the room, read document content, and write real-time edits.
    • Viewer (user.id in doc.viewers or document isPublic: true): Permission to join the room and read document content in real time, but strictly blocked from writing.
    • Unauthorized / No Access: If an authenticated user is not an owner, editor, or viewer and the document is private, their connection attempt is rejected.
  • Where it happens in CoWrite:
    • REST API: In Server/Controllers/documentControllers.js. For example, only the document owner can delete the document or add/remove collaborators, while editors and owners can view or update.
    • WebSocket Upgrade Handshake: In Server/Config/yjs.js during server.on('upgrade'). The server queries the document from the database and resolves the user's role with getUserDocumentRole(doc, userId). If the user does not possess any role for that document, the handshake is rejected with HTTP/1.1 403 Forbidden.
    • WebSocket Message Sync (Write Protection): In Server/Config/yjs.js inside setupSecureWSConnection. When incoming binary Yjs synchronization messages arrive (messageYjsSyncStep2 or messageYjsUpdate), the server checks conn.userRole. If the user holds the viewer role, any write attempt is blocked: the server skips applying the update to the shared Y.Doc, suppresses broadcast to collaborators, and returns a permission-denied auth frame.

๐Ÿงช Running the WebSocket Security Tests

The automated test suite verifies:

  1. No token (rejected): Connection without a token fails during handshake with HTTP 401 Unauthorized.
  2. Valid token for unauthorized document (rejected): Valid JWT for a user with no document access fails during handshake with HTTP 403 Forbidden.
  3. Viewer trying to write (blocked): Viewer successfully connects and reads, but write operations (SyncStep2 / Update) are intercepted and blocked without altering the server document.
  4. Contrast verification: Document owners/editors can successfully write updates.

Test Command

Run from the repository root:

npm test

Or from the Server/ directory:

cd Server
npm test

๐Ÿ› ๏ธ Tech Stack

Layer Technology
Frontend React, TipTap (ProseMirror), Vite, TailwindCSS
Backend Node.js, Express, MongoDB (Mongoose)
Collaboration Yjs + y-websocket + y-mongodb-provider
AI Groq API / Google Gemini
Auth JWT + HttpOnly Cookies, Google OAuth
PDF Export html2pdf.js

๐Ÿ“ Project Structure

CoWrite/
โ”œโ”€โ”€ Client/                      # React frontend (Vite + TailwindCSS)
โ”‚   โ””โ”€โ”€ src/
โ”‚       โ”œโ”€โ”€ Pages/               # Editor, Dashboard, Login, Signup, PublicEditor
โ”‚       โ”œโ”€โ”€ Components/          # AskDocSidebar, SlashCommandList, AIPreviewBubble, CommentPanel, ...
โ”‚       โ”œโ”€โ”€ Extensions/          # SlashCommands, SmoothCursor, EditorShortcuts, CommentExtension, ...
โ”‚       โ””โ”€โ”€ Context/             # AuthContext
โ”œโ”€โ”€ Server/                      # Express REST API & Yjs WebSocket server
โ”‚   โ”œโ”€โ”€ Controllers/             # Document, Auth & AI controllers
โ”‚   โ”œโ”€โ”€ Models/                  # Mongoose schemas (User, Document)
โ”‚   โ”œโ”€โ”€ Routes/                  # Express routes
โ”‚   โ”œโ”€โ”€ Middlewares/             # JWT auth middleware
โ”‚   โ””โ”€โ”€ Config/                  # Yjs & database configuration
โ””โ”€โ”€ yjs-server/                  # Dedicated Yjs WebSocket server instance

๐Ÿš€ Local Setup

Prerequisites

  • Node.js โ‰ฅ 18
  • MongoDB Atlas URI (or local MongoDB)

1. Clone the repository

git clone https://github.com/your-username/CoWrite.git
cd CoWrite

2. Backend Setup

cd Server
npm install
npm start

Create Server/.env:

DB_URI=your_mongodb_uri
JWT_SECRET=your_jwt_secret
FRONTEND_URL=http://localhost:5173
PORT=3000
GROQ_API_KEY=your_groq_api_key

3. Frontend Setup

cd ../Client
npm install
npm run dev

Create Client/.env:

VITE_URL=http://localhost:3000
VITE_WEBSOCKET_URL=ws://localhost:3000
VITE_GOOGLE_CLIENT_ID=your_google_client_id

4. Running Locally

# Terminal 1 - Backend (REST API + Yjs WebSocket)
cd Server && npm start

# Terminal 2 - Frontend
cd Client && npm run dev

๐Ÿ“Œ API Endpoints

Auth

Method Route Description
POST /api/auth/signup Register new account
POST /api/auth/login Email/password login
POST /api/auth/google-signup Google OAuth authentication
GET /api/auth/me Fetch active session

Documents

Method Route Auth Description
GET /api/documents โœ… List user's documents
POST /api/documents โœ… Create new document
GET /api/documents/:id โœ… Get document details
PUT /api/documents/:id โœ… Update title, content, or visibility
DELETE /api/documents/:id โœ… Owner Delete document
DELETE /api/documents/:id/leave โœ… Collab Leave shared document
POST /api/documents/:id/collaborators โœ… Owner Add collaborator by email
GET /api/documents/public/:id โŒ Read-only public preview

AI

Method Route Auth Description
POST /api/ai/transform โœ… Execute writing transformation / critique / corrections
POST /api/ai/ask โœ… Ask document assistant queries

๐Ÿ“ How to Use

Action How
Slash Commands Type / on any line to open the command palette (โ†‘/โ†“ to navigate, drag โ‹ฎโ‹ฎ to reorder)
Doc Copilot Click Doc Copilot in the top bar to open the resizable AI assistant sidebar
Share Document Click Share in the top bar to invite teammates or manage access
Comments Select text โ†’ click ๐Ÿ’ฌ in bubble menu โ†’ write & post
AI In-line Fixes Highlight text โ†’ select an AI action โ†’ review diff highlights โ†’ Accept/Reject
Export as PDF Click Export in the top bar โ†’ "Download as PDF"
Public Link Click Export โ†’ toggle "Public View Link" โ†’ copy URL

๐ŸŒ Live Deployment

Service URL
Frontend https://krishan-cowrite.netlify.app
Backend https://cowrite-x48q.onrender.com

๐Ÿค Contributing

Contributions, feedback, and feature requests are welcome! Feel free to fork the repository and open a pull request. โญ

About

A webapp that takes your writing process to next level by enabling you to collaborate with people with AI support as well

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages