Skip to main content

Built-in Documentation Editor - Setup Guide

This guide explains how to set up and use the built-in documentation editor for HyperSpin-Docs.

Overview

The built-in editor allows authenticated users to edit documentation files directly from the browser, with changes automatically committed to GitHub. The editor features:

  • Full markdown editing with live preview
  • Syntax highlighting and formatting tools
  • Direct GitHub integration - changes are committed automatically
  • HyperList authentication - uses your existing authentication system
  • Conflict detection - prevents overwriting concurrent changes
  • Author attribution - commits are attributed to the editing user

Architecture

The system consists of three components:

  1. Frontend Components (React/Docusaurus)

    • EditButton - Appears on each documentation page for authenticated users
    • EditorModal - Full-screen markdown editor with live preview
    • useAuth hook - Manages authentication state using HyperList pattern
  2. Backend API (Node.js/Express)

    • Handles GitHub operations (fetch/commit files)
    • Validates authentication using query parameters
    • Prevents conflicts using SHA comparison
  3. GitHub Integration (Octokit)

    • Fetches file content from repository
    • Commits changes with proper attribution
    • Handles branch operations

Setup Instructions

1. Backend API Setup

Install Dependencies

cd api
npm install

Configure Environment Variables

Create api/.env file:

# GitHub Configuration
GITHUB_TOKEN=ghp_your_github_personal_access_token_here
GITHUB_OWNER=HyperSpin-LLC
GITHUB_REPO=HyperSpin-Docs
GITHUB_DEFAULT_BRANCH=main

# API Configuration
API_PORT=3001
API_AUTH_TOKEN=your_secret_token_here

# CORS Configuration
ALLOWED_ORIGINS=http://localhost:3000,https://docs.hyperai.io

GitHub Token Setup

  1. Go to GitHub → Settings → Developer settings → Personal access tokens → Tokens (classic)
  2. Click "Generate new token (classic)"
  3. Give it a descriptive name (e.g., "HyperSpin Docs Editor")
  4. Select scopes:
    • repo (Full control of private repositories)
      • Needed to read and write files
  5. Generate token and copy it to GITHUB_TOKEN in .env

Important: Keep this token secure! It has write access to your repository.

Start the API Server

cd api
npm start

The server will start on port 3001 (or your configured port).

2. Frontend Setup

The frontend components are already integrated into the Docusaurus site. No additional setup needed!

How It Works

  1. Authentication Check

    • Editor checks localStorage for AuthToken key
    • This matches the HyperList authentication pattern
    • Token structure:
      {
      "access_token": "your_token",
      "userId": 123,
      "username": "john_doe",
      "logTime": "2025-01-01T12:00:00Z"
      }
  2. Edit Button Visibility

    • Edit button only appears if user is authenticated
    • Uses the useAuth() hook to check authentication state
  3. Editor Workflow

    • Click "Edit this page" button
    • Modal opens with current file content
    • Make changes in markdown editor with live preview
    • Click "Save Changes" to commit to GitHub
    • Page reloads to show updated content

3. Authentication Integration

For Development/Testing

To test the editor without full authentication:

// In browser console:
localStorage.setItem('AuthToken', JSON.stringify({
access_token: 'your_secret_token_here', // Must match API_AUTH_TOKEN in backend .env
userId: 1,
username: 'testuser',
logTime: new Date().toISOString()
}));

// Reload page
window.location.reload();

For Production

Integrate with your existing HyperList authentication:

  1. When users log in to HyperList, the auth response is already stored in localStorage.AuthToken
  2. The editor automatically reads this token
  3. No additional authentication step needed!

The editor uses the same authentication pattern as HyperList:

  • Auth parameters sent as query parameters (accessToken, userId)
  • Token validated against backend configuration
  • User information included in commit messages

API Endpoints

GET /api/docs/file

Fetches a file from the GitHub repository.

Query Parameters:

  • path (required) - File path within the repository
  • accessToken (required) - User's access token
  • userId (required) - User's ID
  • branch (optional) - Branch name (defaults to main)

Example:

GET /api/docs/file?path=docs/intro.md&accessToken=your_token&userId=123

Response:

{
"success": true,
"data": {
"path": "docs/intro.md",
"name": "intro.md",
"content": "# Introduction\n\nWelcome...",
"sha": "abc123def456",
"size": 1234,
"url": "https://github.com/...",
"download_url": "https://raw.githubusercontent.com/..."
}
}

POST /api/docs/file

Commits changes to a file in the GitHub repository.

Query Parameters:

  • accessToken (required) - User's access token
  • userId (required) - User's ID

Body Parameters (JSON):

{
"path": "docs/intro.md",
"content": "# Updated content\n\n...",
"message": "Update intro documentation",
"sha": "abc123def456",
"author": {
"name": "John Doe",
"email": "[email protected]"
}
}

Response:

{
"success": true,
"message": "File committed successfully",
"data": {
"commit": {
"sha": "def456ghi789",
"url": "https://github.com/.../commit/def456ghi789",
"message": "Update intro documentation"
},
"content": {
"path": "docs/intro.md",
"sha": "jkl012mno345",
"url": "https://github.com/.../blob/main/docs/intro.md"
}
}
}

GET /api/health

Health check endpoint.

Response:

{
"status": "ok",
"service": "HyperSpin Docs API",
"timestamp": "2025-01-30T12:00:00.000Z",
"github": {
"owner": "HyperSpin-LLC",
"repo": "HyperSpin-Docs",
"branch": "main"
}
}

Usage

For End Users

  1. Log in to HyperList (authentication is shared)
  2. Navigate to any documentation page
  3. Click "Edit this page" button in the top-right
  4. Edit the markdown content in the editor
  5. Preview your changes in real-time (right pane)
  6. Save your changes - they're committed to GitHub immediately
  7. Page reloads to show your updates

For Administrators

Managing Access

Edit permissions are controlled by:

  1. API Token - Only users with valid tokens can edit
  2. GitHub Permissions - Backend token must have repo write access

To revoke access:

  • Change the API_AUTH_TOKEN in backend .env
  • Restart the API server

Monitoring Changes

All commits include:

  • Author attribution (username from auth token)
  • Commit message with filename
  • Timestamp

View commit history:

git log --oneline docs/

Deployment

Backend Deployment

The backend API needs to run separately from the static Docusaurus site.

Option 1: Same Server (Different Port)

# Deploy Docusaurus to port 80/443
npm run build
npm run serve

# Deploy API to port 3001
cd api
npm start

Configure nginx to proxy /api/* requests to port 3001.

Option 2: Separate Server

Deploy API to separate server (e.g., api.hyperspin-docs.com):

  1. Update ALLOWED_ORIGINS in API .env
  2. Update API base URL in frontend code if needed
  3. Configure CORS properly

Frontend Deployment

Docusaurus builds to static files - deploy anywhere:

  • Netlify
  • Vercel
  • GitHub Pages
  • Your own server

The editor components are built into the static site automatically.

Security Considerations

Important Security Practices

  1. GitHub Token

    • Never commit the .env file
    • Use a dedicated token with minimal permissions
    • Rotate tokens periodically
    • Consider using GitHub Apps instead of personal tokens
  2. API Authentication

    • Use strong, random tokens
    • Implement rate limiting in production
    • Consider adding IP whitelisting
    • Log all edit operations
  3. Input Validation

    • Backend validates all file paths (prevents path traversal)
    • Content is sanitized before committing
    • SHA comparison prevents concurrent edit conflicts
  4. CORS Configuration

    • Only allow trusted origins
    • Don't use wildcard (*) in production
    • Update ALLOWED_ORIGINS for production domains

Production Recommendations

  1. Replace MVP Auth with real validation:

    // In server.js authenticateToken function:
    // Instead of checking against API_AUTH_TOKEN,
    // validate against your actual auth API:
    const isValid = await yourAuthAPI.validateToken(accessToken, userId);
    if (!isValid) {
    return res.status(403).json({ error: 'Invalid token' });
    }
  2. Add Rate Limiting:

    npm install express-rate-limit
  3. Add Logging:

    • Log all edit operations
    • Include user, timestamp, file path
    • Monitor for suspicious activity
  4. Consider Pull Requests:

    • Instead of direct commits, create PRs
    • Requires approval before merging
    • Provides review opportunity
    • Update backend to use PR workflow

Troubleshooting

Editor Button Not Appearing

Issue: Can't see "Edit this page" button

Solutions:

  1. Check authentication:
    // In browser console:
    console.log(localStorage.getItem('AuthToken'));
  2. Verify token is valid JSON
  3. Check browser console for errors
  4. Clear cache and reload

Cannot Save Changes

Issue: Error when clicking "Save Changes"

Solutions:

  1. Check API server is running:
    curl http://localhost:3001/api/health
  2. Verify authentication token is valid
  3. Check browser console for detailed error
  4. Verify GitHub token has write permissions

Conflict Errors (409/422)

Issue: "File has been modified" error

Cause: Someone else edited the file since you opened it

Solution:

  1. Close the editor (lose your changes) OR
  2. Copy your changes to clipboard
  3. Reload page to get latest version
  4. Re-open editor
  5. Paste your changes
  6. Save again

CORS Errors

Issue: "CORS policy" error in browser console

Solutions:

  1. Add your frontend URL to ALLOWED_ORIGINS in backend .env
  2. Restart API server
  3. Clear browser cache

Development Tips

Testing Locally

  1. Start API server:

    cd api && npm start
  2. Start Docusaurus dev server:

    npm start
  3. Set test authentication:

    localStorage.setItem('AuthToken', JSON.stringify({
    access_token: 'test_token',
    userId: 1,
    username: 'developer'
    }));
  4. Navigate to any doc page and test editing

Debugging

Enable debug logging in API server:

// In api/server.js, add:
app.use((req, res, next) => {
console.log('Request:', req.method, req.path);
console.log('Query:', req.query);
console.log('Body:', req.body);
next();
});

Future Enhancements

Potential improvements for the editor:

  1. Rich Features

    • Image upload support
    • File browser for navigation
    • Search and replace
    • Spell check
  2. Collaboration

    • Real-time collaborative editing
    • See who else is editing
    • Edit locks to prevent conflicts
  3. Workflow

    • Draft/publish workflow
    • Review/approval process
    • Automated PR creation
    • Integration with CI/CD
  4. Advanced Auth

    • Role-based permissions (who can edit what)
    • OAuth integration
    • Session management
    • Token refresh

Support

If you encounter issues:

  1. Check this guide's troubleshooting section
  2. Review API server logs
  3. Check browser console for errors
  4. Verify environment variables are set correctly
  5. Test with curl to isolate frontend vs backend issues

Last Updated: 2025-01-30 Version: 1.0.0 (MVP)