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:
-
Frontend Components (React/Docusaurus)
EditButton- Appears on each documentation page for authenticated usersEditorModal- Full-screen markdown editor with live previewuseAuthhook - Manages authentication state using HyperList pattern
-
Backend API (Node.js/Express)
- Handles GitHub operations (fetch/commit files)
- Validates authentication using query parameters
- Prevents conflicts using SHA comparison
-
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
- Go to GitHub → Settings → Developer settings → Personal access tokens → Tokens (classic)
- Click "Generate new token (classic)"
- Give it a descriptive name (e.g., "HyperSpin Docs Editor")
- Select scopes:
- ✅
repo(Full control of private repositories)- Needed to read and write files
- ✅
- Generate token and copy it to
GITHUB_TOKENin.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
-
Authentication Check
- Editor checks localStorage for
AuthTokenkey - This matches the HyperList authentication pattern
- Token structure:
{
"access_token": "your_token",
"userId": 123,
"username": "john_doe",
"logTime": "2025-01-01T12:00:00Z"
}
- Editor checks localStorage for
-
Edit Button Visibility
- Edit button only appears if user is authenticated
- Uses the
useAuth()hook to check authentication state
-
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:
- When users log in to HyperList, the auth response is already stored in
localStorage.AuthToken - The editor automatically reads this token
- 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 repositoryaccessToken(required) - User's access tokenuserId(required) - User's IDbranch(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 tokenuserId(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
- Log in to HyperList (authentication is shared)
- Navigate to any documentation page
- Click "Edit this page" button in the top-right
- Edit the markdown content in the editor
- Preview your changes in real-time (right pane)
- Save your changes - they're committed to GitHub immediately
- Page reloads to show your updates
For Administrators
Managing Access
Edit permissions are controlled by:
- API Token - Only users with valid tokens can edit
- GitHub Permissions - Backend token must have repo write access
To revoke access:
- Change the
API_AUTH_TOKENin 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):
- Update
ALLOWED_ORIGINSin API.env - Update API base URL in frontend code if needed
- 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
-
GitHub Token
- Never commit the
.envfile - Use a dedicated token with minimal permissions
- Rotate tokens periodically
- Consider using GitHub Apps instead of personal tokens
- Never commit the
-
API Authentication
- Use strong, random tokens
- Implement rate limiting in production
- Consider adding IP whitelisting
- Log all edit operations
-
Input Validation
- Backend validates all file paths (prevents path traversal)
- Content is sanitized before committing
- SHA comparison prevents concurrent edit conflicts
-
CORS Configuration
- Only allow trusted origins
- Don't use wildcard (
*) in production - Update
ALLOWED_ORIGINSfor production domains
Production Recommendations
-
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' });
} -
Add Rate Limiting:
npm install express-rate-limit -
Add Logging:
- Log all edit operations
- Include user, timestamp, file path
- Monitor for suspicious activity
-
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:
- Check authentication:
// In browser console:
console.log(localStorage.getItem('AuthToken')); - Verify token is valid JSON
- Check browser console for errors
- Clear cache and reload
Cannot Save Changes
Issue: Error when clicking "Save Changes"
Solutions:
- Check API server is running:
curl http://localhost:3001/api/health - Verify authentication token is valid
- Check browser console for detailed error
- 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:
- Close the editor (lose your changes) OR
- Copy your changes to clipboard
- Reload page to get latest version
- Re-open editor
- Paste your changes
- Save again
CORS Errors
Issue: "CORS policy" error in browser console
Solutions:
- Add your frontend URL to
ALLOWED_ORIGINSin backend.env - Restart API server
- Clear browser cache
Development Tips
Testing Locally
-
Start API server:
cd api && npm start -
Start Docusaurus dev server:
npm start -
Set test authentication:
localStorage.setItem('AuthToken', JSON.stringify({
access_token: 'test_token',
userId: 1,
username: 'developer'
})); -
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:
-
Rich Features
- Image upload support
- File browser for navigation
- Search and replace
- Spell check
-
Collaboration
- Real-time collaborative editing
- See who else is editing
- Edit locks to prevent conflicts
-
Workflow
- Draft/publish workflow
- Review/approval process
- Automated PR creation
- Integration with CI/CD
-
Advanced Auth
- Role-based permissions (who can edit what)
- OAuth integration
- Session management
- Token refresh
Support
If you encounter issues:
- Check this guide's troubleshooting section
- Review API server logs
- Check browser console for errors
- Verify environment variables are set correctly
- Test with curl to isolate frontend vs backend issues
Last Updated: 2025-01-30 Version: 1.0.0 (MVP)