Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d838b67e31 | ||
|
|
fa6b7e8939 | ||
|
|
321c828c86 | ||
|
|
15a5cfcc61 | ||
|
|
9fb8ce34ec | ||
|
|
8f9fe3fa08 | ||
|
|
f32a756434 | ||
|
|
3a0dfea128 | ||
|
|
6c551f4cd0 | ||
|
|
5539235004 |
@@ -30,6 +30,7 @@ coverage
|
||||
.nyc_output
|
||||
*.test.ts
|
||||
*.spec.ts
|
||||
tests
|
||||
|
||||
# CI/CD
|
||||
.github
|
||||
@@ -49,6 +50,13 @@ docker-compose*.yml
|
||||
.env.local
|
||||
.env.*.local
|
||||
|
||||
# Sensitive key material
|
||||
*.pem
|
||||
*.key
|
||||
*.p12
|
||||
*.pfx
|
||||
*.crt
|
||||
|
||||
# Misc
|
||||
tmp
|
||||
temp
|
||||
|
||||
+15
-15
@@ -17,7 +17,7 @@ jobs:
|
||||
outputs:
|
||||
should_test: ${{ steps.filter.outputs.should_test }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -42,16 +42,16 @@ jobs:
|
||||
if: needs.check-changes.outputs.should_test == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
with:
|
||||
node-version: '20.x'
|
||||
|
||||
- name: Cache node_modules
|
||||
id: cache-nm
|
||||
uses: actions/cache@v4
|
||||
uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
|
||||
with:
|
||||
path: node_modules
|
||||
key: node-modules-${{ runner.os }}-node20-${{ hashFiles('package-lock.json') }}
|
||||
@@ -75,15 +75,15 @@ jobs:
|
||||
needs: setup
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
with:
|
||||
node-version: '20.x'
|
||||
|
||||
- name: Restore node_modules from cache
|
||||
uses: actions/cache/restore@v4
|
||||
uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
|
||||
with:
|
||||
path: node_modules
|
||||
key: node-modules-${{ runner.os }}-node20-${{ hashFiles('package-lock.json') }}
|
||||
@@ -96,15 +96,15 @@ jobs:
|
||||
needs: setup
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
with:
|
||||
node-version: '20.x'
|
||||
|
||||
- name: Restore node_modules from cache
|
||||
uses: actions/cache/restore@v4
|
||||
uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
|
||||
with:
|
||||
path: node_modules
|
||||
key: node-modules-${{ runner.os }}-node20-${{ hashFiles('package-lock.json') }}
|
||||
@@ -117,21 +117,21 @@ jobs:
|
||||
needs: setup
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
with:
|
||||
node-version: '20.x'
|
||||
|
||||
- name: Restore node_modules from cache
|
||||
uses: actions/cache/restore@v4
|
||||
uses: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
|
||||
with:
|
||||
path: node_modules
|
||||
key: node-modules-${{ runner.os }}-node20-${{ hashFiles('package-lock.json') }}
|
||||
|
||||
- name: Download build output
|
||||
uses: actions/download-artifact@v4
|
||||
uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4.3.0
|
||||
with:
|
||||
name: dist
|
||||
path: dist/
|
||||
@@ -148,7 +148,7 @@ jobs:
|
||||
|
||||
- name: Cache Playwright browsers
|
||||
id: cache-pw
|
||||
uses: actions/cache@v4
|
||||
uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
|
||||
with:
|
||||
path: ~/.cache/ms-playwright
|
||||
key: playwright-${{ runner.os }}-${{ steps.pw-version.outputs.version }}
|
||||
|
||||
@@ -17,8 +17,8 @@ concurrency:
|
||||
cancel-in-progress: true
|
||||
|
||||
env:
|
||||
IMAGE_NAME_MCP: sanjibdevnath/mcp-excalidraw-local
|
||||
IMAGE_NAME_CANVAS: sanjibdevnath/mcp-excalidraw-local-canvas
|
||||
IMAGE_NAME_MCP: celstnblacc/excalidraw-mcp-sentinel
|
||||
IMAGE_NAME_CANVAS: celstnblacc/excalidraw-mcp-sentinel-canvas
|
||||
|
||||
jobs:
|
||||
check-changes:
|
||||
@@ -27,7 +27,7 @@ jobs:
|
||||
outputs:
|
||||
should_build: ${{ steps.filter.outputs.should_build }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -52,14 +52,14 @@ jobs:
|
||||
if: needs.check-changes.outputs.should_build == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3.10.0
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
if: github.event_name == 'workflow_dispatch' && github.event.inputs.push == 'true'
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
@@ -74,7 +74,7 @@ jobs:
|
||||
type=sha,prefix=sha-
|
||||
|
||||
- name: Build MCP Server image
|
||||
uses: docker/build-push-action@v5
|
||||
uses: docker/build-push-action@14487ce63c7a62a4a324b0bfb37086795e31c6c1 # v5.5.0
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
@@ -90,14 +90,14 @@ jobs:
|
||||
if: needs.check-changes.outputs.should_build == 'true'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3.10.0
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
if: github.event_name == 'workflow_dispatch' && github.event.inputs.push == 'true'
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
@@ -112,7 +112,7 @@ jobs:
|
||||
type=sha,prefix=sha-
|
||||
|
||||
- name: Build Canvas Server image
|
||||
uses: docker/build-push-action@v5
|
||||
uses: docker/build-push-action@14487ce63c7a62a4a324b0bfb37086795e31c6c1 # v5.5.0
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile.canvas
|
||||
@@ -128,7 +128,7 @@ jobs:
|
||||
if: needs.build-mcp.result == 'success' && needs.build-canvas.result == 'success'
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
|
||||
- name: Build and test Canvas image locally
|
||||
run: |
|
||||
|
||||
@@ -24,10 +24,10 @@ jobs:
|
||||
id-token: write
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
with:
|
||||
node-version: '20.x'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
@@ -58,7 +58,7 @@ jobs:
|
||||
- name: Check if version exists on NPM
|
||||
id: check
|
||||
run: |
|
||||
if npm view @sanjibdevnath/mcp-excalidraw-local@${{ steps.version.outputs.version }} version 2>/dev/null; then
|
||||
if npm view excalidraw-mcp-sentinel@${{ steps.version.outputs.version }} version 2>/dev/null; then
|
||||
echo "exists=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "exists=false" >> "$GITHUB_OUTPUT"
|
||||
|
||||
@@ -26,7 +26,7 @@ jobs:
|
||||
should_release: ${{ steps.bump.outputs.should_release }}
|
||||
prev_tag: ${{ steps.bump.outputs.prev_tag }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
@@ -128,20 +128,20 @@ jobs:
|
||||
steps:
|
||||
- name: Generate release bot token
|
||||
id: app-token
|
||||
uses: actions/create-github-app-token@v1
|
||||
uses: actions/create-github-app-token@c1a285145b9d317df6ced56c550f5b5e3e8cd3f9 # v1.11.6
|
||||
with:
|
||||
app-id: ${{ secrets.APP_ID }}
|
||||
private-key: ${{ secrets.APP_PRIVATE_KEY }}
|
||||
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
fetch-depth: 0
|
||||
token: ${{ steps.app-token.outputs.token }}
|
||||
|
||||
- name: Configure git
|
||||
run: |
|
||||
git config user.name "sanjibdevnathlabs-release-bot[bot]"
|
||||
git config user.email "${{ secrets.APP_ID }}+sanjibdevnathlabs-release-bot[bot]@users.noreply.github.com"
|
||||
git config user.name "excalidraw-sentinel-release-bot[bot]"
|
||||
git config user.email "${{ secrets.APP_ID }}+excalidraw-sentinel-release-bot[bot]@users.noreply.github.com"
|
||||
|
||||
- name: Bump version in package.json
|
||||
run: |
|
||||
@@ -156,7 +156,7 @@ jobs:
|
||||
git push origin "v${{ needs.check.outputs.new_version }}"
|
||||
|
||||
- name: Create GitHub Release
|
||||
uses: softprops/action-gh-release@v2
|
||||
uses: softprops/action-gh-release@da05d552573ad5aba36ea0be2ddfef1a7e5c4d12 # v2.2.2
|
||||
with:
|
||||
token: ${{ steps.app-token.outputs.token }}
|
||||
tag_name: v${{ needs.check.outputs.new_version }}
|
||||
@@ -170,7 +170,7 @@ jobs:
|
||||
|
||||
---
|
||||
```
|
||||
npm install @sanjibdevnath/mcp-excalidraw-local@${{ needs.check.outputs.new_version }}
|
||||
npm install excalidraw-mcp-sentinel@${{ needs.check.outputs.new_version }}
|
||||
```
|
||||
draft: false
|
||||
prerelease: false
|
||||
@@ -180,19 +180,19 @@ jobs:
|
||||
needs: release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
ref: main
|
||||
|
||||
- name: Setup Node.js
|
||||
uses: actions/setup-node@v4
|
||||
uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4.4.0
|
||||
with:
|
||||
node-version: '20.x'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
|
||||
- name: Cache node_modules
|
||||
id: cache-nm
|
||||
uses: actions/cache@v4
|
||||
uses: actions/cache@5a3ec84eff668545956fd18022155c47e93e2684 # v4.2.3
|
||||
with:
|
||||
path: node_modules
|
||||
key: node-modules-${{ runner.os }}-node20.x-${{ hashFiles('package-lock.json') }}
|
||||
@@ -208,7 +208,7 @@ jobs:
|
||||
id: check-npm
|
||||
run: |
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
if npm view @sanjibdevnath/mcp-excalidraw-local@$VERSION version 2>/dev/null; then
|
||||
if npm view excalidraw-mcp-sentinel@$VERSION version 2>/dev/null; then
|
||||
echo "exists=true" >> "$GITHUB_OUTPUT"
|
||||
else
|
||||
echo "exists=false" >> "$GITHUB_OUTPUT"
|
||||
@@ -233,41 +233,41 @@ jobs:
|
||||
needs: release
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
|
||||
with:
|
||||
ref: v${{ needs.release.outputs.version }}
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
uses: docker/setup-buildx-action@b5ca514318bd6ebac0fb2aedd5d36ec1b5c232a2 # v3.10.0
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Build and push MCP Server image
|
||||
uses: docker/build-push-action@v5
|
||||
uses: docker/build-push-action@14487ce63c7a62a4a324b0bfb37086795e31c6c1 # v5.5.0
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
push: true
|
||||
tags: |
|
||||
sanjibdevnath/mcp-excalidraw-local:latest
|
||||
sanjibdevnath/mcp-excalidraw-local:v${{ needs.release.outputs.version }}
|
||||
celstnblacc/excalidraw-mcp-sentinel:latest
|
||||
celstnblacc/excalidraw-mcp-sentinel:v${{ needs.release.outputs.version }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
platforms: linux/amd64,linux/arm64
|
||||
|
||||
- name: Build and push Canvas Server image
|
||||
uses: docker/build-push-action@v5
|
||||
uses: docker/build-push-action@14487ce63c7a62a4a324b0bfb37086795e31c6c1 # v5.5.0
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile.canvas
|
||||
push: true
|
||||
tags: |
|
||||
sanjibdevnath/mcp-excalidraw-local-canvas:latest
|
||||
sanjibdevnath/mcp-excalidraw-local-canvas:v${{ needs.release.outputs.version }}
|
||||
celstnblacc/excalidraw-mcp-sentinel-canvas:latest
|
||||
celstnblacc/excalidraw-mcp-sentinel-canvas:v${{ needs.release.outputs.version }}
|
||||
cache-from: type=gha
|
||||
cache-to: type=gha,mode=max
|
||||
platforms: linux/amd64,linux/arm64
|
||||
|
||||
@@ -7,6 +7,12 @@ public/dist/
|
||||
|
||||
# Environment files
|
||||
.env
|
||||
.env.*
|
||||
*.key
|
||||
*.pem
|
||||
*.p12
|
||||
*.pfx
|
||||
secrets.json
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
|
||||
Executable
+12
@@ -0,0 +1,12 @@
|
||||
#!/usr/bin/env bash
|
||||
# Project-level pre-commit hook for mcp-excalidraw-local.
|
||||
# ShipGuard SAST and secret detection are handled by the global hook.
|
||||
# This hook runs the project test suite.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
REPO_ROOT="$(git rev-parse --show-toplevel)"
|
||||
cd "$REPO_ROOT"
|
||||
|
||||
echo "→ Running tests (vitest)..."
|
||||
npm test --silent
|
||||
@@ -0,0 +1,107 @@
|
||||
# AGENTS.md
|
||||
|
||||
Agent instructions for excalidraw-mcp-sentinel. Read this before starting any task.
|
||||
|
||||
## What This Is
|
||||
|
||||
A hardened, self-hosted Excalidraw MCP server (`excalidraw-mcp-sentinel`). Single Node.js/TypeScript process
|
||||
running an MCP server (stdio, 32 tools), an Express+WebSocket canvas server, and
|
||||
SQLite persistence with multi-tenancy. Forked from [sanjibdevnathlabs/mcp-excalidraw-local](https://github.com/sanjibdevnathlabs/mcp-excalidraw-local).
|
||||
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
# Install
|
||||
npm ci
|
||||
|
||||
# Build (frontend + server)
|
||||
npm run build
|
||||
|
||||
# Build server only (TypeScript)
|
||||
npm run build:server
|
||||
|
||||
# Type check
|
||||
npm run type-check
|
||||
|
||||
# Tests
|
||||
npm test # full suite (vitest, 369 tests)
|
||||
npm run test:api # API tests only
|
||||
npm run test:ws # WebSocket tests only
|
||||
|
||||
# Run canvas server
|
||||
node dist/server.js
|
||||
|
||||
# Health check
|
||||
curl http://localhost:3000/health
|
||||
```
|
||||
|
||||
## Architecture
|
||||
|
||||
```
|
||||
src/index.ts MCP server (stdio) — 32 tools, HTTP client to canvas
|
||||
src/server.ts Express canvas server — REST API, WebSocket, Zod validation
|
||||
src/security.ts Security middleware — auth, CORS, rate limiting, sanitization
|
||||
src/db.ts SQLite persistence — CRUD, FTS5, migrations, tenants
|
||||
src/types.ts Shared TypeScript types, ID generation, element validation
|
||||
frontend/ React + Excalidraw UI (Vite, output → dist/frontend/)
|
||||
```
|
||||
|
||||
Data flow: MCP tool → `index.ts` → HTTP → `server.ts` → SQLite + WS broadcast → frontend.
|
||||
|
||||
## Key Constraints
|
||||
|
||||
- **ESM only** — all imports use `.js` extension. Do not use `require()`.
|
||||
- **Strict TypeScript** — `noUncheckedIndexedAccess` enabled. No `any` without justification.
|
||||
- **No `===` on secrets** — use `crypto.timingSafeEqual`. See `src/security.ts`.
|
||||
- **Validation before DB write** — always validate element types against `VALID_ELEMENT_TYPES` before persisting.
|
||||
- **Logger after validation** — never access `req.body` fields in logger calls before the array/type checks run (crash risk).
|
||||
- **Auth env vars read at request time** — `security.ts` reads `process.env` on each call so tests can mutate env between cases. Do not cache `process.env.EXCALIDRAW_API_KEY`.
|
||||
- **Canvas sync is fire-and-forget** — MCP handlers call canvas REST but never fail if canvas is down. Use `syncToCanvas()`.
|
||||
- **Logging to file only** — never log to stdout (breaks MCP stdio JSON protocol). Use the Winston logger in `src/utils/logger.ts`.
|
||||
|
||||
## Security Middleware (`src/security.ts`)
|
||||
|
||||
All middleware lives here — do not duplicate in routes:
|
||||
- `helmetMiddleware` — security headers
|
||||
- `corsMiddleware` — explicit origin allowlist (env: `ALLOWED_ORIGINS`)
|
||||
- `apiKeyAuth` — timing-safe API key check (env: `EXCALIDRAW_API_KEY`)
|
||||
- `sanitizeBody` — strips `__proto__`/`constructor`/`prototype` keys
|
||||
- `validateMermaidInput` — caps diagram size at 50 KB
|
||||
- `generalRateLimit` / `destructiveRateLimit` / `writeBurstLimit` — 3-tier rate limiting
|
||||
- `requireConfirm` — requires `?confirm=true` on destructive endpoints
|
||||
- `verifyWsClient` — WS origin check at upgrade time
|
||||
- `sanitizeSearchQuery` / `InvalidSearchQueryError` — FTS input sanitization
|
||||
|
||||
## Environment Variables
|
||||
|
||||
| Variable | Default | Notes |
|
||||
|----------|---------|-------|
|
||||
| `CANVAS_PORT` | `3000` | Canvas server port |
|
||||
| `EXCALIDRAW_API_KEY` | _(unset)_ | Enables API key auth on all `/api/*` routes |
|
||||
| `ALLOWED_ORIGINS` | `http://localhost:3000,...` | Comma-separated CORS allowlist |
|
||||
| `EXCALIDRAW_DB_PATH` | `$HOME/.excalidraw-mcp/excalidraw.db` | SQLite path |
|
||||
| `EXCALIDRAW_EXPORT_DIR` | `process.cwd()` | Export directory (path traversal guard) |
|
||||
| `EXCALIDRAW_RATE_LIMIT_GENERAL_MAX` | `100` | Requests per 15-minute window |
|
||||
| `EXCALIDRAW_RATE_LIMIT_DESTRUCTIVE_MAX` | `10` | Requests per 1-minute window |
|
||||
| `EXCALIDRAW_RATE_LIMIT_WRITE_BURST_MAX` | `10` | Sync writes per 1-minute window |
|
||||
|
||||
## Testing Rules
|
||||
|
||||
- 369 tests across 20 files — all must pass before any commit.
|
||||
- New security-relevant behaviour must have a regression test.
|
||||
- Tests mutate `process.env` between cases — do not cache env values at module init.
|
||||
- Integration tests use real SQLite (tmpdir). Do not mock the DB.
|
||||
|
||||
## Protected Files
|
||||
|
||||
- `AGENTS.md` — immutable unless explicitly named in the request.
|
||||
- `CLAUDE.md` — immutable unless explicitly named in the request.
|
||||
- `CHANGELOG.md` — append-only. Never edit or reorder existing entries.
|
||||
|
||||
## Before `npm publish`
|
||||
|
||||
- [ ] Bump `version` in `package.json` (current: `1.0.0`)
|
||||
- [ ] `npm test` → 369/369
|
||||
- [ ] `npm run build` → zero errors
|
||||
- [ ] `shipguard scan .` → 0 CRITICAL
|
||||
- [ ] `npm publish --dry-run` → only `dist/`, `skills/`, `README.md`, `LICENSE` included
|
||||
@@ -0,0 +1,55 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this project are documented here.
|
||||
Format: [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [1.0.1] - 2026-03-29
|
||||
|
||||
### Fixed
|
||||
- `better-sqlite3` native module now rebuilt on install via `postinstall` script, fixing Node.js version mismatch errors (e.g. Node v22 vs v25) when installing via npx
|
||||
|
||||
## [1.0.0] - 2026-03-29
|
||||
|
||||
### Changed
|
||||
- Renamed project from `@sanjibdevnath/mcp-excalidraw-local` to `excalidraw-mcp-sentinel`
|
||||
- New npm package name: `excalidraw-mcp-sentinel` (unscoped)
|
||||
- GitHub repo: `celstnblacc/excalidraw-mcp-sentinel`
|
||||
- Docker images: `celstnblacc/excalidraw-mcp-sentinel` and `celstnblacc/excalidraw-mcp-sentinel-canvas`
|
||||
- CLI binary renamed: `excalidraw-mcp-sentinel`
|
||||
- Version reset to 1.0.0 for independent release track
|
||||
- Added "Why this fork?" section to README with full attribution
|
||||
|
||||
### Removed
|
||||
- Superseded planning docs (PLAN.md, PLAN_v2.md, REVIEW.md, HANDOFF.md)
|
||||
|
||||
## [1.6.3] - 2026-03-29
|
||||
|
||||
### Security
|
||||
- Added `security.ts` middleware module: helmet headers, explicit CORS allowlist, API key auth
|
||||
with timing-safe comparison, prototype pollution guard, Mermaid input size limits
|
||||
- WebSocket authentication: challenge-response (`auth_required` → `hello + apiKey`) with 5 s
|
||||
timeout and close code 4001 on failure; origin verification via `verifyClient`
|
||||
- Rate limiting on all `/api/*` routes: 100 req/15 min general, 10 req/min destructive, 10 req/min
|
||||
sync write burst
|
||||
- `sanitizeSearchQuery` now throws typed `InvalidSearchQueryError` instead of generic `Error`
|
||||
- Docker: added `deploy.resources.limits` (canvas 1 CPU/512M, mcp 0.5 CPU/256M) to
|
||||
`docker-compose.yml`; extended `.dockerignore` with `tests/` and sensitive key file patterns
|
||||
|
||||
### Fixed
|
||||
- `POST /api/elements/sync`: array validation now runs before logger access, preventing a
|
||||
`TypeError` crash (500) on null/non-array input — now returns 400
|
||||
- `POST /api/elements/sync/v2`: element type validated against `EXCALIDRAW_ELEMENT_TYPES`
|
||||
before write; invalid types return 400 instead of being persisted silently
|
||||
- Upgraded `zod` from 3.22.4 to 3.25.5 to resolve `ERR_PACKAGE_PATH_NOT_EXPORTED` crash at
|
||||
MCP server startup caused by `zod-to-json-schema` peer dependency mismatch
|
||||
|
||||
### Changed
|
||||
- `ElementSharedFieldsSchema` extracted from `CreateElementSchema`/`UpdateElementSchema` to
|
||||
eliminate 25-field duplication; both schemas now use `.extend()`
|
||||
- `VALID_ELEMENT_TYPES` moved to module-level constant (was allocated per-request)
|
||||
- `resolveHelloTenantAndProject` parameter typed as `HelloMessage` (was `any`)
|
||||
- `getAllFilesObject()` helper extracted; `sendFilesAdded()` and `GET /api/files` share it
|
||||
- `sendLegacyInitialWsMessages` renamed to `sendAuthlessInitialMessages`
|
||||
- `.project-hooks/pre-commit` added to run vitest on every commit
|
||||
@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
||||
|
||||
## What This Is
|
||||
|
||||
A fully local, self-hosted Excalidraw MCP server. Single Node.js process that runs an MCP server (stdio, 32 tools), an embedded Express+WebSocket canvas server, and SQLite persistence with multi-tenancy. Forked from [yctimlin/mcp_excalidraw](https://github.com/yctimlin/mcp_excalidraw).
|
||||
A hardened, self-hosted Excalidraw MCP server (`excalidraw-mcp-sentinel`). Single Node.js process that runs an MCP server (stdio, 32 tools), an embedded Express+WebSocket canvas server, and SQLite persistence with multi-tenancy. Forked from [sanjibdevnathlabs/mcp-excalidraw-local](https://github.com/sanjibdevnathlabs/mcp-excalidraw-local) (itself from [yctimlin/mcp_excalidraw](https://github.com/yctimlin/mcp_excalidraw)).
|
||||
|
||||
## Build & Development Commands
|
||||
|
||||
@@ -38,7 +38,7 @@ node dist/server.js
|
||||
curl http://localhost:3000/health
|
||||
```
|
||||
|
||||
There are no unit tests. Validation is done via type checking (`pnpm run type-check`) and build verification. The CI runs `type-check` then `build` across Node 18/20/22.
|
||||
369 tests across unit, API, WebSocket, and regression suites. Run `npm test` or `pnpm test`. CI runs `type-check` then `build` then `test` across Node 18/20/22.
|
||||
|
||||
## Architecture
|
||||
|
||||
@@ -106,6 +106,29 @@ frontend/ ── React + Excalidraw UI (Vite build → dist/frontend/)
|
||||
Two Dockerfiles: `Dockerfile` (MCP server only), `Dockerfile.canvas` (canvas with frontend). `docker-compose.yml` orchestrates both with a `full` profile.
|
||||
|
||||
|
||||
## Publish Readiness
|
||||
|
||||
**Last hardened:** 2026-03-29 — gauntlet all-green, PR #1 merged.
|
||||
|
||||
### Security posture (as of 1.6.3)
|
||||
- `src/security.ts`: helmet, CORS allowlist, timing-safe API key auth, prototype pollution guard, 3-tier rate limiting, WS challenge-response auth, Mermaid input size cap
|
||||
- 369/369 tests passing; 4 regression tests cover previously crash-able sync paths
|
||||
- Docker: non-root user, resource limits, hardened `.dockerignore`
|
||||
|
||||
### Before running `npm publish`
|
||||
- [ ] Bump `version` in `package.json` to match `CHANGELOG.md` entry (currently `1.0.0`)
|
||||
- [ ] Run `npm test` — must be 369/369
|
||||
- [ ] Run `npm run build` — must be zero TS errors
|
||||
- [ ] Run `shipguard scan .` — must be 0 CRITICAL findings
|
||||
- [ ] Verify `CHANGELOG.md` has an entry for the version being published
|
||||
- [ ] `npm publish --dry-run` to confirm only `dist/`, `skills/`, `README.md`, `LICENSE` are included
|
||||
|
||||
### Safe to push to GitHub?
|
||||
Yes — as of PR #1, the repo is clean for public visibility:
|
||||
- No secrets, hardcoded paths, or private identifiers in tracked files
|
||||
- Auth is opt-in (`EXCALIDRAW_API_KEY` unset = dev mode, by design)
|
||||
- Docker images run non-root with resource limits
|
||||
|
||||
## Code Search Optimization
|
||||
|
||||
When exploring or understanding code in supported languages (JS, TS, Python, Go, Rust, Java, C, C++, Ruby):
|
||||
|
||||
@@ -51,6 +51,9 @@ USER nodejs
|
||||
|
||||
ENV NODE_ENV=production
|
||||
ENV PORT=3000
|
||||
# HOST=0.0.0.0 is correct inside Docker: the container binds all interfaces,
|
||||
# but external access is gated by the published port mapping in docker-compose.yml.
|
||||
# For local dev without Docker, the server defaults to localhost (127.0.0.1).
|
||||
ENV HOST=0.0.0.0
|
||||
ENV EXCALIDRAW_DB_PATH=/app/data/excalidraw.db
|
||||
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
# MCP Excalidraw Local
|
||||
# Excalidraw MCP Sentinel
|
||||
|
||||
[](https://github.com/sanjibdevnathlabs/mcp-excalidraw-local/actions/workflows/ci.yml)
|
||||
[](https://github.com/sanjibdevnathlabs/mcp-excalidraw-local/actions/workflows/release.yml)
|
||||
[](https://github.com/celstnblacc/excalidraw-mcp-sentinel/actions/workflows/ci.yml)
|
||||
[](https://github.com/celstnblacc/excalidraw-mcp-sentinel/actions/workflows/release.yml)
|
||||
[](LICENSE)
|
||||
|
||||
A fully local, self-hosted Excalidraw MCP server with **SQLite persistence**, **multi-tenancy**, and **auto-sync** — designed to run entirely on your machine without depending on `excalidraw.com`.
|
||||
A **hardened**, fully local, self-hosted Excalidraw MCP server with **SQLite persistence**, **multi-tenancy**, **auto-sync**, and **production-grade security** — designed to run entirely on your machine without depending on `excalidraw.com`.
|
||||
|
||||
Run a live Excalidraw canvas and control it from any AI agent. This repo provides:
|
||||
|
||||
@@ -13,10 +13,23 @@ Run a live Excalidraw canvas and control it from any AI agent. This repo provide
|
||||
- **Live Canvas**: Real-time Excalidraw UI synced via WebSocket
|
||||
- **SQLite Persistence**: Elements survive restarts, with versioning and search
|
||||
- **Multi-Tenancy**: Isolated canvases per workspace, auto-detected
|
||||
- **Security Hardened**: Helmet, rate limiting, API key auth, prototype pollution guard, WS challenge-response
|
||||
- **369 Tests**: Full test coverage across unit, API, WebSocket, and regression tests
|
||||
|
||||
> **Fork notice:** This project is forked from [yctimlin/mcp_excalidraw](https://github.com/yctimlin/mcp_excalidraw) and extends it with persistence, multi-workspace support, and numerous UX improvements. Full credit to the original author for the excellent foundation. See [What Changed From Upstream](#what-changed-from-upstream) for details.
|
||||
## Why this fork?
|
||||
|
||||
Keywords: Excalidraw MCP server, AI diagramming, local Excalidraw, self-hosted, SQLite persistence, multi-tenant, Mermaid to Excalidraw.
|
||||
Forked from [celstnblacc/excalidraw-mcp-sentinel](https://github.com/celstnblacc/excalidraw-mcp-sentinel) (itself a fork of [yctimlin/mcp_excalidraw](https://github.com/yctimlin/mcp_excalidraw)) with production hardening:
|
||||
|
||||
- **369 tests** (upstream has none) — unit, API, WebSocket, and regression
|
||||
- **Security middleware** (`src/security.ts`): helmet, CORS allowlist, timing-safe API key auth, prototype pollution guard, input sanitization
|
||||
- **3-tier rate limiting**: general, destructive, and write-burst ceilings
|
||||
- **WebSocket challenge-response authentication**
|
||||
- **Docker hardening**: non-root user, resource limits, hardened `.dockerignore`
|
||||
- **Full gauntlet security audit pass**
|
||||
|
||||
Full credit to [@sanjibdevnathlabs](https://github.com/sanjibdevnathlabs) and [@yctimlin](https://github.com/yctimlin) for the excellent foundation. See [What Changed From Upstream](#what-changed-from-upstream) for the full diff.
|
||||
|
||||
Keywords: Excalidraw MCP server, AI diagramming, local Excalidraw, self-hosted, SQLite persistence, multi-tenant, Mermaid to Excalidraw, security hardened.
|
||||
|
||||
## Screenshots
|
||||
|
||||
@@ -87,14 +100,14 @@ Install "Desktop development with C++" from [Visual Studio Build Tools](https://
|
||||
The setup wizard checks your environment, optionally installs the agent skill, and configures MCP clients — all interactively. Every step is skippable.
|
||||
|
||||
```bash
|
||||
npx @sanjibdevnath/mcp-excalidraw-local setup
|
||||
npx excalidraw-mcp-sentinel setup
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Example session</summary>
|
||||
|
||||
```
|
||||
$ npx @sanjibdevnath/mcp-excalidraw-local setup
|
||||
$ npx excalidraw-mcp-sentinel setup
|
||||
|
||||
Excalidraw MCP — Setup
|
||||
|
||||
@@ -136,8 +149,8 @@ $ npx @sanjibdevnath/mcp-excalidraw-local setup
|
||||
### Path B: From Source
|
||||
|
||||
```bash
|
||||
git clone https://github.com/sanjibdevnathlabs/mcp-excalidraw-local.git
|
||||
cd mcp-excalidraw-local
|
||||
git clone https://github.com/celstnblacc/excalidraw-mcp-sentinel.git
|
||||
cd excalidraw-mcp-sentinel
|
||||
|
||||
npm install
|
||||
npm run build
|
||||
@@ -156,7 +169,7 @@ Open `http://localhost:3000` in your browser.
|
||||
|
||||
Canvas server:
|
||||
```bash
|
||||
docker run -d -p 3000:3000 --name mcp-excalidraw-canvas sanjibdevnath/mcp-excalidraw-local-canvas:latest
|
||||
docker run -d -p 3000:3000 --name mcp-excalidraw-canvas celstnblacc/excalidraw-mcp-sentinel-canvas:latest
|
||||
```
|
||||
|
||||
MCP server (stdio) is typically launched by your MCP client:
|
||||
@@ -168,7 +181,7 @@ MCP server (stdio) is typically launched by your MCP client:
|
||||
"args": [
|
||||
"run", "-i", "--rm",
|
||||
"-e", "CANVAS_PORT=3000",
|
||||
"sanjibdevnath/mcp-excalidraw-local:latest"
|
||||
"celstnblacc/excalidraw-mcp-sentinel:latest"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -190,7 +203,7 @@ Add to `~/.cursor/mcp.json` (global) or `.cursor/mcp.json` (per-project):
|
||||
"mcpServers": {
|
||||
"excalidraw-canvas": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@sanjibdevnath/mcp-excalidraw-local"],
|
||||
"args": ["-y", "excalidraw-mcp-sentinel"],
|
||||
"env": {
|
||||
"CANVAS_PORT": "3000"
|
||||
}
|
||||
@@ -224,7 +237,7 @@ Add to `claude_desktop_config.json`:
|
||||
"mcpServers": {
|
||||
"excalidraw-canvas": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@sanjibdevnath/mcp-excalidraw-local"],
|
||||
"args": ["-y", "excalidraw-mcp-sentinel"],
|
||||
"env": {
|
||||
"CANVAS_PORT": "3000"
|
||||
}
|
||||
@@ -238,7 +251,7 @@ Add to `claude_desktop_config.json`:
|
||||
```bash
|
||||
claude mcp add excalidraw-canvas --scope user \
|
||||
-e CANVAS_PORT=3000 \
|
||||
-- npx -y @sanjibdevnath/mcp-excalidraw-local
|
||||
-- npx -y excalidraw-mcp-sentinel
|
||||
```
|
||||
|
||||
### Codex CLI
|
||||
@@ -250,7 +263,7 @@ Add to `~/.codex/mcp.json`:
|
||||
"mcpServers": {
|
||||
"excalidraw-canvas": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@sanjibdevnath/mcp-excalidraw-local"],
|
||||
"args": ["-y", "excalidraw-mcp-sentinel"],
|
||||
"env": {
|
||||
"CANVAS_PORT": "3000"
|
||||
}
|
||||
@@ -288,14 +301,14 @@ Already installed a previous version? The interactive update wizard is the easie
|
||||
### Interactive Update (recommended)
|
||||
|
||||
```bash
|
||||
npx @sanjibdevnath/mcp-excalidraw-local@latest update
|
||||
npx excalidraw-mcp-sentinel@latest update
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>Example session</summary>
|
||||
|
||||
```
|
||||
$ npx @sanjibdevnath/mcp-excalidraw-local@latest update
|
||||
$ npx excalidraw-mcp-sentinel@latest update
|
||||
|
||||
Excalidraw MCP — Update v1.2.0
|
||||
|
||||
@@ -333,7 +346,7 @@ If you prefer to update manually, follow the steps for your installation method,
|
||||
|
||||
#### npx users
|
||||
|
||||
If your MCP config uses `npx -y @sanjibdevnath/mcp-excalidraw-local`, npx caches the package locally and won't automatically fetch new versions.
|
||||
If your MCP config uses `npx -y excalidraw-mcp-sentinel`, npx caches the package locally and won't automatically fetch new versions.
|
||||
|
||||
**Option A — Clear the cache (one-time):**
|
||||
```bash
|
||||
@@ -349,7 +362,7 @@ Update the `args` in your MCP config to include `@latest`:
|
||||
"mcpServers": {
|
||||
"excalidraw-canvas": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@sanjibdevnath/mcp-excalidraw-local@latest"],
|
||||
"args": ["-y", "excalidraw-mcp-sentinel@latest"],
|
||||
"env": { "CANVAS_PORT": "3000" }
|
||||
}
|
||||
}
|
||||
@@ -370,8 +383,8 @@ npm run build
|
||||
#### Docker users
|
||||
|
||||
```bash
|
||||
docker pull sanjibdevnath/mcp-excalidraw-local:latest
|
||||
docker pull sanjibdevnath/mcp-excalidraw-local-canvas:latest
|
||||
docker pull celstnblacc/excalidraw-mcp-sentinel:latest
|
||||
docker pull celstnblacc/excalidraw-mcp-sentinel-canvas:latest
|
||||
```
|
||||
|
||||
Then recreate your containers (`docker compose up -d` or `docker run` again).
|
||||
@@ -391,7 +404,7 @@ cp -R skills/excalidraw-skill ~/.claude/skills/excalidraw-skill
|
||||
curl -s http://localhost:3000/health
|
||||
|
||||
# Or check the installed package version
|
||||
npx @sanjibdevnath/mcp-excalidraw-local --version
|
||||
npx excalidraw-mcp-sentinel --version
|
||||
```
|
||||
|
||||
## How We Differ from the Official Excalidraw MCP
|
||||
@@ -449,6 +462,31 @@ This fork extends [yctimlin/mcp_excalidraw](https://github.com/yctimlin/mcp_exca
|
||||
| `EXCALIDRAW_DB_PATH` | Path to the SQLite database file | `~/.excalidraw-mcp/excalidraw.db` |
|
||||
| `EXCALIDRAW_EXPORT_DIR` | Allowed directory for file exports | `process.cwd()` |
|
||||
| `EXPRESS_SERVER_URL` | Canvas server URL (only if running canvas separately) | `http://localhost:3000` |
|
||||
| `EXCALIDRAW_API_KEY` | Shared secret for API key auth on all `/api/*` routes. When unset, auth is disabled (dev mode). | _(unset — auth off)_ |
|
||||
| `ALLOWED_ORIGINS` | Comma-separated list of allowed CORS + WebSocket origins | `http://localhost:3000,http://127.0.0.1:3000` |
|
||||
| `EXCALIDRAW_RATE_LIMIT_GENERAL_MAX` | Override the general API rate-limit ceiling (requests per 15-minute window) | `100` |
|
||||
| `EXCALIDRAW_RATE_LIMIT_DESTRUCTIVE_MAX` | Override the destructive-operation rate-limit ceiling (requests per 1-minute window) | `10` |
|
||||
| `EXCALIDRAW_RATE_LIMIT_WRITE_BURST_MAX` | Override the sync write-burst rate-limit ceiling (requests per 1-minute window) | `10` |
|
||||
|
||||
### Security configuration
|
||||
|
||||
**Enabling API key protection** (recommended for any network-accessible deployment):
|
||||
|
||||
```bash
|
||||
EXCALIDRAW_API_KEY=your-secret-here node dist/server.js
|
||||
```
|
||||
|
||||
All requests to `/api/*` must then include the header `X-API-Key: your-secret-here`. The `/health` endpoint is always exempt.
|
||||
|
||||
When `EXCALIDRAW_API_KEY` is set, the browser canvas UI receives the key automatically: `GET /` injects `window.__EXCALIDRAW_API_KEY__` into the served HTML, so the browser's WebSocket `hello` message can include it without any manual configuration. The WebSocket handshake uses a challenge-response protocol: the server sends `{ type: "auth_required" }` immediately on connect, the client must respond with a `hello` message containing `{ apiKey: "<key>" }` within 5 seconds, or the connection is closed (code 4001).
|
||||
|
||||
**Restricting CORS origins** (e.g. if your canvas UI is on a custom domain):
|
||||
|
||||
```bash
|
||||
ALLOWED_ORIGINS=https://canvas.example.com,http://localhost:3000 node dist/server.js
|
||||
```
|
||||
|
||||
This controls both REST CORS responses and WebSocket `Origin` verification. Requests with no `Origin` header (MCP stdio, curl, server-side tools) are always allowed.
|
||||
|
||||
## Multi-Tenancy (Workspaces)
|
||||
|
||||
@@ -478,7 +516,7 @@ This repo includes a skill at `skills/excalidraw-skill/` that provides:
|
||||
The easiest way to install the skill:
|
||||
|
||||
```bash
|
||||
npx @sanjibdevnath/mcp-excalidraw-local setup
|
||||
npx excalidraw-mcp-sentinel setup
|
||||
```
|
||||
|
||||
The wizard detects your installed agents and lets you choose which ones get the skill.
|
||||
@@ -504,8 +542,8 @@ cp -R skills/excalidraw-skill ~/.codex/skills/excalidraw-skill
|
||||
|---|---|
|
||||
| **Element CRUD** | `create_element`, `get_element`, `update_element`, `delete_element`, `query_elements`, `batch_create_elements`, `duplicate_elements` |
|
||||
| **Layout** | `align_elements`, `distribute_elements`, `group_elements`, `ungroup_elements`, `lock_elements`, `unlock_elements` |
|
||||
| **Scene Awareness** | `describe_scene`, `get_canvas_screenshot` |
|
||||
| **File I/O** | `export_scene`, `import_scene`, `export_to_image`, `export_to_excalidraw_url`, `create_from_mermaid` |
|
||||
| **Scene Awareness** | `describe_scene`, `get_canvas_screenshot` ⚠️ |
|
||||
| **File I/O** | `export_scene`, `import_scene`, `export_to_image` ⚠️, `export_to_excalidraw_url`, `create_from_mermaid` |
|
||||
| **State Management** | `clear_canvas`, `snapshot_scene`, `restore_snapshot` |
|
||||
| **Viewport** | `set_viewport` |
|
||||
| **Design Guide** | `read_diagram_guide` |
|
||||
@@ -516,6 +554,8 @@ cp -R skills/excalidraw-skill ~/.codex/skills/excalidraw-skill
|
||||
|
||||
Full schemas are discoverable via `tools/list` or in `skills/excalidraw-skill/references/cheatsheet.md`.
|
||||
|
||||
> ⚠️ **Requires open browser:** `get_canvas_screenshot` and `export_to_image` rely on the frontend rendering pipeline. The canvas UI must be open in a browser tab at `http://localhost:3000` for these tools to work. They return HTTP 503 if no browser is connected.
|
||||
|
||||
## Testing
|
||||
|
||||
### Health check
|
||||
@@ -562,7 +602,7 @@ This is the most common installation issue. `better-sqlite3` is a native Node.js
|
||||
```
|
||||
3. Or run the setup wizard which handles this automatically:
|
||||
```bash
|
||||
npx @sanjibdevnath/mcp-excalidraw-local setup
|
||||
npx excalidraw-mcp-sentinel setup
|
||||
```
|
||||
|
||||
### EADDRINUSE (port already in use)
|
||||
@@ -592,7 +632,7 @@ node dist/index.js # restart
|
||||
|
||||
### NVM / path issues with npx
|
||||
|
||||
**Symptom:** `npx @sanjibdevnath/mcp-excalidraw-local` hangs or uses the wrong Node version.
|
||||
**Symptom:** `npx excalidraw-mcp-sentinel` hangs or uses the wrong Node version.
|
||||
|
||||
**Fix:**
|
||||
```bash
|
||||
@@ -612,7 +652,7 @@ Then use the full path in your MCP config:
|
||||
"mcpServers": {
|
||||
"excalidraw-canvas": {
|
||||
"command": "/Users/you/.nvm/versions/node/v22.12.0/bin/npx",
|
||||
"args": ["-y", "@sanjibdevnath/mcp-excalidraw-local"],
|
||||
"args": ["-y", "excalidraw-mcp-sentinel"],
|
||||
"env": { "CANVAS_PORT": "3000" }
|
||||
}
|
||||
}
|
||||
@@ -661,20 +701,37 @@ The canvas server exposes a REST API alongside the WebSocket interface:
|
||||
|
||||
| Method | Endpoint | Description |
|
||||
|--------|----------|-------------|
|
||||
| GET | `/health` | Health check |
|
||||
| GET | `/health` | Health check (auth-exempt) |
|
||||
| GET | `/api/elements` | List all elements |
|
||||
| POST | `/api/elements` | Create an element |
|
||||
| GET | `/api/elements/search` | Search elements (`?q=term` for FTS, `?type=rectangle` for filter) |
|
||||
| GET | `/api/elements/:id` | Get element by ID |
|
||||
| PUT | `/api/elements/:id` | Update an element |
|
||||
| DELETE | `/api/elements/:id` | Delete an element |
|
||||
| DELETE | `/api/elements/clear` | Clear all elements |
|
||||
| POST | `/api/elements/sync` | Sync all elements (bulk upsert) |
|
||||
| DELETE | `/api/elements/clear` | Clear all elements (requires `?confirm=true`) |
|
||||
| POST | `/api/elements/batch` | Batch create elements |
|
||||
| POST | `/api/elements/from-mermaid` | Convert Mermaid diagram and broadcast to canvas |
|
||||
| POST | `/api/elements/sync` | Bulk-replace all elements (canvas → server) |
|
||||
| POST | `/api/elements/sync/v2` | Delta sync (changes since `lastSyncVersion`) |
|
||||
| GET | `/api/sync/version` | Current sync version for a project |
|
||||
| GET | `/api/sync/status` | Sync status (element count, memory usage) |
|
||||
| GET | `/api/files` | List image files (in-memory) |
|
||||
| POST | `/api/files` | Add image files |
|
||||
| DELETE | `/api/files/:id` | Delete an image file |
|
||||
| POST | `/api/export/image` | Request image export (requires open browser tab) |
|
||||
| POST | `/api/export/image/result` | Deliver export result from frontend |
|
||||
| POST | `/api/viewport` | Set canvas viewport (requires open browser tab) |
|
||||
| POST | `/api/viewport/result` | Deliver viewport result from frontend |
|
||||
| POST | `/api/snapshots` | Save a named snapshot |
|
||||
| GET | `/api/snapshots` | List snapshots |
|
||||
| GET | `/api/snapshots/:name` | Get snapshot by name |
|
||||
| GET | `/api/tenants` | List all tenants |
|
||||
| GET | `/api/tenant/active` | Get the active tenant |
|
||||
| PUT | `/api/tenant/active` | Set the active tenant |
|
||||
| GET | `/api/settings/:key` | Read a setting |
|
||||
| PUT | `/api/settings/:key` | Write a setting |
|
||||
|
||||
All endpoints accept an `X-Tenant-Id` header for per-request tenant scoping.
|
||||
All endpoints accept an `X-Tenant-Id` header for per-request tenant scoping. When `EXCALIDRAW_API_KEY` is set, all `/api/*` endpoints require `X-API-Key: <key>` (see [Security configuration](#security-configuration)).
|
||||
|
||||
## Credits
|
||||
|
||||
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
# Security
|
||||
|
||||
## Threat Model
|
||||
|
||||
This server is designed for **local and self-hosted use** — it runs on the same machine as your AI agent and browser. The primary threat surface is:
|
||||
|
||||
1. A malicious website making cross-origin requests to the canvas API (CSRF / drive-by reads or writes).
|
||||
2. A compromised or untrusted network exposing the canvas port to other hosts.
|
||||
3. Malicious input (oversized payloads, prototype pollution, injection) reaching route handlers.
|
||||
|
||||
The threat model does **not** cover:
|
||||
- An attacker with local OS access (they can read the SQLite file directly).
|
||||
- Server-side request forgery from within the canvas server itself.
|
||||
|
||||
---
|
||||
|
||||
## Mitigations
|
||||
|
||||
### CORS — `corsMiddleware` (`src/security.ts`)
|
||||
|
||||
Restricts cross-origin requests to an explicit allowlist (`ALLOWED_ORIGINS` env var, defaults to `localhost:3000` / `127.0.0.1:3000`). Requests with no `Origin` header (MCP stdio, curl, same-origin) are always allowed.
|
||||
|
||||
### WebSocket origin check — `verifyWsClient` (`src/security.ts`)
|
||||
|
||||
WebSocket upgrades are verified against the same allowlist before the connection is established. Rejects browser-originated connections from unlisted origins.
|
||||
|
||||
### WebSocket auth challenge-response
|
||||
|
||||
When `EXCALIDRAW_API_KEY` is set, the server immediately sends `{ type: "auth_required" }` after each new WebSocket connection. The client must respond with a `hello` message containing `{ type: "hello", apiKey: "<key>", ... }` within 5 seconds. If the key is missing, wrong, or the timeout fires, the server closes the connection with close code 4001. All other message types are silently dropped until auth succeeds. When auth is disabled, the `hello` handshake proceeds without key validation.
|
||||
|
||||
### Auth bootstrap — `GET /` key injection
|
||||
|
||||
When `EXCALIDRAW_API_KEY` is set, `GET /` injects `<script>window.__EXCALIDRAW_API_KEY__=…</script>` into the served HTML before `</head>`. The browser canvas reads this value at startup and includes it in the WebSocket `hello` message automatically, so users don't need to configure the key in the browser separately. The value is JSON-encoded with `<` escaped to `\u003c` to prevent script injection.
|
||||
|
||||
### API key auth — `apiKeyAuth` (`src/security.ts`)
|
||||
|
||||
When `EXCALIDRAW_API_KEY` is set, all `/api/*` routes require the header `X-API-Key: <key>`. Disabled by default for backward compatibility and zero-config local use. The `/health` endpoint is always exempt.
|
||||
|
||||
### Security headers — `helmetMiddleware` (`src/security.ts`)
|
||||
|
||||
Sets `X-Content-Type-Options: nosniff`, `X-Frame-Options`, `X-DNS-Prefetch-Control`, and removes `X-Powered-By`. CSP and COEP are intentionally disabled to allow Excalidraw's React bundle (inline scripts/styles).
|
||||
|
||||
### Rate limiting — `generalRateLimit` / `destructiveRateLimit` / `writeBurstLimit` (`src/security.ts`)
|
||||
|
||||
Three limiters apply, all returning `RateLimit-*` headers (draft-7) so clients can self-throttle:
|
||||
|
||||
| Limiter | Applied to | Default | Override env var |
|
||||
|---------|-----------|---------|-----------------|
|
||||
| `generalRateLimit` | All `/api/*` routes | 100 req / 15 min | `EXCALIDRAW_RATE_LIMIT_GENERAL_MAX` |
|
||||
| `destructiveRateLimit` | `DELETE /api/elements/clear` | 10 req / 1 min | `EXCALIDRAW_RATE_LIMIT_DESTRUCTIVE_MAX` |
|
||||
| `writeBurstLimit` | `POST /api/elements/sync`, `POST /api/elements/sync/v2` | 10 req / 1 min | `EXCALIDRAW_RATE_LIMIT_WRITE_BURST_MAX` |
|
||||
|
||||
Ceilings are read from env vars at server start. The E2E test harness sets them to high values via `playwright.config.ts` so tests are not self-throttled.
|
||||
|
||||
### Confirmation guard — `requireConfirm` (`src/security.ts`)
|
||||
|
||||
The `DELETE /api/elements/clear` endpoint requires `?confirm=true`. Prevents accidental or CSRF-triggered canvas wipes.
|
||||
|
||||
### Body size limits (`src/server.ts`)
|
||||
|
||||
- Default body limit: **100 KB** (standard API requests).
|
||||
- Batch/sync endpoints: **5 MB** (element arrays and sync payloads).
|
||||
- Oversized payloads return `413 Payload Too Large`.
|
||||
|
||||
### Prototype pollution guard — `sanitizeBody` (`src/security.ts`)
|
||||
|
||||
Rejects any request body containing `__proto__`, `constructor`, or `prototype` as object keys. Returns `400 Bad Request` before any route handler sees the data.
|
||||
|
||||
### Search query sanitization — `sanitizeSearchQuery` (`src/security.ts`)
|
||||
|
||||
`GET /api/elements/search?q=…` passes the query through `sanitizeSearchQuery` before handing it to the SQLite FTS5 engine. The function rejects queries that contain FTS5 operators (`AND`, `OR`, `NOT`, `NEAR/N`), double-quote quoting constructs, or special characters (`*`, `(`, `)`, `{`, `}`, `^`). This prevents malformed FTS5 syntax from bubbling up as SQLite parse errors and closes a narrow injection surface into the FTS virtual table.
|
||||
|
||||
### Mermaid input validation — `validateMermaidInput` (`src/security.ts`)
|
||||
|
||||
- Diagram string: max **50 KB** (prevents DoS via large Mermaid parse).
|
||||
- Config object: max **10 keys** (prevents unbounded config expansion).
|
||||
|
||||
### Error handling (`src/server.ts`)
|
||||
|
||||
The global error handler never exposes stack traces, file paths, or `node_modules` references in responses. 500 errors return the generic message `"Internal server error"`. Non-500 errors surface the error message only.
|
||||
|
||||
### Docker host binding (`Dockerfile.canvas`, `docker-compose.yml`)
|
||||
|
||||
`HOST=0.0.0.0` inside Docker is intentional: the container binds all interfaces, but the port is only reachable via the published port mapping. For local non-Docker use, the server defaults to `127.0.0.1` (loopback only).
|
||||
|
||||
---
|
||||
|
||||
## Pinned Dependencies
|
||||
|
||||
Security-critical packages are pinned to exact versions (no `^` range) to prevent silent upgrades introducing regressions:
|
||||
|
||||
| Package | Reason |
|
||||
|---------|--------|
|
||||
| `helmet` | Security headers — pin to known-good config |
|
||||
| `express-rate-limit` | Rate limiter — header format changes between major versions |
|
||||
| `cors` | CORS policy enforcement |
|
||||
| `express` | HTTP server — patch releases may change middleware behavior |
|
||||
| `ws` | WebSocket server — security patches applied selectively |
|
||||
| `better-sqlite3` | Native module — ABI compatibility with pinned Node.js |
|
||||
| `zod` | Input validation — schema breaking changes between minors |
|
||||
| `@modelcontextprotocol/sdk` | Protocol — pin to tested version |
|
||||
|
||||
---
|
||||
|
||||
## Reporting Vulnerabilities
|
||||
|
||||
Open an issue in the project repository. For sensitive disclosures, contact the maintainer directly via GitHub.
|
||||
|
||||
---
|
||||
|
||||
## Known Limitations
|
||||
|
||||
- **No HTTPS**: The canvas server speaks plain HTTP. Use a reverse proxy (nginx, Caddy) with TLS for any non-localhost deployment.
|
||||
- **Single shared API key**: There is no per-user or per-tenant auth. The key protects the entire API surface equally.
|
||||
- **Rate limits are in-memory**: They reset on process restart and are not shared across multiple server instances.
|
||||
- **SQLite is not encrypted**: The database file is stored in plaintext. Apply OS-level encryption if needed.
|
||||
@@ -2,7 +2,7 @@
|
||||
"mcpServers": {
|
||||
"excalidraw-canvas": {
|
||||
"command": "node",
|
||||
"args": ["/absolute/path/to/mcp-excalidraw-local/dist/index.js"],
|
||||
"args": ["/absolute/path/to/excalidraw-mcp-sentinel/dist/index.js"],
|
||||
"env": {
|
||||
"CANVAS_PORT": "3000"
|
||||
}
|
||||
|
||||
+20
-2
@@ -15,15 +15,21 @@ services:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile.canvas
|
||||
image: sanjibdevnath/mcp-excalidraw-local-canvas:latest
|
||||
image: celstnblacc/excalidraw-mcp-sentinel-canvas:latest
|
||||
container_name: mcp-excalidraw-canvas
|
||||
ports:
|
||||
- "3000:3000"
|
||||
environment:
|
||||
- NODE_ENV=production
|
||||
- PORT=3000
|
||||
# HOST=0.0.0.0 is intentional in Docker — the container's port is
|
||||
# exposed only via the published port mapping above. For local dev
|
||||
# without Docker, the default is localhost (set in src/server.ts).
|
||||
- HOST=0.0.0.0
|
||||
- DEBUG=false
|
||||
# Optional: set to enable API key auth on all /api/* routes.
|
||||
# Must match EXCALIDRAW_API_KEY in the mcp service below so inter-service calls succeed.
|
||||
- EXCALIDRAW_API_KEY=${EXCALIDRAW_API_KEY:-}
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
test: ["CMD", "node", "-e", "require('http').get('http://localhost:3000/health', (r) => process.exit(r.statusCode === 200 ? 0 : 1))"]
|
||||
@@ -31,6 +37,11 @@ services:
|
||||
timeout: 10s
|
||||
retries: 3
|
||||
start_period: 40s
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '1.0'
|
||||
memory: 512M
|
||||
networks:
|
||||
- mcp-network
|
||||
|
||||
@@ -40,7 +51,7 @@ services:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
image: sanjibdevnath/mcp-excalidraw-local:latest
|
||||
image: celstnblacc/excalidraw-mcp-sentinel:latest
|
||||
container_name: mcp-excalidraw-mcp
|
||||
stdin_open: true
|
||||
tty: true
|
||||
@@ -49,9 +60,16 @@ services:
|
||||
- EXPRESS_SERVER_URL=http://canvas:3000
|
||||
- ENABLE_CANVAS_SYNC=true
|
||||
- DEBUG=false
|
||||
# Must match canvas EXCALIDRAW_API_KEY so inter-service sync calls are authenticated.
|
||||
- EXCALIDRAW_API_KEY=${EXCALIDRAW_API_KEY:-}
|
||||
depends_on:
|
||||
canvas:
|
||||
condition: service_healthy
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: '0.5'
|
||||
memory: 256M
|
||||
networks:
|
||||
- mcp-network
|
||||
profiles:
|
||||
|
||||
+101
-48
@@ -53,11 +53,21 @@ interface TenantInfo {
|
||||
workspace_path: string;
|
||||
}
|
||||
|
||||
declare global {
|
||||
interface Window {
|
||||
__EXCALIDRAW_API_KEY__?: string;
|
||||
}
|
||||
}
|
||||
|
||||
const WS_AUTH_CLOSE_CODE = 4001
|
||||
const browserApiKey = typeof window !== 'undefined' ? window.__EXCALIDRAW_API_KEY__ : undefined
|
||||
|
||||
function App(): JSX.Element {
|
||||
const [excalidrawAPI, setExcalidrawAPI] = useState<ExcalidrawAPIRefValue | null>(null)
|
||||
const excalidrawAPIRef = useRef<ExcalidrawAPIRefValue | null>(null)
|
||||
const [isConnected, setIsConnected] = useState<boolean>(false)
|
||||
const websocketRef = useRef<WebSocket | null>(null)
|
||||
const reconnectEnabledRef = useRef<boolean>(true)
|
||||
|
||||
// Sync state
|
||||
const [syncStatus, setSyncStatus] = useState<SyncStatus>('idle')
|
||||
@@ -101,6 +111,7 @@ function App(): JSX.Element {
|
||||
}
|
||||
const tid = activeTenantIdRef.current
|
||||
if (tid) headers['X-Tenant-Id'] = tid
|
||||
if (browserApiKey) headers['X-API-Key'] = browserApiKey
|
||||
return headers
|
||||
}
|
||||
|
||||
@@ -244,6 +255,9 @@ function App(): JSX.Element {
|
||||
}
|
||||
|
||||
const connectWebSocket = (): void => {
|
||||
if (!reconnectEnabledRef.current) {
|
||||
return
|
||||
}
|
||||
if (websocketRef.current && websocketRef.current.readyState === WebSocket.OPEN) {
|
||||
return
|
||||
}
|
||||
@@ -274,7 +288,7 @@ function App(): JSX.Element {
|
||||
setIsConnected(false)
|
||||
|
||||
// Reconnect after 3 seconds if not a clean close
|
||||
if (event.code !== 1000) {
|
||||
if (event.code !== 1000 && event.code !== WS_AUTH_CLOSE_CODE && reconnectEnabledRef.current) {
|
||||
setTimeout(connectWebSocket, 3000)
|
||||
}
|
||||
}
|
||||
@@ -285,10 +299,13 @@ function App(): JSX.Element {
|
||||
}
|
||||
}
|
||||
|
||||
const sendHello = (tenantId: string): void => {
|
||||
const sendHello = (tenantId?: string): void => {
|
||||
const ws = websocketRef.current
|
||||
if (!ws || ws.readyState !== WebSocket.OPEN) return
|
||||
ws.send(JSON.stringify({ type: 'hello', tenantId }))
|
||||
const message: Record<string, string> = { type: 'hello' }
|
||||
if (tenantId) message.tenantId = tenantId
|
||||
if (browserApiKey) message.apiKey = browserApiKey
|
||||
ws.send(JSON.stringify(message))
|
||||
}
|
||||
|
||||
const sendAck = (msgId: string | undefined, status: 'applied' | 'partial' | 'failed', elementCount?: number, expectedCount?: number): void => {
|
||||
@@ -358,6 +375,85 @@ function App(): JSX.Element {
|
||||
}
|
||||
|
||||
const handleWebSocketMessage = async (data: WebSocketMessage): Promise<void> => {
|
||||
switch (data.type) {
|
||||
case 'auth_required':
|
||||
sendHello(activeTenantIdRef.current ?? undefined)
|
||||
return
|
||||
|
||||
case 'auth_failed':
|
||||
reconnectEnabledRef.current = false
|
||||
showToast('Authentication failed - check EXCALIDRAW_API_KEY', 4000)
|
||||
if (websocketRef.current?.readyState === WebSocket.OPEN) {
|
||||
websocketRef.current.close(WS_AUTH_CLOSE_CODE, 'Authentication failed')
|
||||
}
|
||||
return
|
||||
|
||||
case 'error':
|
||||
if (typeof data.message === 'string' && data.message) {
|
||||
showToast(data.message, 4000)
|
||||
}
|
||||
return
|
||||
|
||||
case 'tenant_switched': {
|
||||
console.log('Tenant switched:', data.tenant)
|
||||
if (!data.tenant) return
|
||||
const incoming = data.tenant as TenantInfo
|
||||
sendHello(incoming.id)
|
||||
if (incoming.id !== activeTenantIdRef.current) {
|
||||
activeTenantIdRef.current = incoming.id
|
||||
setActiveTenant(incoming)
|
||||
const api = excalidrawAPIRef.current
|
||||
if (!api) return
|
||||
api.updateScene({
|
||||
elements: [],
|
||||
captureUpdate: CaptureUpdateAction.NEVER
|
||||
})
|
||||
lastSyncedHashRef.current = ''
|
||||
loadExistingElements()
|
||||
} else {
|
||||
setActiveTenant(incoming)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
case 'hello_ack': {
|
||||
console.log('Hello acknowledged by server:', data.tenantId, data.projectId)
|
||||
if (data.tenant) {
|
||||
const incoming = data.tenant as TenantInfo
|
||||
activeTenantIdRef.current = incoming.id
|
||||
setActiveTenant(incoming)
|
||||
} else if (typeof data.tenantId === 'string') {
|
||||
activeTenantIdRef.current = data.tenantId
|
||||
}
|
||||
|
||||
const api = excalidrawAPIRef.current
|
||||
if (!api) return
|
||||
|
||||
if (Array.isArray(data.elements) && data.elements.length > 0) {
|
||||
const cleanedElements = data.elements.map(cleanElementForExcalidraw)
|
||||
const validatedElements = validateAndFixBindings(cleanedElements)
|
||||
const convertedElements = convertElementsPreservingImageProps(validatedElements)
|
||||
api.updateScene({
|
||||
elements: convertedElements,
|
||||
captureUpdate: CaptureUpdateAction.NEVER
|
||||
})
|
||||
const helloBaseline = new Map<string, any>()
|
||||
for (const el of data.elements) {
|
||||
helloBaseline.set(el.id, el)
|
||||
}
|
||||
lastSyncedElementsRef.current = helloBaseline
|
||||
} else if (Array.isArray(data.elements)) {
|
||||
api.updateScene({
|
||||
elements: [],
|
||||
captureUpdate: CaptureUpdateAction.NEVER
|
||||
})
|
||||
lastSyncedElementsRef.current = new Map()
|
||||
lastSyncedHashRef.current = ''
|
||||
}
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// Gap detection (Task 12): if a message carries sync_version, check for gaps
|
||||
if (data.sync_version !== undefined && typeof data.sync_version === 'number') {
|
||||
const expected = lastReceivedSyncVersionRef.current + 1
|
||||
@@ -714,46 +810,6 @@ function App(): JSX.Element {
|
||||
case 'file_deleted':
|
||||
break
|
||||
|
||||
case 'tenant_switched':
|
||||
console.log('Tenant switched:', data.tenant)
|
||||
if (data.tenant) {
|
||||
const incoming = data.tenant as TenantInfo
|
||||
// Send hello to register WS connection under the correct tenant scope
|
||||
sendHello(incoming.id)
|
||||
if (incoming.id !== activeTenantIdRef.current) {
|
||||
activeTenantIdRef.current = incoming.id
|
||||
setActiveTenant(incoming)
|
||||
api.updateScene({
|
||||
elements: [],
|
||||
captureUpdate: CaptureUpdateAction.NEVER
|
||||
})
|
||||
lastSyncedHashRef.current = ''
|
||||
loadExistingElements()
|
||||
} else {
|
||||
setActiveTenant(incoming)
|
||||
}
|
||||
}
|
||||
break
|
||||
|
||||
case 'hello_ack':
|
||||
console.log('Hello acknowledged by server:', data.tenantId, data.projectId)
|
||||
if (data.elements && Array.isArray(data.elements) && data.elements.length > 0) {
|
||||
const converted = convertToExcalidrawElements(data.elements)
|
||||
api.updateScene({
|
||||
elements: converted,
|
||||
captureUpdate: CaptureUpdateAction.NEVER
|
||||
})
|
||||
// Update sync baseline for deletion detection
|
||||
const helloBaseline = new Map<string, any>()
|
||||
for (const el of data.elements) {
|
||||
helloBaseline.set(el.id, el)
|
||||
}
|
||||
lastSyncedElementsRef.current = helloBaseline
|
||||
} else if (data.elements && data.elements.length === 0) {
|
||||
lastSyncedElementsRef.current = new Map()
|
||||
}
|
||||
break
|
||||
|
||||
default:
|
||||
console.log('Unknown WebSocket message type:', data.type)
|
||||
}
|
||||
@@ -875,10 +931,7 @@ function App(): JSX.Element {
|
||||
|
||||
// Load elements for the newly-active tenant
|
||||
const elemRes = await fetch('/api/elements', {
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Tenant-Id': tenantId
|
||||
}
|
||||
headers: tenantHeaders({ 'X-Tenant-Id': tenantId })
|
||||
})
|
||||
const result: ApiResponse = await elemRes.json()
|
||||
if (result.success && result.elements && result.elements.length > 0) {
|
||||
@@ -996,7 +1049,7 @@ function App(): JSX.Element {
|
||||
|
||||
// Load "skip confirm" preference from backend on mount
|
||||
useEffect(() => {
|
||||
fetch('/api/settings/clear_canvas_skip_confirm')
|
||||
fetch('/api/settings/clear_canvas_skip_confirm', { headers: tenantHeaders() })
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
if (data.value === 'true') setClearSkipConfirm(true)
|
||||
|
||||
Generated
+400
-339
File diff suppressed because it is too large
Load Diff
+22
-14
@@ -1,11 +1,11 @@
|
||||
{
|
||||
"name": "@sanjibdevnath/mcp-excalidraw-local",
|
||||
"version": "1.6.2",
|
||||
"description": "Fully local MCP server for Excalidraw with SQLite persistence, multi-tenancy, auto-sync, real-time canvas, and 32 tools",
|
||||
"name": "excalidraw-mcp-sentinel",
|
||||
"version": "1.0.1",
|
||||
"description": "Hardened, self-hosted Excalidraw MCP server with SQLite persistence, multi-tenancy, auto-sync, security middleware, and 369 tests",
|
||||
"main": "dist/index.js",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
"mcp-excalidraw-local": "dist/index.js"
|
||||
"excalidraw-mcp-sentinel": "dist/index.js"
|
||||
},
|
||||
"scripts": {
|
||||
"start": "npm run build:server && node dist/index.js",
|
||||
@@ -17,6 +17,7 @@
|
||||
"dev": "concurrently \"npm run dev:server\" \"vite\"",
|
||||
"dev:server": "npx tsc --watch",
|
||||
"production": "npm run build && npm run canvas",
|
||||
"postinstall": "npm rebuild better-sqlite3 --update-binary 2>/dev/null || true",
|
||||
"prepublishOnly": "npm run build",
|
||||
"setup": "node dist/index.js setup",
|
||||
"update": "node dist/index.js update",
|
||||
@@ -32,18 +33,20 @@
|
||||
"dependencies": {
|
||||
"@excalidraw/excalidraw": "^0.18.0",
|
||||
"@excalidraw/mermaid-to-excalidraw": "^1.1.3",
|
||||
"@modelcontextprotocol/sdk": "^1.26.0",
|
||||
"better-sqlite3": "^12.6.2",
|
||||
"cors": "^2.8.5",
|
||||
"@modelcontextprotocol/sdk": "1.26.0",
|
||||
"better-sqlite3": "12.6.2",
|
||||
"cors": "2.8.5",
|
||||
"dotenv": "^16.3.1",
|
||||
"express": "^4.18.2",
|
||||
"express": "4.22.1",
|
||||
"express-rate-limit": "8.3.1",
|
||||
"helmet": "8.1.0",
|
||||
"mermaid": "^11.12.1",
|
||||
"node-fetch": "^3.3.2",
|
||||
"react": "^18.3.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"winston": "^3.11.0",
|
||||
"ws": "^8.14.2",
|
||||
"zod": "^3.22.4",
|
||||
"ws": "8.20.0",
|
||||
"zod": "3.25.5",
|
||||
"zod-to-json-schema": "^3.22.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -82,9 +85,14 @@
|
||||
"local"
|
||||
],
|
||||
"author": {
|
||||
"name": "sanjibdevnathlabs"
|
||||
"name": "celstnblacc",
|
||||
"url": "https://github.com/celstnblacc"
|
||||
},
|
||||
"contributors": [
|
||||
{
|
||||
"name": "sanjibdevnathlabs",
|
||||
"url": "https://github.com/sanjibdevnathlabs"
|
||||
},
|
||||
{
|
||||
"name": "yctimlin",
|
||||
"email": "c22647809@gmail.com",
|
||||
@@ -94,11 +102,11 @@
|
||||
"license": "MIT",
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/sanjibdevnathlabs/mcp-excalidraw-local.git"
|
||||
"url": "https://github.com/celstnblacc/excalidraw-mcp-sentinel.git"
|
||||
},
|
||||
"homepage": "https://github.com/sanjibdevnathlabs/mcp-excalidraw-local#readme",
|
||||
"homepage": "https://github.com/celstnblacc/excalidraw-mcp-sentinel#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/sanjibdevnathlabs/mcp-excalidraw-local/issues"
|
||||
"url": "https://github.com/celstnblacc/excalidraw-mcp-sentinel/issues"
|
||||
},
|
||||
"pnpm": {
|
||||
"onlyBuiltDependencies": [
|
||||
|
||||
@@ -9,7 +9,7 @@ export default defineConfig({
|
||||
workers: 1,
|
||||
reporter: 'list',
|
||||
use: {
|
||||
baseURL: 'http://localhost:3100',
|
||||
baseURL: 'http://127.0.0.1:3100',
|
||||
trace: 'on-first-retry',
|
||||
},
|
||||
projects: [
|
||||
@@ -25,8 +25,12 @@ export default defineConfig({
|
||||
reuseExistingServer: !process.env.CI,
|
||||
env: {
|
||||
CANVAS_PORT: '3100',
|
||||
HOST: 'localhost',
|
||||
HOST: '127.0.0.1',
|
||||
EXCALIDRAW_DB_PATH: '/tmp/excalidraw-e2e-test.db',
|
||||
ALLOWED_ORIGINS: 'http://127.0.0.1:3100,http://localhost:3100,http://localhost:3000,http://127.0.0.1:3000',
|
||||
EXCALIDRAW_RATE_LIMIT_GENERAL_MAX: '10000',
|
||||
EXCALIDRAW_RATE_LIMIT_DESTRUCTIVE_MAX: '10000',
|
||||
EXCALIDRAW_RATE_LIMIT_WRITE_BURST_MAX: '10000',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
@@ -11,7 +11,7 @@ Run these checks **in order**:
|
||||
|
||||
1. **MCP Server** (best): If tools like `batch_create_elements` are available → use MCP mode.
|
||||
2. **REST API** (fallback): `curl -s http://localhost:3000/health` returns `{"status":"ok"}` → use REST API mode.
|
||||
3. **Nothing works**: Guide user to install (clone `sanjibdevnathlabs/mcp-excalidraw-local`, build, configure MCP).
|
||||
3. **Nothing works**: Guide user to install (clone `celstnblacc/excalidraw-mcp-sentinel`, build, configure MCP).
|
||||
|
||||
See `references/cheatsheet.md` for the full MCP-vs-REST mapping and REST API gotchas.
|
||||
|
||||
|
||||
@@ -512,6 +512,10 @@ export function getActiveTenant(): Tenant {
|
||||
return db.prepare('SELECT * FROM tenants WHERE id = ?').get(activeTenantId) as Tenant;
|
||||
}
|
||||
|
||||
export function getTenantById(id: string): Tenant | undefined {
|
||||
return db.prepare('SELECT * FROM tenants WHERE id = ?').get(id) as Tenant | undefined;
|
||||
}
|
||||
|
||||
export function getActiveTenantId(): string {
|
||||
return activeTenantId;
|
||||
}
|
||||
@@ -535,6 +539,12 @@ export function listProjects(): Project[] {
|
||||
return db.prepare('SELECT * FROM projects WHERE tenant_id = ? ORDER BY updated_at DESC').all(activeTenantId) as Project[];
|
||||
}
|
||||
|
||||
export function getProjectForTenant(projectId: string, tenantId: string): Project | undefined {
|
||||
return db.prepare(
|
||||
'SELECT * FROM projects WHERE id = ? AND tenant_id = ?'
|
||||
).get(projectId, tenantId) as Project | undefined;
|
||||
}
|
||||
|
||||
export function setActiveProject(id: string): void {
|
||||
const project = db.prepare('SELECT id, tenant_id FROM projects WHERE id = ?').get(id) as { id: string; tenant_id: string } | undefined;
|
||||
if (!project) throw new Error(`Project "${id}" not found`);
|
||||
|
||||
+7
-2
@@ -137,11 +137,16 @@ interface SyncResponse {
|
||||
}
|
||||
|
||||
function canvasHeaders(extra?: Record<string, string>): Record<string, string> {
|
||||
return {
|
||||
const headers: Record<string, string> = {
|
||||
'Content-Type': 'application/json',
|
||||
'X-Tenant-Id': dbGetActiveTenantId(),
|
||||
...extra
|
||||
};
|
||||
// Forward API key to canvas when auth is enabled — required for two-service
|
||||
// Docker deployments where canvas runs with EXCALIDRAW_API_KEY set.
|
||||
const apiKey = process.env.EXCALIDRAW_API_KEY;
|
||||
if (apiKey) headers['X-API-Key'] = apiKey;
|
||||
return headers;
|
||||
}
|
||||
|
||||
// Helper functions to sync with Express server (canvas)
|
||||
@@ -2918,7 +2923,7 @@ if (isMainModule()) {
|
||||
try {
|
||||
const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
|
||||
if (arg === '--help' || arg === '-h') {
|
||||
process.stdout.write(`${pkg.name} v${pkg.version}\n\nUsage:\n mcp-excalidraw-local Start MCP server (stdio transport)\n mcp-excalidraw-local setup Interactive setup wizard\n mcp-excalidraw-local update Update agent skills and MCP config\n mcp-excalidraw-local --help Show this help\n mcp-excalidraw-local --version Show version\n`);
|
||||
process.stdout.write(`${pkg.name} v${pkg.version}\n\nUsage:\n excalidraw-mcp-sentinel Start MCP server (stdio transport)\n excalidraw-mcp-sentinel setup Interactive setup wizard\n excalidraw-mcp-sentinel update Update agent skills and MCP config\n excalidraw-mcp-sentinel --help Show this help\n excalidraw-mcp-sentinel --version Show version\n`);
|
||||
} else {
|
||||
process.stdout.write(`${pkg.version}\n`);
|
||||
}
|
||||
|
||||
+213
@@ -0,0 +1,213 @@
|
||||
/**
|
||||
* Security middleware for excalidraw-mcp-sentinel.
|
||||
*
|
||||
* All env vars are read at request/connection time (not at module init)
|
||||
* so that tests can mutate process.env between cases.
|
||||
*/
|
||||
|
||||
import cors from 'cors';
|
||||
import rateLimit from 'express-rate-limit';
|
||||
import helmet from 'helmet';
|
||||
import { timingSafeEqual } from 'crypto';
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { IncomingMessage } from 'http';
|
||||
|
||||
// ── Helpers ──────────────────────────────────────────────────────────────────
|
||||
|
||||
function getAllowedOrigins(): string[] {
|
||||
if (process.env.ALLOWED_ORIGINS) {
|
||||
return process.env.ALLOWED_ORIGINS.split(',').map((o) => o.trim()).filter(Boolean);
|
||||
}
|
||||
return ['http://localhost:3000', 'http://127.0.0.1:3000'];
|
||||
}
|
||||
|
||||
function getEnvInt(name: string, fallback: number): number {
|
||||
const value = process.env[name];
|
||||
if (!value) return fallback;
|
||||
const parsed = Number.parseInt(value, 10);
|
||||
return Number.isFinite(parsed) && parsed > 0 ? parsed : fallback;
|
||||
}
|
||||
|
||||
export function isAuthEnabled(): boolean {
|
||||
return !!process.env.EXCALIDRAW_API_KEY;
|
||||
}
|
||||
|
||||
export function validateApiKey(provided: string | string[] | undefined): boolean {
|
||||
const required = process.env.EXCALIDRAW_API_KEY;
|
||||
if (!required) return true;
|
||||
if (typeof provided !== 'string') return false;
|
||||
// Use timing-safe comparison to prevent timing-based key enumeration.
|
||||
const a = Buffer.from(provided);
|
||||
const b = Buffer.from(required);
|
||||
if (a.length !== b.length) return false;
|
||||
return timingSafeEqual(a, b);
|
||||
}
|
||||
|
||||
// ── Security Headers (helmet) ─────────────────────────────────────────────────
|
||||
// Sets X-Content-Type-Options, X-Frame-Options, X-DNS-Prefetch-Control, etc.
|
||||
// Disables X-Powered-By to avoid fingerprinting.
|
||||
// CSP is left permissive here (Excalidraw needs inline scripts/styles for React).
|
||||
export const helmetMiddleware = helmet({
|
||||
contentSecurityPolicy: false, // Excalidraw's React bundle needs inline evaluation
|
||||
crossOriginEmbedderPolicy: false, // Allow embedding Excalidraw assets
|
||||
});
|
||||
|
||||
// ── CORS ─────────────────────────────────────────────────────────────────────
|
||||
// Restrict to an explicit allowlist. `cors()` with no config defaults to
|
||||
// wildcard (*) which lets any website make cross-origin calls to the canvas
|
||||
// server — a security risk for local use.
|
||||
|
||||
export const corsMiddleware = cors({
|
||||
origin(origin, callback) {
|
||||
// No Origin header = curl / MCP stdio / same-origin request — always allow.
|
||||
if (!origin) return callback(null, true);
|
||||
if (getAllowedOrigins().includes(origin)) return callback(null, origin);
|
||||
// Deny: return false so cors does not set ACAO header.
|
||||
// The browser will block the response; the server stays available.
|
||||
return callback(null, false);
|
||||
},
|
||||
credentials: true,
|
||||
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
|
||||
allowedHeaders: ['Content-Type', 'X-Tenant-Id', 'X-API-Key'],
|
||||
});
|
||||
|
||||
// ── API Key Auth ──────────────────────────────────────────────────────────────
|
||||
// When EXCALIDRAW_API_KEY is not set, auth is disabled (dev / backward-compat mode).
|
||||
// Set the env var to protect all /api/* routes.
|
||||
// /health is exempt so monitoring tools work without credentials.
|
||||
|
||||
export function apiKeyAuth(req: Request, res: Response, next: NextFunction): void {
|
||||
// Auth disabled — pass through.
|
||||
if (!isAuthEnabled()) return next();
|
||||
|
||||
const provided = req.headers['x-api-key'];
|
||||
if (!validateApiKey(provided)) {
|
||||
res.status(401).json({ success: false, error: 'Unauthorized' });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
// ── Prototype Pollution Guard ─────────────────────────────────────────────────
|
||||
// Strip (and reject) dangerous prototype-chain keys from req.body before any
|
||||
// route handler sees the data. These keys are safe in JSON.parse on modern V8
|
||||
// but can cause issues downstream with Object.assign / spread patterns.
|
||||
const DANGEROUS_KEYS = new Set(['__proto__', 'constructor', 'prototype']);
|
||||
|
||||
function hasDangerousKey(obj: unknown, depth = 0): boolean {
|
||||
if (depth > 10 || obj === null || typeof obj !== 'object') return false;
|
||||
for (const key of Object.keys(obj as object)) {
|
||||
if (DANGEROUS_KEYS.has(key)) return true;
|
||||
if (hasDangerousKey((obj as Record<string, unknown>)[key], depth + 1)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function sanitizeBody(req: Request, res: Response, next: NextFunction): void {
|
||||
if (req.body && typeof req.body === 'object' && hasDangerousKey(req.body)) {
|
||||
res.status(400).json({ success: false, error: 'Request body contains disallowed keys.' });
|
||||
return;
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
// ── Mermaid Input Validation ──────────────────────────────────────────────────
|
||||
const MAX_MERMAID_LENGTH = 50 * 1024; // 50 KB
|
||||
const MAX_MERMAID_CONFIG_KEYS = 10;
|
||||
|
||||
export function validateMermaidInput(req: Request, res: Response, next: NextFunction): void {
|
||||
const { mermaidDiagram, config } = req.body ?? {};
|
||||
|
||||
if (typeof mermaidDiagram === 'string' && mermaidDiagram.length > MAX_MERMAID_LENGTH) {
|
||||
res.status(400).json({ success: false, error: 'Mermaid diagram exceeds maximum allowed size (50 KB).' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (config !== undefined && config !== null && typeof config === 'object' && !Array.isArray(config)) {
|
||||
if (Object.keys(config as object).length > MAX_MERMAID_CONFIG_KEYS) {
|
||||
res.status(400).json({ success: false, error: `Mermaid config must not exceed ${MAX_MERMAID_CONFIG_KEYS} keys.` });
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
next();
|
||||
}
|
||||
|
||||
// ── Rate Limiting ─────────────────────────────────────────────────────────────
|
||||
// General limit for all /api routes.
|
||||
export const generalRateLimit = rateLimit({
|
||||
windowMs: 15 * 60 * 1000, // 15 minutes
|
||||
max: getEnvInt('EXCALIDRAW_RATE_LIMIT_GENERAL_MAX', 100),
|
||||
standardHeaders: 'draft-7',
|
||||
legacyHeaders: false,
|
||||
message: { success: false, error: 'Too many requests, please try again later.' },
|
||||
});
|
||||
|
||||
// Stricter limit for destructive clear operations.
|
||||
export const destructiveRateLimit = rateLimit({
|
||||
windowMs: 60 * 1000, // 1 minute
|
||||
max: getEnvInt('EXCALIDRAW_RATE_LIMIT_DESTRUCTIVE_MAX', 10),
|
||||
standardHeaders: 'draft-7',
|
||||
legacyHeaders: false,
|
||||
message: { success: false, error: 'Too many destructive operations, please slow down.' },
|
||||
});
|
||||
|
||||
// Stricter limit for write-heavy sync operations.
|
||||
export const writeBurstLimit = rateLimit({
|
||||
windowMs: 60 * 1000, // 1 minute
|
||||
max: getEnvInt('EXCALIDRAW_RATE_LIMIT_WRITE_BURST_MAX', 10),
|
||||
standardHeaders: 'draft-7',
|
||||
legacyHeaders: false,
|
||||
message: { success: false, error: 'Too many sync operations, please slow down.' },
|
||||
});
|
||||
|
||||
// ── Confirmation Guard ────────────────────────────────────────────────────────
|
||||
// Requires ?confirm=true on destructive REST endpoints.
|
||||
// Prevents accidental or CSRF-triggered data loss.
|
||||
export function requireConfirm(req: Request, res: Response, next: NextFunction): void {
|
||||
if (req.query['confirm'] !== 'true') {
|
||||
res.status(400).json({
|
||||
success: false,
|
||||
error: 'Add ?confirm=true to confirm this destructive operation.',
|
||||
});
|
||||
return;
|
||||
}
|
||||
next();
|
||||
}
|
||||
|
||||
// ── WebSocket Origin Check ────────────────────────────────────────────────────
|
||||
// Passed to WebSocketServer({ verifyClient }) at server init.
|
||||
// Reads allowed origins dynamically so env changes take effect without restart.
|
||||
|
||||
export function verifyWsClient(info: { req: IncomingMessage }): boolean {
|
||||
const origin = info.req.headers.origin;
|
||||
// No origin = non-browser client (MCP tool, curl) — allow.
|
||||
if (!origin) return true;
|
||||
return getAllowedOrigins().includes(origin);
|
||||
}
|
||||
|
||||
export class InvalidSearchQueryError extends Error {
|
||||
constructor() {
|
||||
super('Invalid search query');
|
||||
this.name = 'InvalidSearchQueryError';
|
||||
}
|
||||
}
|
||||
|
||||
export function sanitizeSearchQuery(query: string): string {
|
||||
const trimmed = query.trim();
|
||||
if (!trimmed) return trimmed;
|
||||
|
||||
// Keep search syntax simple and predictable by rejecting FTS operators
|
||||
// and quoting constructs that otherwise bubble SQLite parse errors.
|
||||
if (trimmed.includes('"')) {
|
||||
throw new InvalidSearchQueryError();
|
||||
}
|
||||
if (/\b(?:AND|OR|NOT|NEAR(?:\/\d+)?)\b/i.test(trimmed)) {
|
||||
throw new InvalidSearchQueryError();
|
||||
}
|
||||
if (/[*(){}^]/.test(trimmed)) {
|
||||
throw new InvalidSearchQueryError();
|
||||
}
|
||||
|
||||
return trimmed;
|
||||
}
|
||||
+246
-129
@@ -1,6 +1,6 @@
|
||||
import express, { type Application, Request, Response, NextFunction } from 'express';
|
||||
import cors from 'cors';
|
||||
import { WebSocketServer } from 'ws';
|
||||
import { helmetMiddleware, corsMiddleware, apiKeyAuth, verifyWsClient, generalRateLimit, destructiveRateLimit, writeBurstLimit, requireConfirm, sanitizeBody, validateMermaidInput, isAuthEnabled, validateApiKey, sanitizeSearchQuery, InvalidSearchQueryError } from './security.js';
|
||||
import { createServer } from 'http';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
BatchCreatedMessage,
|
||||
SyncStatusMessage,
|
||||
InitialElementsMessage,
|
||||
HelloMessage,
|
||||
Snapshot,
|
||||
normalizeFontFamily,
|
||||
ExcalidrawFile,
|
||||
@@ -27,7 +28,7 @@ import {
|
||||
BroadcastResult
|
||||
} from './types.js';
|
||||
import * as store from './db.js';
|
||||
import { initDb, listTenants as dbListTenants, getActiveTenant as dbGetActiveTenant, setActiveTenant as dbSetActiveTenant, getDefaultProjectForTenant, getCurrentSyncVersion, getChangesSince } from './db.js';
|
||||
import { initDb, listTenants as dbListTenants, getActiveTenant as dbGetActiveTenant, getTenantById, setActiveTenant as dbSetActiveTenant, getDefaultProjectForTenant, getProjectForTenant, getCurrentSyncVersion, getChangesSince } from './db.js';
|
||||
import { z } from 'zod';
|
||||
import WebSocket from 'ws';
|
||||
|
||||
@@ -39,17 +40,25 @@ const __dirname = path.dirname(__filename);
|
||||
|
||||
const app: Application = express();
|
||||
const httpServer = createServer(app);
|
||||
const wss = new WebSocketServer({ server: httpServer });
|
||||
const wss = new WebSocketServer({ server: httpServer, verifyClient: verifyWsClient });
|
||||
|
||||
// Middleware
|
||||
app.use(cors());
|
||||
app.use(express.json({ limit: '10mb' }));
|
||||
app.use(helmetMiddleware);
|
||||
app.use(corsMiddleware);
|
||||
app.use('/api', generalRateLimit);
|
||||
app.use('/api', apiKeyAuth);
|
||||
// Body parsing — path-specific limits applied in order (most-specific first).
|
||||
// batch/sync endpoints get 5 MB; everything else gets 100 KB.
|
||||
app.use('/api/elements/batch', express.json({ limit: '5mb' }));
|
||||
app.use('/api/elements/sync', express.json({ limit: '5mb' }));
|
||||
app.use(express.json({ limit: '100kb' }));
|
||||
app.use('/api', sanitizeBody);
|
||||
|
||||
// Serve static files from the build directory
|
||||
const staticDir = path.join(__dirname, '../dist');
|
||||
app.use(express.static(staticDir));
|
||||
app.use(express.static(staticDir, { index: false }));
|
||||
// Also serve frontend assets
|
||||
app.use(express.static(path.join(__dirname, '../dist/frontend')));
|
||||
app.use(express.static(path.join(__dirname, '../dist/frontend'), { index: false }));
|
||||
|
||||
// Resolve tenant from X-Tenant-Id header to a projectId override.
|
||||
// Returns undefined when header is absent (browser requests), falling back to global state.
|
||||
@@ -73,6 +82,113 @@ function resolveScope(req: Request): { tenantId: string; projectId: string } {
|
||||
return { tenantId: tenant.id, projectId };
|
||||
}
|
||||
|
||||
const WS_AUTH_CLOSE_CODE = 4001;
|
||||
const WS_AUTH_TIMEOUT_MS = 5000;
|
||||
const frontendHtmlPath = path.join(__dirname, '../dist/frontend/index.html');
|
||||
|
||||
function identifyConnection(ws: WebSocket, tenantId: string, projectId: string): void {
|
||||
if (wsToConnection.has(ws)) {
|
||||
moveConnection(ws, tenantId, projectId);
|
||||
return;
|
||||
}
|
||||
|
||||
registerConnection({
|
||||
ws,
|
||||
tenantId,
|
||||
projectId,
|
||||
connectedAt: Date.now(),
|
||||
identified: true,
|
||||
});
|
||||
}
|
||||
|
||||
function getAllFilesObject(): Record<string, ExcalidrawFile> {
|
||||
const result: Record<string, ExcalidrawFile> = {};
|
||||
for (const [id, file] of files) {
|
||||
result[id] = file;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function sendFilesAdded(ws: WebSocket): void {
|
||||
if (files.size === 0) return;
|
||||
ws.send(JSON.stringify({ type: 'files_added', files: getAllFilesObject() }));
|
||||
}
|
||||
|
||||
function sendSyncStatus(ws: WebSocket, projectId: string): void {
|
||||
const syncMessage: SyncStatusMessage = {
|
||||
type: 'sync_status',
|
||||
elementCount: store.getElementCount(projectId),
|
||||
timestamp: new Date().toISOString()
|
||||
};
|
||||
ws.send(JSON.stringify(syncMessage));
|
||||
}
|
||||
|
||||
function sendAuthlessInitialMessages(
|
||||
ws: WebSocket,
|
||||
tenant: { id: string; name: string; workspace_path: string },
|
||||
projectId: string
|
||||
): void {
|
||||
ws.send(JSON.stringify({
|
||||
type: 'tenant_switched',
|
||||
tenant: { id: tenant.id, name: tenant.name, workspace_path: tenant.workspace_path }
|
||||
}));
|
||||
|
||||
const initialMessage: InitialElementsMessage = {
|
||||
type: 'initial_elements',
|
||||
elements: store.getAllElements(projectId)
|
||||
};
|
||||
ws.send(JSON.stringify(initialMessage));
|
||||
|
||||
sendFilesAdded(ws);
|
||||
sendSyncStatus(ws, projectId);
|
||||
}
|
||||
|
||||
function sendHelloAck(
|
||||
ws: WebSocket,
|
||||
tenant: { id: string; name: string; workspace_path: string },
|
||||
projectId: string
|
||||
): void {
|
||||
ws.send(JSON.stringify({
|
||||
type: 'hello_ack',
|
||||
tenant: { id: tenant.id, name: tenant.name, workspace_path: tenant.workspace_path },
|
||||
tenantId: tenant.id,
|
||||
projectId,
|
||||
elements: store.getAllElements(projectId)
|
||||
}));
|
||||
}
|
||||
|
||||
function resolveHelloTenantAndProject(msg: HelloMessage):
|
||||
| { tenant: { id: string; name: string; workspace_path: string }; projectId: string }
|
||||
| { error: string } {
|
||||
let tenant = dbGetActiveTenant();
|
||||
|
||||
if (typeof msg.tenantId === 'string' && msg.tenantId.trim()) {
|
||||
const requestedTenant = getTenantById(msg.tenantId.trim());
|
||||
if (!requestedTenant) {
|
||||
return { error: 'Unknown tenant' };
|
||||
}
|
||||
tenant = requestedTenant;
|
||||
}
|
||||
|
||||
let projectId = getDefaultProjectForTenant(tenant.id);
|
||||
if (typeof msg.projectId === 'string' && msg.projectId.trim()) {
|
||||
const requestedProject = getProjectForTenant(msg.projectId.trim(), tenant.id);
|
||||
if (requestedProject) {
|
||||
projectId = requestedProject.id;
|
||||
}
|
||||
}
|
||||
|
||||
return { tenant, projectId };
|
||||
}
|
||||
|
||||
function injectApiKeyIntoHtml(html: string): string {
|
||||
const apiKey = process.env.EXCALIDRAW_API_KEY;
|
||||
if (!apiKey) return html;
|
||||
const serialized = JSON.stringify(apiKey).replace(/</g, '\\u003c');
|
||||
const script = `<script>window.__EXCALIDRAW_API_KEY__=${serialized};</script>`;
|
||||
return html.includes('</head>') ? html.replace('</head>', `${script}</head>`) : `${script}${html}`;
|
||||
}
|
||||
|
||||
// ── Connection Registry (Task 3) ──────────────────────────────────────────
|
||||
// Scoped by tenant → project → Set<ClientConnection>
|
||||
const connections = new Map<string, Map<string, Set<ClientConnection>>>();
|
||||
@@ -248,72 +364,73 @@ function broadcast(message: WebSocketMessage): void {
|
||||
|
||||
// ── WebSocket Connection Handling (Task 4: Hello Handshake) ───────────────
|
||||
wss.on('connection', (ws: WebSocket) => {
|
||||
// Register with fallback scope until hello handshake identifies the client.
|
||||
const tenant = (() => { try { return dbGetActiveTenant(); } catch { return { id: 'default', name: 'default', workspace_path: '' }; } })();
|
||||
const fallbackProjectId = getDefaultProjectForTenant(tenant.id) ?? 'default';
|
||||
const conn: ClientConnection = {
|
||||
ws,
|
||||
tenantId: tenant.id,
|
||||
projectId: fallbackProjectId,
|
||||
connectedAt: Date.now(),
|
||||
identified: false
|
||||
};
|
||||
registerConnection(conn);
|
||||
logger.info('New WebSocket connection established (awaiting hello)');
|
||||
const authEnabled = isAuthEnabled();
|
||||
let awaitingAuth = authEnabled;
|
||||
let authTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
// Send tenant info so the FE knows where to send hello
|
||||
ws.send(JSON.stringify({
|
||||
type: 'tenant_switched',
|
||||
tenant: { id: tenant.id, name: tenant.name, workspace_path: tenant.workspace_path }
|
||||
}));
|
||||
|
||||
// For backward compatibility: also send initial_elements immediately.
|
||||
// New FE versions will ignore this and use hello_ack instead.
|
||||
const initialMessage: InitialElementsMessage = {
|
||||
type: 'initial_elements',
|
||||
elements: store.getAllElements(fallbackProjectId)
|
||||
};
|
||||
ws.send(JSON.stringify(initialMessage));
|
||||
|
||||
// Send any stored files (image data)
|
||||
if (files.size > 0) {
|
||||
const allFiles: Record<string, ExcalidrawFile> = {};
|
||||
for (const [id, file] of files) {
|
||||
allFiles[id] = file;
|
||||
const tenant = (() => {
|
||||
try {
|
||||
return dbGetActiveTenant();
|
||||
} catch {
|
||||
return { id: 'default', name: 'default', workspace_path: '' };
|
||||
}
|
||||
ws.send(JSON.stringify({ type: 'files_added', files: allFiles }));
|
||||
}
|
||||
})();
|
||||
const fallbackProjectId = getDefaultProjectForTenant(tenant.id) ?? 'default';
|
||||
|
||||
// Send sync status to new client
|
||||
const syncMessage: SyncStatusMessage = {
|
||||
type: 'sync_status',
|
||||
elementCount: store.getElementCount(fallbackProjectId),
|
||||
timestamp: new Date().toISOString()
|
||||
};
|
||||
ws.send(JSON.stringify(syncMessage));
|
||||
logger.info(`New WebSocket connection established${authEnabled ? ' (awaiting auth)' : ' (legacy mode)'}`);
|
||||
|
||||
if (authEnabled) {
|
||||
ws.send(JSON.stringify({ type: 'auth_required' }));
|
||||
authTimer = setTimeout(() => {
|
||||
if (ws.readyState !== WebSocket.OPEN) return;
|
||||
ws.send(JSON.stringify({ type: 'auth_failed', reason: 'timeout' }));
|
||||
ws.close(WS_AUTH_CLOSE_CODE, 'Authentication required');
|
||||
}, WS_AUTH_TIMEOUT_MS);
|
||||
} else {
|
||||
registerConnection({
|
||||
ws,
|
||||
tenantId: tenant.id,
|
||||
projectId: fallbackProjectId,
|
||||
connectedAt: Date.now(),
|
||||
identified: false
|
||||
});
|
||||
sendAuthlessInitialMessages(ws, tenant, fallbackProjectId);
|
||||
}
|
||||
|
||||
// Handle incoming messages from this client
|
||||
ws.on('message', (raw) => {
|
||||
try {
|
||||
const msg = JSON.parse(raw.toString());
|
||||
if (msg.type === 'hello') {
|
||||
const helloTenantId = msg.tenantId as string;
|
||||
const helloProjectId = (msg.projectId as string) || getDefaultProjectForTenant(msg.tenantId) || `${msg.tenantId}-default`;
|
||||
if (helloTenantId) {
|
||||
// Move connection to the correct scope
|
||||
moveConnection(ws, helloTenantId, helloProjectId);
|
||||
logger.info(`Client identified: tenant=${helloTenantId} project=${helloProjectId}`);
|
||||
|
||||
// Respond with scoped elements
|
||||
const elements = store.getAllElements(helloProjectId);
|
||||
ws.send(JSON.stringify({
|
||||
type: 'hello_ack',
|
||||
tenantId: helloTenantId,
|
||||
projectId: helloProjectId,
|
||||
elements
|
||||
}));
|
||||
if (awaitingAuth) {
|
||||
if (!validateApiKey(msg.apiKey)) {
|
||||
ws.send(JSON.stringify({ type: 'auth_failed', reason: 'invalid_key' }));
|
||||
ws.close(WS_AUTH_CLOSE_CODE, 'Invalid API key');
|
||||
return;
|
||||
}
|
||||
awaitingAuth = false;
|
||||
if (authTimer) {
|
||||
clearTimeout(authTimer);
|
||||
authTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
const resolved = resolveHelloTenantAndProject(msg);
|
||||
if ('error' in resolved) {
|
||||
ws.send(JSON.stringify({ type: 'error', message: resolved.error }));
|
||||
return;
|
||||
}
|
||||
identifyConnection(ws, resolved.tenant.id, resolved.projectId);
|
||||
logger.info(`Client identified: tenant=${resolved.tenant.id} project=${resolved.projectId}`);
|
||||
|
||||
sendHelloAck(ws, resolved.tenant, resolved.projectId);
|
||||
if (authEnabled) {
|
||||
sendFilesAdded(ws);
|
||||
sendSyncStatus(ws, resolved.projectId);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (awaitingAuth) return;
|
||||
if (msg.type === 'ack' && msg.msgId) {
|
||||
resolveAck(msg.msgId, {
|
||||
status: msg.status ?? 'applied',
|
||||
@@ -327,22 +444,23 @@ wss.on('connection', (ws: WebSocket) => {
|
||||
});
|
||||
|
||||
ws.on('close', () => {
|
||||
if (authTimer) clearTimeout(authTimer);
|
||||
unregisterConnection(ws);
|
||||
logger.info('WebSocket connection closed');
|
||||
});
|
||||
|
||||
ws.on('error', (error) => {
|
||||
if (authTimer) clearTimeout(authTimer);
|
||||
logger.error('WebSocket error:', error);
|
||||
unregisterConnection(ws);
|
||||
});
|
||||
});
|
||||
|
||||
// Schema validation
|
||||
const CreateElementSchema = z.object({
|
||||
id: z.string().optional(),
|
||||
type: z.enum(Object.values(EXCALIDRAW_ELEMENT_TYPES) as [ExcalidrawElementType, ...ExcalidrawElementType[]]),
|
||||
x: z.number(),
|
||||
y: z.number(),
|
||||
// Module-level constants
|
||||
const VALID_ELEMENT_TYPES = new Set(Object.values(EXCALIDRAW_ELEMENT_TYPES));
|
||||
|
||||
// Schema validation — shared fields extracted to avoid duplication
|
||||
const ElementSharedFieldsSchema = z.object({
|
||||
width: z.number().optional(),
|
||||
height: z.number().optional(),
|
||||
backgroundColor: z.string().optional(),
|
||||
@@ -353,9 +471,7 @@ const CreateElementSchema = z.object({
|
||||
opacity: z.number().optional(),
|
||||
text: z.string().optional(),
|
||||
originalText: z.string().optional(),
|
||||
label: z.object({
|
||||
text: z.string()
|
||||
}).optional(),
|
||||
label: z.object({ text: z.string() }).optional(),
|
||||
fontSize: z.number().optional(),
|
||||
fontFamily: z.union([z.string(), z.number()]).optional(),
|
||||
groupIds: z.array(z.string()).optional(),
|
||||
@@ -363,7 +479,6 @@ const CreateElementSchema = z.object({
|
||||
roundness: z.object({ type: z.number(), value: z.number().optional() }).nullable().optional(),
|
||||
fillStyle: z.string().optional(),
|
||||
// Arrow-specific properties
|
||||
points: z.any().optional(),
|
||||
start: z.object({ id: z.string() }).optional(),
|
||||
end: z.object({ id: z.string() }).optional(),
|
||||
startArrowhead: z.string().nullable().optional(),
|
||||
@@ -378,45 +493,23 @@ const CreateElementSchema = z.object({
|
||||
scale: z.tuple([z.number(), z.number()]).optional(),
|
||||
});
|
||||
|
||||
const UpdateElementSchema = z.object({
|
||||
const CreateElementSchema = ElementSharedFieldsSchema.extend({
|
||||
id: z.string().optional(),
|
||||
type: z.enum(Object.values(EXCALIDRAW_ELEMENT_TYPES) as [ExcalidrawElementType, ...ExcalidrawElementType[]]),
|
||||
x: z.number(),
|
||||
y: z.number(),
|
||||
points: z.any().optional(),
|
||||
});
|
||||
|
||||
const UpdateElementSchema = ElementSharedFieldsSchema.extend({
|
||||
id: z.string(),
|
||||
type: z.enum(Object.values(EXCALIDRAW_ELEMENT_TYPES) as [ExcalidrawElementType, ...ExcalidrawElementType[]]).optional(),
|
||||
x: z.number().optional(),
|
||||
y: z.number().optional(),
|
||||
width: z.number().optional(),
|
||||
height: z.number().optional(),
|
||||
backgroundColor: z.string().optional(),
|
||||
strokeColor: z.string().optional(),
|
||||
strokeWidth: z.number().optional(),
|
||||
strokeStyle: z.string().optional(),
|
||||
roughness: z.number().optional(),
|
||||
opacity: z.number().optional(),
|
||||
text: z.string().optional(),
|
||||
originalText: z.string().optional(),
|
||||
label: z.object({
|
||||
text: z.string()
|
||||
}).optional(),
|
||||
fontSize: z.number().optional(),
|
||||
fontFamily: z.union([z.string(), z.number()]).optional(),
|
||||
groupIds: z.array(z.string()).optional(),
|
||||
locked: z.boolean().optional(),
|
||||
roundness: z.object({ type: z.number(), value: z.number().optional() }).nullable().optional(),
|
||||
fillStyle: z.string().optional(),
|
||||
points: z.array(z.union([
|
||||
z.tuple([z.number(), z.number()]),
|
||||
z.object({ x: z.number(), y: z.number() })
|
||||
])).optional(),
|
||||
start: z.object({ id: z.string() }).optional(),
|
||||
end: z.object({ id: z.string() }).optional(),
|
||||
startArrowhead: z.string().nullable().optional(),
|
||||
endArrowhead: z.string().nullable().optional(),
|
||||
startBinding: z.any().nullable().optional(),
|
||||
endBinding: z.any().nullable().optional(),
|
||||
boundElements: z.any().nullable().optional(),
|
||||
elbowed: z.boolean().optional(),
|
||||
fileId: z.string().optional(),
|
||||
status: z.string().optional(),
|
||||
scale: z.tuple([z.number(), z.number()]).optional(),
|
||||
});
|
||||
|
||||
// API Routes
|
||||
@@ -465,7 +558,7 @@ app.post('/api/elements', async (req: Request, res: Response) => {
|
||||
type: 'element_created',
|
||||
element: element
|
||||
};
|
||||
(message as any).sync_version = sv;
|
||||
message['sync_version'] = sv;
|
||||
const ackResult = await serializedBroadcastWithAck(scope.tenantId, scope.projectId, message);
|
||||
|
||||
res.json({
|
||||
@@ -526,7 +619,7 @@ app.put('/api/elements/:id', async (req: Request, res: Response) => {
|
||||
type: 'element_updated',
|
||||
element: updatedElement
|
||||
};
|
||||
(message as any).sync_version = sv;
|
||||
message['sync_version'] = sv;
|
||||
const ackResult = await serializedBroadcastWithAck(scope.tenantId, scope.projectId, message);
|
||||
|
||||
res.json({
|
||||
@@ -550,7 +643,7 @@ app.put('/api/elements/:id', async (req: Request, res: Response) => {
|
||||
});
|
||||
|
||||
// Clear all elements (must be before /:id route)
|
||||
app.delete('/api/elements/clear', (req: Request, res: Response) => {
|
||||
app.delete('/api/elements/clear', destructiveRateLimit, requireConfirm, (req: Request, res: Response) => {
|
||||
try {
|
||||
const projId = resolveTenantProject(req);
|
||||
const count = store.clearElements(projId);
|
||||
@@ -626,8 +719,11 @@ app.get('/api/elements/search', (req: Request, res: Response) => {
|
||||
const { type, q, ...filters } = req.query;
|
||||
|
||||
if (q && typeof q === 'string') {
|
||||
const results = store.searchElements(q, projId);
|
||||
return res.json({ success: true, elements: results, count: results.length });
|
||||
const sanitizedQuery = sanitizeSearchQuery(q);
|
||||
if (sanitizedQuery) {
|
||||
const results = store.searchElements(sanitizedQuery, projId);
|
||||
return res.json({ success: true, elements: results, count: results.length });
|
||||
}
|
||||
}
|
||||
|
||||
const results = store.queryElements(
|
||||
@@ -643,9 +739,15 @@ app.get('/api/elements/search', (req: Request, res: Response) => {
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Error querying elements:', error);
|
||||
if (error instanceof InvalidSearchQueryError) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Invalid search query'
|
||||
});
|
||||
}
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: (error as Error).message
|
||||
error: 'Search failed'
|
||||
});
|
||||
}
|
||||
});
|
||||
@@ -881,7 +983,7 @@ app.post('/api/elements/batch', async (req: Request, res: Response) => {
|
||||
});
|
||||
|
||||
// Convert Mermaid diagram to Excalidraw elements
|
||||
app.post('/api/elements/from-mermaid', (req: Request, res: Response) => {
|
||||
app.post('/api/elements/from-mermaid', validateMermaidInput, (req: Request, res: Response) => {
|
||||
try {
|
||||
const { mermaidDiagram, config } = req.body;
|
||||
|
||||
@@ -923,22 +1025,22 @@ app.post('/api/elements/from-mermaid', (req: Request, res: Response) => {
|
||||
});
|
||||
|
||||
// Sync elements from frontend (overwrite sync)
|
||||
app.post('/api/elements/sync', (req: Request, res: Response) => {
|
||||
app.post('/api/elements/sync', writeBurstLimit, (req: Request, res: Response) => {
|
||||
try {
|
||||
const projId = resolveTenantProject(req);
|
||||
const { elements: frontendElements, timestamp } = req.body;
|
||||
|
||||
logger.info(`Sync request received: ${frontendElements.length} elements`, {
|
||||
timestamp,
|
||||
elementCount: frontendElements.length
|
||||
});
|
||||
|
||||
|
||||
if (!Array.isArray(frontendElements)) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: 'Expected elements to be an array'
|
||||
});
|
||||
}
|
||||
|
||||
logger.info(`Sync request received: ${frontendElements.length} elements`, {
|
||||
timestamp,
|
||||
elementCount: frontendElements.length
|
||||
});
|
||||
|
||||
const beforeCount = store.getElementCount(projId);
|
||||
|
||||
@@ -996,7 +1098,7 @@ app.post('/api/elements/sync', (req: Request, res: Response) => {
|
||||
|
||||
// ── Delta Sync v2 (Task 10) ──
|
||||
|
||||
app.post('/api/elements/sync/v2', (req: Request, res: Response) => {
|
||||
app.post('/api/elements/sync/v2', writeBurstLimit, (req: Request, res: Response) => {
|
||||
try {
|
||||
const projId = resolveTenantProject(req);
|
||||
const { lastSyncVersion = 0, changes = [] } = req.body;
|
||||
@@ -1008,6 +1110,20 @@ app.post('/api/elements/sync/v2', (req: Request, res: Response) => {
|
||||
const scope = resolveScope(req);
|
||||
const feChangeIds = new Set<string>();
|
||||
|
||||
// Validate all upsert elements before applying any changes
|
||||
for (const change of changes) {
|
||||
const { id, action, element } = change;
|
||||
if (!id || !action) continue;
|
||||
if (action === 'upsert' && element && element.type !== undefined) {
|
||||
if (!VALID_ELEMENT_TYPES.has(element.type)) {
|
||||
return res.status(400).json({
|
||||
success: false,
|
||||
error: `Invalid element type: ${element.type}`
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Apply FE changes to DB
|
||||
let appliedCount = 0;
|
||||
for (const change of changes) {
|
||||
@@ -1069,11 +1185,7 @@ app.get('/api/sync/version', (req: Request, res: Response) => {
|
||||
// Get all files
|
||||
app.get('/api/files', (_req: Request, res: Response) => {
|
||||
try {
|
||||
const allFiles: Record<string, ExcalidrawFile> = {};
|
||||
for (const [id, file] of files) {
|
||||
allFiles[id] = file;
|
||||
}
|
||||
res.json({ success: true, files: allFiles });
|
||||
res.json({ success: true, files: getAllFilesObject() });
|
||||
} catch (error) {
|
||||
logger.error('Error fetching files:', error);
|
||||
res.status(500).json({ success: false, error: (error as Error).message });
|
||||
@@ -1415,12 +1527,13 @@ app.get('/api/snapshots/:name', (req: Request, res: Response) => {
|
||||
|
||||
// Serve the frontend
|
||||
app.get('/', (req: Request, res: Response) => {
|
||||
const htmlFile = path.join(__dirname, '../dist/frontend/index.html');
|
||||
res.sendFile(htmlFile, (err) => {
|
||||
fs.readFile(frontendHtmlPath, 'utf8', (err, html) => {
|
||||
if (err) {
|
||||
logger.error('Error serving frontend:', err);
|
||||
res.status(404).send('Frontend not found. Please run "npm run build" first.');
|
||||
return;
|
||||
}
|
||||
res.type('html').send(injectApiKeyIntoHtml(html));
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1524,11 +1637,15 @@ app.get('/api/sync/status', (req: Request, res: Response) => {
|
||||
});
|
||||
|
||||
// Error handling middleware
|
||||
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
|
||||
app.use((err: any, req: Request, res: Response, next: NextFunction) => {
|
||||
// Propagate HTTP status from framework errors (e.g. 413 from express.json, 429 from rate-limit).
|
||||
const status: number = typeof err.status === 'number' ? err.status
|
||||
: typeof err.statusCode === 'number' ? err.statusCode
|
||||
: 500;
|
||||
logger.error('Unhandled error:', err);
|
||||
res.status(500).json({
|
||||
res.status(status).json({
|
||||
success: false,
|
||||
error: 'Internal server error'
|
||||
error: status === 500 ? 'Internal server error' : (err.message ?? 'Error')
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1612,4 +1729,4 @@ if (isServerMainModule()) {
|
||||
});
|
||||
}
|
||||
|
||||
export default app;
|
||||
export default app;
|
||||
|
||||
+6
-6
@@ -1,8 +1,8 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/**
|
||||
* Interactive setup wizard for mcp-excalidraw-local.
|
||||
* Runs via: npx @sanjibdevnath/mcp-excalidraw-local setup
|
||||
* Interactive setup wizard for excalidraw-mcp-sentinel.
|
||||
* Runs via: npx excalidraw-mcp-sentinel setup
|
||||
*
|
||||
* Uses only Node.js built-ins — no third-party dependencies.
|
||||
* Every phase is optional and skippable.
|
||||
@@ -92,7 +92,7 @@ function getAgents(): AgentDef[] {
|
||||
},
|
||||
mcpConfigType: 'cli-command',
|
||||
mcpCliRemove: 'claude mcp remove excalidraw-canvas --scope user',
|
||||
mcpCliCommand: 'claude mcp add excalidraw-canvas --scope user -e CANVAS_PORT=3000 -- npx -y @sanjibdevnath/mcp-excalidraw-local@latest',
|
||||
mcpCliCommand: 'claude mcp add excalidraw-canvas --scope user -e CANVAS_PORT=3000 -- npx -y excalidraw-mcp-sentinel@latest',
|
||||
instructionConfig: {
|
||||
global: path.join(home, '.claude', 'CLAUDE.md'),
|
||||
local: path.join(process.cwd(), 'CLAUDE.md'),
|
||||
@@ -493,7 +493,7 @@ async function phaseMcpConfig(rl: readline.Interface): Promise<void> {
|
||||
function mergeJsonConfig(configPath: string): void {
|
||||
const mcpEntry = {
|
||||
command: 'npx',
|
||||
args: ['-y', '@sanjibdevnath/mcp-excalidraw-local@latest'],
|
||||
args: ['-y', 'excalidraw-mcp-sentinel@latest'],
|
||||
env: { CANVAS_PORT: '3000' },
|
||||
};
|
||||
|
||||
@@ -549,7 +549,7 @@ function printManualConfig(): void {
|
||||
"mcpServers": {
|
||||
"excalidraw-canvas": {
|
||||
"command": "npx",
|
||||
"args": ["-y", "@sanjibdevnath/mcp-excalidraw-local@latest"],
|
||||
"args": ["-y", "excalidraw-mcp-sentinel@latest"],
|
||||
"env": { "CANVAS_PORT": "3000" }
|
||||
}
|
||||
}
|
||||
@@ -619,7 +619,7 @@ export async function runUpdate(): Promise<void> {
|
||||
const skillSource = path.resolve(__dirname, '..', 'skills', 'excalidraw-skill');
|
||||
if (!fs.existsSync(skillSource)) {
|
||||
fail(`Skill source not found at ${skillSource}`);
|
||||
fail('This can happen with corrupted installs. Try: npx @sanjibdevnath/mcp-excalidraw-local@latest setup');
|
||||
fail('This can happen with corrupted installs. Try: npx excalidraw-mcp-sentinel@latest setup');
|
||||
rl.close();
|
||||
return;
|
||||
}
|
||||
|
||||
+13
-4
@@ -196,7 +196,10 @@ export type WebSocketMessageType =
|
||||
| 'file_deleted'
|
||||
| 'hello'
|
||||
| 'hello_ack'
|
||||
| 'ack';
|
||||
| 'ack'
|
||||
| 'auth_required'
|
||||
| 'auth_failed'
|
||||
| 'error';
|
||||
|
||||
// Connection registry types
|
||||
export interface ClientConnection {
|
||||
@@ -215,8 +218,9 @@ export interface BroadcastResult {
|
||||
|
||||
export interface HelloMessage extends WebSocketMessage {
|
||||
type: 'hello';
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
tenantId?: string;
|
||||
projectId?: string;
|
||||
apiKey?: string;
|
||||
}
|
||||
|
||||
export interface HelloAckMessage extends WebSocketMessage {
|
||||
@@ -224,6 +228,11 @@ export interface HelloAckMessage extends WebSocketMessage {
|
||||
tenantId: string;
|
||||
projectId: string;
|
||||
elements: ServerElement[];
|
||||
tenant?: {
|
||||
id: string;
|
||||
name: string;
|
||||
workspace_path: string;
|
||||
};
|
||||
}
|
||||
|
||||
export interface AckMessage extends WebSocketMessage {
|
||||
@@ -413,4 +422,4 @@ export function validateElement(element: Partial<ServerElement>): element is Ser
|
||||
// Helper function to generate unique IDs
|
||||
export function generateId(): string {
|
||||
return Date.now().toString(36) + Math.random().toString(36).substring(2);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -173,7 +173,7 @@ describe('DELETE /api/elements/clear', () => {
|
||||
setElement('a', makeElement({ id: 'a' }));
|
||||
setElement('b', makeElement({ id: 'b' }));
|
||||
|
||||
const res = await request(app).delete('/api/elements/clear');
|
||||
const res = await request(app).delete('/api/elements/clear?confirm=true');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.count).toBe(2);
|
||||
|
||||
@@ -182,7 +182,7 @@ describe('DELETE /api/elements/clear', () => {
|
||||
});
|
||||
|
||||
it('returns 0 count when already empty', async () => {
|
||||
const res = await request(app).delete('/api/elements/clear');
|
||||
const res = await request(app).delete('/api/elements/clear?confirm=true');
|
||||
expect(res.body.count).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest';
|
||||
import {
|
||||
initDb,
|
||||
closeDb,
|
||||
clearElements,
|
||||
ensureTenant,
|
||||
getDefaultProjectForTenant,
|
||||
setActiveTenant,
|
||||
setElement,
|
||||
} from '../../src/db.js';
|
||||
import type { ServerElement } from '../../src/types.js';
|
||||
import WebSocket from 'ws';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import fs from 'fs';
|
||||
|
||||
let dbPath: string;
|
||||
let port: number;
|
||||
let startCanvasServer: () => Promise<void>;
|
||||
let stopCanvasServer: () => Promise<void>;
|
||||
const frontendDir = path.join(process.cwd(), 'dist/frontend');
|
||||
const frontendHtmlPath = path.join(frontendDir, 'index.html');
|
||||
let originalFrontendHtml: string | null = null;
|
||||
let hadFrontendHtml = false;
|
||||
|
||||
function waitForMessageOfType(ws: WebSocket, type: string, timeoutMs = 5000): Promise<any> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => reject(new Error(`Timeout waiting for message type: ${type}`)), timeoutMs);
|
||||
const handler = (data: WebSocket.RawData) => {
|
||||
const msg = JSON.parse(data.toString());
|
||||
if (msg.type === type) {
|
||||
clearTimeout(timer);
|
||||
ws.off('message', handler);
|
||||
resolve(msg);
|
||||
}
|
||||
};
|
||||
ws.on('message', handler);
|
||||
});
|
||||
}
|
||||
|
||||
function connectAndCollect(waitMs = 200): Promise<{ ws: WebSocket; messages: any[] }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const messages: any[] = [];
|
||||
const ws = new WebSocket(`ws://localhost:${port}`);
|
||||
ws.on('message', (raw) => messages.push(JSON.parse(raw.toString())));
|
||||
ws.on('open', () => setTimeout(() => resolve({ ws, messages }), waitMs));
|
||||
ws.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
port = 3500 + Math.floor(Math.random() * 100);
|
||||
process.env.CANVAS_PORT = String(port);
|
||||
process.env.HOST = 'localhost';
|
||||
process.env.EXCALIDRAW_API_KEY = 'integration-secret';
|
||||
|
||||
dbPath = path.join(os.tmpdir(), `excalidraw-auth-integration-${Date.now()}.db`);
|
||||
initDb(dbPath);
|
||||
|
||||
hadFrontendHtml = fs.existsSync(frontendHtmlPath);
|
||||
originalFrontendHtml = hadFrontendHtml ? fs.readFileSync(frontendHtmlPath, 'utf8') : null;
|
||||
fs.mkdirSync(frontendDir, { recursive: true });
|
||||
fs.writeFileSync(frontendHtmlPath, '<!doctype html><html><head><title>Integration</title></head><body><div id="root"></div></body></html>');
|
||||
|
||||
const mod = await import('../../src/server.js');
|
||||
startCanvasServer = mod.startCanvasServer;
|
||||
stopCanvasServer = mod.stopCanvasServer;
|
||||
await startCanvasServer();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
delete process.env.EXCALIDRAW_API_KEY;
|
||||
await stopCanvasServer();
|
||||
closeDb();
|
||||
if (hadFrontendHtml && originalFrontendHtml !== null) {
|
||||
fs.writeFileSync(frontendHtmlPath, originalFrontendHtml);
|
||||
} else {
|
||||
try { fs.unlinkSync(frontendHtmlPath); } catch {}
|
||||
}
|
||||
for (const suffix of ['', '-wal', '-shm']) {
|
||||
try { fs.unlinkSync(dbPath + suffix); } catch {}
|
||||
}
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
setActiveTenant('default');
|
||||
clearElements();
|
||||
});
|
||||
|
||||
describe('Auth bootstrap integration', () => {
|
||||
it('serves injected HTML, authenticates over WS, and reads scoped REST data', async () => {
|
||||
ensureTenant('integration-a', 'Integration A', 'workspace/integration-a');
|
||||
setActiveTenant('integration-a');
|
||||
const projectId = getDefaultProjectForTenant('integration-a');
|
||||
setElement('integration-el', {
|
||||
id: 'integration-el',
|
||||
type: 'rectangle',
|
||||
x: 25,
|
||||
y: 30,
|
||||
width: 120,
|
||||
height: 80,
|
||||
version: 1,
|
||||
} as ServerElement, projectId);
|
||||
|
||||
const rootRes = await fetch(`http://localhost:${port}/`);
|
||||
expect(rootRes.status).toBe(200);
|
||||
const html = await rootRes.text();
|
||||
expect(html).toContain('window.__EXCALIDRAW_API_KEY__="integration-secret"');
|
||||
|
||||
const { ws, messages } = await connectAndCollect();
|
||||
expect(messages.some(message => message.type === 'auth_required')).toBe(true);
|
||||
|
||||
const ackPromise = waitForMessageOfType(ws, 'hello_ack');
|
||||
ws.send(JSON.stringify({ type: 'hello', apiKey: 'integration-secret' }));
|
||||
const ack = await ackPromise;
|
||||
|
||||
expect(ack.tenantId).toBe('integration-a');
|
||||
expect(ack.projectId).toBe(projectId);
|
||||
expect(ack.elements.map((element: any) => element.id)).toContain('integration-el');
|
||||
|
||||
const listRes = await fetch(`http://localhost:${port}/api/elements`, {
|
||||
headers: {
|
||||
'X-API-Key': 'integration-secret',
|
||||
'X-Tenant-Id': 'integration-a',
|
||||
},
|
||||
});
|
||||
expect(listRes.status).toBe(200);
|
||||
const listBody = await listRes.json() as { count: number; elements: { id: string }[] };
|
||||
expect(listBody.count).toBe(1);
|
||||
expect(listBody.elements[0].id).toBe('integration-el');
|
||||
|
||||
ws.close();
|
||||
});
|
||||
|
||||
it('authenticated WS clients receive tenant_switched after a keyed REST switch', async () => {
|
||||
ensureTenant('integration-b', 'Integration B', 'workspace/integration-b');
|
||||
ensureTenant('integration-c', 'Integration C', 'workspace/integration-c');
|
||||
setActiveTenant('integration-b');
|
||||
|
||||
const { ws, messages } = await connectAndCollect();
|
||||
expect(messages.some(message => message.type === 'auth_required')).toBe(true);
|
||||
const ackPromise = waitForMessageOfType(ws, 'hello_ack');
|
||||
ws.send(JSON.stringify({ type: 'hello', apiKey: 'integration-secret' }));
|
||||
const ack = await ackPromise;
|
||||
expect(ack.tenantId).toBe('integration-b');
|
||||
|
||||
const switchPromise = waitForMessageOfType(ws, 'tenant_switched');
|
||||
const switchRes = await fetch(`http://localhost:${port}/api/tenant/active`, {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': 'integration-secret',
|
||||
},
|
||||
body: JSON.stringify({ tenantId: 'integration-c' }),
|
||||
});
|
||||
|
||||
expect(switchRes.status).toBe(200);
|
||||
const switched = await switchPromise;
|
||||
expect(switched.tenant.id).toBe('integration-c');
|
||||
|
||||
ws.close();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,255 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import request from 'supertest';
|
||||
import { initDb, closeDb, setActiveTenant } from '../../src/db.js';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import fs from 'fs';
|
||||
|
||||
let dbPath: string;
|
||||
let app: any;
|
||||
const frontendDir = path.join(process.cwd(), 'dist/frontend');
|
||||
const frontendHtmlPath = path.join(frontendDir, 'index.html');
|
||||
let originalFrontendHtml: string | null = null;
|
||||
let hadFrontendHtml = false;
|
||||
|
||||
beforeEach(async () => {
|
||||
dbPath = path.join(os.tmpdir(), `excalidraw-auth-test-${Date.now()}-${Math.random().toString(36).slice(2)}.db`);
|
||||
initDb(dbPath);
|
||||
setActiveTenant('default');
|
||||
hadFrontendHtml = fs.existsSync(frontendHtmlPath);
|
||||
originalFrontendHtml = hadFrontendHtml ? fs.readFileSync(frontendHtmlPath, 'utf8') : null;
|
||||
fs.mkdirSync(frontendDir, { recursive: true });
|
||||
fs.writeFileSync(frontendHtmlPath, '<!doctype html><html><head><title>Test</title></head><body><div id="root"></div></body></html>');
|
||||
const mod = await import('../../src/server.js');
|
||||
app = mod.default;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.EXCALIDRAW_API_KEY;
|
||||
delete process.env.ALLOWED_ORIGINS;
|
||||
closeDb();
|
||||
if (hadFrontendHtml && originalFrontendHtml !== null) {
|
||||
fs.writeFileSync(frontendHtmlPath, originalFrontendHtml);
|
||||
} else {
|
||||
try { fs.unlinkSync(frontendHtmlPath); } catch {}
|
||||
}
|
||||
for (const suffix of ['', '-wal', '-shm']) {
|
||||
try { fs.unlinkSync(dbPath + suffix); } catch {}
|
||||
}
|
||||
});
|
||||
|
||||
// ─── API Key Auth ───────────────────────────────────────────────────────────
|
||||
|
||||
describe('API Key Auth — disabled (no env var)', () => {
|
||||
it('allows GET /api/elements without API key', async () => {
|
||||
delete process.env.EXCALIDRAW_API_KEY;
|
||||
const res = await request(app).get('/api/elements');
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it('allows DELETE /api/elements/clear without API key', async () => {
|
||||
delete process.env.EXCALIDRAW_API_KEY;
|
||||
const res = await request(app).delete('/api/elements/clear?confirm=true');
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
describe('API Key Auth — enabled (EXCALIDRAW_API_KEY set)', () => {
|
||||
it('rejects GET /api/elements without key → 401', async () => {
|
||||
process.env.EXCALIDRAW_API_KEY = 'test-secret';
|
||||
const res = await request(app).get('/api/elements');
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.body.success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects GET /api/elements with wrong key → 401', async () => {
|
||||
process.env.EXCALIDRAW_API_KEY = 'test-secret';
|
||||
const res = await request(app)
|
||||
.get('/api/elements')
|
||||
.set('X-API-Key', 'wrong-key');
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('allows GET /api/elements with correct key → 200', async () => {
|
||||
process.env.EXCALIDRAW_API_KEY = 'test-secret';
|
||||
const res = await request(app)
|
||||
.get('/api/elements')
|
||||
.set('X-API-Key', 'test-secret');
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it('rejects POST /api/elements without key → 401', async () => {
|
||||
process.env.EXCALIDRAW_API_KEY = 'test-secret';
|
||||
const res = await request(app)
|
||||
.post('/api/elements')
|
||||
.send({ type: 'rectangle', x: 0, y: 0, width: 100, height: 50 });
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('rejects DELETE /api/elements/clear without key → 401', async () => {
|
||||
process.env.EXCALIDRAW_API_KEY = 'test-secret';
|
||||
const res = await request(app).delete('/api/elements/clear?confirm=true');
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('health endpoint is exempt from auth → 200', async () => {
|
||||
process.env.EXCALIDRAW_API_KEY = 'test-secret';
|
||||
const res = await request(app).get('/health');
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it('rejects empty X-API-Key header → 401', async () => {
|
||||
process.env.EXCALIDRAW_API_KEY = 'test-secret';
|
||||
const res = await request(app)
|
||||
.get('/api/elements')
|
||||
.set('X-API-Key', '');
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── MCP → Canvas inter-service auth (trust boundary A) ─────────────────────
|
||||
// When EXCALIDRAW_API_KEY is set, the canvas REST API must reject requests that
|
||||
// don't include the key — including any inter-service caller (MCP or other).
|
||||
// This validates that the canvas enforces auth at its own boundary regardless
|
||||
// of the caller; the MCP-side fix (forwarding X-API-Key in canvasHeaders) is
|
||||
// verified by ensuring the canvas correctly accepts/rejects the header.
|
||||
|
||||
describe('MCP → Canvas auth boundary: canvas enforces key on all callers', () => {
|
||||
it('rejects inter-service request with no X-API-Key → 401', async () => {
|
||||
process.env.EXCALIDRAW_API_KEY = 'inter-service-secret';
|
||||
const res = await request(app)
|
||||
.get('/api/elements')
|
||||
.set('X-Tenant-Id', 'default');
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('accepts inter-service request with correct X-API-Key → 200', async () => {
|
||||
process.env.EXCALIDRAW_API_KEY = 'inter-service-secret';
|
||||
const res = await request(app)
|
||||
.get('/api/elements')
|
||||
.set('X-Tenant-Id', 'default')
|
||||
.set('X-API-Key', 'inter-service-secret');
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it('rejects inter-service request with wrong X-API-Key → 401', async () => {
|
||||
process.env.EXCALIDRAW_API_KEY = 'inter-service-secret';
|
||||
const res = await request(app)
|
||||
.get('/api/elements')
|
||||
.set('X-Tenant-Id', 'default')
|
||||
.set('X-API-Key', 'wrong-key');
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── CORS ───────────────────────────────────────────────────────────────────
|
||||
|
||||
describe('CORS — origin restriction', () => {
|
||||
it('allows requests with no Origin header', async () => {
|
||||
const res = await request(app).get('/api/elements');
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it('reflects localhost:3000 as allowed origin', async () => {
|
||||
const res = await request(app)
|
||||
.get('/api/elements')
|
||||
.set('Origin', 'http://localhost:3000');
|
||||
expect(res.headers['access-control-allow-origin']).toBe('http://localhost:3000');
|
||||
});
|
||||
|
||||
it('reflects 127.0.0.1:3000 as allowed origin', async () => {
|
||||
const res = await request(app)
|
||||
.get('/api/elements')
|
||||
.set('Origin', 'http://127.0.0.1:3000');
|
||||
expect(res.headers['access-control-allow-origin']).toBe('http://127.0.0.1:3000');
|
||||
});
|
||||
|
||||
it('does NOT reflect untrusted origin in ACAO header', async () => {
|
||||
const res = await request(app)
|
||||
.get('/api/elements')
|
||||
.set('Origin', 'https://evil.com');
|
||||
const acao = res.headers['access-control-allow-origin'];
|
||||
expect(acao).not.toBe('https://evil.com');
|
||||
expect(acao).not.toBe('*');
|
||||
});
|
||||
|
||||
it('allows custom origin from ALLOWED_ORIGINS env var', async () => {
|
||||
process.env.ALLOWED_ORIGINS = 'http://myapp.local:4000,http://localhost:3000';
|
||||
const res = await request(app)
|
||||
.get('/api/elements')
|
||||
.set('Origin', 'http://myapp.local:4000');
|
||||
expect(res.headers['access-control-allow-origin']).toBe('http://myapp.local:4000');
|
||||
});
|
||||
|
||||
it('rejects origin not in custom ALLOWED_ORIGINS list', async () => {
|
||||
process.env.ALLOWED_ORIGINS = 'http://myapp.local:4000';
|
||||
const res = await request(app)
|
||||
.get('/api/elements')
|
||||
.set('Origin', 'http://localhost:3000');
|
||||
const acao = res.headers['access-control-allow-origin'];
|
||||
expect(acao).not.toBe('http://localhost:3000');
|
||||
expect(acao).not.toBe('*');
|
||||
});
|
||||
});
|
||||
|
||||
describe('validateApiKey — timing-safe comparison', () => {
|
||||
it('accepts correct key', async () => {
|
||||
process.env.EXCALIDRAW_API_KEY = 'secure-key-abc123';
|
||||
const { validateApiKey } = await import('../../src/security.js');
|
||||
expect(validateApiKey('secure-key-abc123')).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects wrong key', async () => {
|
||||
process.env.EXCALIDRAW_API_KEY = 'secure-key-abc123';
|
||||
const { validateApiKey } = await import('../../src/security.js');
|
||||
expect(validateApiKey('wrong-key')).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects key that is a prefix of the correct key', async () => {
|
||||
process.env.EXCALIDRAW_API_KEY = 'secure-key-abc123';
|
||||
const { validateApiKey } = await import('../../src/security.js');
|
||||
expect(validateApiKey('secure-key-abc')).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects key that is a superstring of the correct key', async () => {
|
||||
process.env.EXCALIDRAW_API_KEY = 'secure-key-abc123';
|
||||
const { validateApiKey } = await import('../../src/security.js');
|
||||
expect(validateApiKey('secure-key-abc123EXTRA')).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects undefined', async () => {
|
||||
process.env.EXCALIDRAW_API_KEY = 'secure-key-abc123';
|
||||
const { validateApiKey } = await import('../../src/security.js');
|
||||
expect(validateApiKey(undefined)).toBe(false);
|
||||
});
|
||||
|
||||
it('allows anything when auth is disabled', async () => {
|
||||
delete process.env.EXCALIDRAW_API_KEY;
|
||||
const { validateApiKey } = await import('../../src/security.js');
|
||||
expect(validateApiKey(undefined)).toBe(true);
|
||||
expect(validateApiKey('anything')).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('GET / frontend auth bootstrap', () => {
|
||||
it('injects __EXCALIDRAW_API_KEY__ into the served HTML when auth is enabled', async () => {
|
||||
process.env.EXCALIDRAW_API_KEY = 'test-secret';
|
||||
const res = await request(app).get('/');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.text).toContain('window.__EXCALIDRAW_API_KEY__="test-secret"');
|
||||
});
|
||||
|
||||
it('does not inject __EXCALIDRAW_API_KEY__ when auth is disabled', async () => {
|
||||
delete process.env.EXCALIDRAW_API_KEY;
|
||||
const res = await request(app).get('/');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.text).not.toContain('__EXCALIDRAW_API_KEY__');
|
||||
});
|
||||
|
||||
it('injects the current EXCALIDRAW_API_KEY value', async () => {
|
||||
process.env.EXCALIDRAW_API_KEY = 'rotated-secret';
|
||||
const res = await request(app).get('/');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.text).toContain('window.__EXCALIDRAW_API_KEY__="rotated-secret"');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,103 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import request from 'supertest';
|
||||
import { initDb, closeDb, setActiveTenant } from '../../src/db.js';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import fs from 'fs';
|
||||
|
||||
let dbPath: string;
|
||||
let app: any;
|
||||
|
||||
beforeEach(async () => {
|
||||
dbPath = path.join(os.tmpdir(), `excalidraw-headers-test-${Date.now()}-${Math.random().toString(36).slice(2)}.db`);
|
||||
initDb(dbPath);
|
||||
setActiveTenant('default');
|
||||
const mod = await import('../../src/server.js');
|
||||
app = mod.default;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closeDb();
|
||||
for (const suffix of ['', '-wal', '-shm']) {
|
||||
try { fs.unlinkSync(dbPath + suffix); } catch {}
|
||||
}
|
||||
});
|
||||
|
||||
// ─── Security Headers ─────────────────────────────────────────────────────────
|
||||
|
||||
describe('Security headers (helmet)', () => {
|
||||
it('sets X-Content-Type-Options: nosniff', async () => {
|
||||
const res = await request(app).get('/health');
|
||||
expect(res.headers['x-content-type-options']).toBe('nosniff');
|
||||
});
|
||||
|
||||
it('sets X-Frame-Options header', async () => {
|
||||
const res = await request(app).get('/health');
|
||||
expect(res.headers['x-frame-options']).toBeDefined();
|
||||
});
|
||||
|
||||
it('sets X-DNS-Prefetch-Control header', async () => {
|
||||
const res = await request(app).get('/health');
|
||||
expect(res.headers['x-dns-prefetch-control']).toBeDefined();
|
||||
});
|
||||
|
||||
it('does NOT expose X-Powered-By: Express', async () => {
|
||||
const res = await request(app).get('/health');
|
||||
expect(res.headers['x-powered-by']).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Error Leakage Prevention ────────────────────────────────────────────────
|
||||
|
||||
describe('Error responses do not leak internals', () => {
|
||||
it('404 response does not contain stack traces', async () => {
|
||||
const res = await request(app).get('/api/nonexistent-endpoint-xyz');
|
||||
const body = JSON.stringify(res.body);
|
||||
expect(body).not.toMatch(/at\s+\w+\s+\(/); // No stack frames
|
||||
expect(body).not.toMatch(/node_modules/);
|
||||
expect(body).not.toMatch(/\/Users\//);
|
||||
expect(body).not.toMatch(/\/home\//);
|
||||
});
|
||||
|
||||
it('500 error response uses generic message, not stack', async () => {
|
||||
// Trigger the global error handler with an invalid route that causes a crash
|
||||
// (we test error handler behavior via the sanitized message)
|
||||
const res = await request(app)
|
||||
.post('/api/elements')
|
||||
.set('Content-Type', 'application/json')
|
||||
.send('{"type":"rectangle","x":0,"y":0}'); // valid, won't trigger 500
|
||||
// Just verify non-500 responses also don't leak internals
|
||||
const body = JSON.stringify(res.body);
|
||||
expect(body).not.toMatch(/at\s+\w+\s+\(/);
|
||||
});
|
||||
|
||||
it('validation error response does not leak file paths', async () => {
|
||||
const res = await request(app)
|
||||
.post('/api/elements')
|
||||
.set('Content-Type', 'application/json')
|
||||
.send('{"__proto__":{"admin":true},"type":"rectangle"}');
|
||||
expect(res.status).toBe(400);
|
||||
const body = JSON.stringify(res.body);
|
||||
expect(body).not.toMatch(/\/Users\//);
|
||||
expect(body).not.toMatch(/node_modules/);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Tenant Validation ───────────────────────────────────────────────────────
|
||||
|
||||
describe('Tenant switching validation', () => {
|
||||
it('PUT /api/tenant/active rejects non-existent tenant → 400', async () => {
|
||||
const res = await request(app)
|
||||
.put('/api/tenant/active')
|
||||
.send({ tenantId: 'totally-fake-tenant-that-does-not-exist' });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.success).toBe(false);
|
||||
});
|
||||
|
||||
it('PUT /api/tenant/active with missing tenantId → 400', async () => {
|
||||
const res = await request(app)
|
||||
.put('/api/tenant/active')
|
||||
.send({});
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
@@ -46,7 +46,7 @@ describe('Clear canvas confirmation flow', () => {
|
||||
setElement('cl-2', makeElement({ id: 'cl-2' }));
|
||||
expect(getAllElements()).toHaveLength(2);
|
||||
|
||||
const res = await request(app).delete('/api/elements/clear');
|
||||
const res = await request(app).delete('/api/elements/clear?confirm=true');
|
||||
expect(res.body.success).toBe(true);
|
||||
expect(res.body.count).toBeDefined();
|
||||
|
||||
@@ -54,13 +54,13 @@ describe('Clear canvas confirmation flow', () => {
|
||||
});
|
||||
|
||||
it('clear on empty canvas returns zero count', async () => {
|
||||
const res = await request(app).delete('/api/elements/clear');
|
||||
const res = await request(app).delete('/api/elements/clear?confirm=true');
|
||||
expect(res.body.success).toBe(true);
|
||||
});
|
||||
|
||||
it('cleared elements stay gone on subsequent GET requests', async () => {
|
||||
setElement('stay-gone', makeElement({ id: 'stay-gone' }));
|
||||
await request(app).delete('/api/elements/clear');
|
||||
await request(app).delete('/api/elements/clear?confirm=true');
|
||||
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const res = await request(app).get('/api/elements');
|
||||
@@ -160,7 +160,7 @@ describe('Snapshot create and restore flow', () => {
|
||||
expect(snapRes.body.success).toBe(true);
|
||||
|
||||
// Clear
|
||||
await request(app).delete('/api/elements/clear');
|
||||
await request(app).delete('/api/elements/clear?confirm=true');
|
||||
expect(getAllElements()).toHaveLength(0);
|
||||
|
||||
// Snapshot should still contain the elements
|
||||
@@ -180,7 +180,7 @@ describe('Snapshot create and restore flow', () => {
|
||||
await request(app).post('/api/snapshots').send({ name: 'restore-test' });
|
||||
|
||||
// Clear and add different elements
|
||||
await request(app).delete('/api/elements/clear');
|
||||
await request(app).delete('/api/elements/clear?confirm=true');
|
||||
setElement('different', makeElement({ id: 'different' }));
|
||||
|
||||
// Get snapshot
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import request from 'supertest';
|
||||
import { initDb, closeDb, setActiveTenant } from '../../src/db.js';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import fs from 'fs';
|
||||
|
||||
let dbPath: string;
|
||||
let app: any;
|
||||
|
||||
beforeEach(async () => {
|
||||
dbPath = path.join(os.tmpdir(), `excalidraw-middleware-test-${Date.now()}-${Math.random().toString(36).slice(2)}.db`);
|
||||
initDb(dbPath);
|
||||
setActiveTenant('default');
|
||||
process.env.EXCALIDRAW_API_KEY = 'test-secret';
|
||||
const mod = await import('../../src/server.js');
|
||||
app = mod.default;
|
||||
app.set('trust proxy', 1);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.EXCALIDRAW_API_KEY;
|
||||
closeDb();
|
||||
for (const suffix of ['', '-wal', '-shm']) {
|
||||
try { fs.unlinkSync(dbPath + suffix); } catch {}
|
||||
}
|
||||
});
|
||||
|
||||
describe('Middleware order', () => {
|
||||
it('bad API key + oversized body returns 401, not 413', async () => {
|
||||
const bigText = 'x'.repeat(150 * 1024);
|
||||
const res = await request(app)
|
||||
.post('/api/elements')
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('X-API-Key', 'wrong-key')
|
||||
.set('X-Forwarded-For', '10.20.0.1')
|
||||
.send(JSON.stringify({ type: 'text', x: 0, y: 0, width: 100, height: 50, text: bigText }));
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
});
|
||||
|
||||
it('bad API key returns 401 with rate-limit headers', async () => {
|
||||
const res = await request(app)
|
||||
.get('/api/elements')
|
||||
.set('X-API-Key', 'wrong-key')
|
||||
.set('X-Forwarded-For', '10.20.0.2');
|
||||
|
||||
expect(res.status).toBe(401);
|
||||
expect(res.headers).toHaveProperty('ratelimit-policy');
|
||||
});
|
||||
|
||||
it('401 with bad API key is still rate-limited', async () => {
|
||||
const ip = '10.20.0.3';
|
||||
for (let i = 0; i < 100; i++) {
|
||||
await request(app)
|
||||
.get('/api/elements')
|
||||
.set('X-API-Key', 'wrong-key')
|
||||
.set('X-Forwarded-For', ip);
|
||||
}
|
||||
|
||||
const res = await request(app)
|
||||
.get('/api/elements')
|
||||
.set('X-API-Key', 'wrong-key')
|
||||
.set('X-Forwarded-For', ip);
|
||||
|
||||
expect(res.status).toBe(429);
|
||||
});
|
||||
|
||||
it('valid API key + oversized body returns 413', async () => {
|
||||
const bigText = 'x'.repeat(150 * 1024);
|
||||
const res = await request(app)
|
||||
.post('/api/elements')
|
||||
.set('Content-Type', 'application/json')
|
||||
.set('X-API-Key', 'test-secret')
|
||||
.set('X-Forwarded-For', '10.20.0.4')
|
||||
.send(JSON.stringify({ type: 'text', x: 0, y: 0, width: 100, height: 50, text: bigText }));
|
||||
|
||||
expect(res.status).toBe(413);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,157 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import request from 'supertest';
|
||||
import { initDb, closeDb, setActiveTenant } from '../../src/db.js';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import fs from 'fs';
|
||||
|
||||
let dbPath: string;
|
||||
let app: any;
|
||||
|
||||
beforeEach(async () => {
|
||||
dbPath = path.join(os.tmpdir(), `excalidraw-ratelimit-test-${Date.now()}-${Math.random().toString(36).slice(2)}.db`);
|
||||
initDb(dbPath);
|
||||
setActiveTenant('default');
|
||||
const mod = await import('../../src/server.js');
|
||||
app = mod.default;
|
||||
app.set('trust proxy', 1);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closeDb();
|
||||
for (const suffix of ['', '-wal', '-shm']) {
|
||||
try { fs.unlinkSync(dbPath + suffix); } catch {}
|
||||
}
|
||||
});
|
||||
|
||||
// ─── Clear Canvas Confirmation ───────────────────────────────────────────────
|
||||
|
||||
describe('DELETE /api/elements/clear — confirmation token', () => {
|
||||
it('rejects clear without confirm=true query param → 400', async () => {
|
||||
const res = await request(app).delete('/api/elements/clear');
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects clear with confirm=false → 400', async () => {
|
||||
const res = await request(app).delete('/api/elements/clear?confirm=false');
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.success).toBe(false);
|
||||
});
|
||||
|
||||
it('allows clear with confirm=true → 200', async () => {
|
||||
const res = await request(app).delete('/api/elements/clear?confirm=true');
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Payload Size Limits ─────────────────────────────────────────────────────
|
||||
|
||||
describe('Payload size limits', () => {
|
||||
it('rejects POST /api/elements with body > 100KB → 413', async () => {
|
||||
const bigText = 'x'.repeat(150 * 1024); // 150KB
|
||||
const res = await request(app)
|
||||
.post('/api/elements')
|
||||
.set('Content-Type', 'application/json')
|
||||
.send(JSON.stringify({ type: 'text', x: 0, y: 0, width: 100, height: 50, text: bigText }));
|
||||
expect(res.status).toBe(413);
|
||||
});
|
||||
|
||||
it('accepts POST /api/elements with body within limit → not 413', async () => {
|
||||
const res = await request(app)
|
||||
.post('/api/elements')
|
||||
.send({ type: 'rectangle', x: 0, y: 0, width: 100, height: 50 });
|
||||
expect(res.status).not.toBe(413);
|
||||
});
|
||||
|
||||
it('rejects POST /api/elements/batch with body > 5MB → 413', async () => {
|
||||
// Build a payload just over 5MB
|
||||
const elements = Array.from({ length: 10 }, (_, i) => ({
|
||||
id: `el-${i}`,
|
||||
type: 'rectangle',
|
||||
x: i * 10, y: 0, width: 100, height: 50,
|
||||
// Pad each element with ~600KB of label text
|
||||
label: 'x'.repeat(600 * 1024),
|
||||
}));
|
||||
const res = await request(app)
|
||||
.post('/api/elements/batch')
|
||||
.set('Content-Type', 'application/json')
|
||||
.send(JSON.stringify({ elements }));
|
||||
expect(res.status).toBe(413);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Rate Limiting ───────────────────────────────────────────────────────────
|
||||
|
||||
describe('Rate limiting — destructive endpoints', () => {
|
||||
it('returns 429 after exceeding clear rate limit', async () => {
|
||||
// Exhaust the per-minute limit for destructive ops (default 10)
|
||||
const limit = 10;
|
||||
for (let i = 0; i < limit; i++) {
|
||||
await request(app).delete('/api/elements/clear?confirm=true');
|
||||
}
|
||||
const res = await request(app).delete('/api/elements/clear?confirm=true');
|
||||
expect(res.status).toBe(429);
|
||||
});
|
||||
|
||||
it('returns RateLimit headers on destructive endpoint', async () => {
|
||||
const res = await request(app).delete('/api/elements/clear?confirm=true');
|
||||
// express-rate-limit draft-7 sets ratelimit-policy on every response
|
||||
expect(res.headers).toHaveProperty('ratelimit-policy');
|
||||
});
|
||||
});
|
||||
|
||||
describe('Rate limiting — sync endpoints', () => {
|
||||
it('returns 429 after exceeding /api/elements/sync write-burst limit', async () => {
|
||||
const ip = '10.10.0.1';
|
||||
for (let i = 0; i < 10; i++) {
|
||||
await request(app)
|
||||
.post('/api/elements/sync')
|
||||
.set('X-Forwarded-For', ip)
|
||||
.send({ elements: [], timestamp: new Date().toISOString() });
|
||||
}
|
||||
|
||||
const res = await request(app)
|
||||
.post('/api/elements/sync')
|
||||
.set('X-Forwarded-For', ip)
|
||||
.send({ elements: [], timestamp: new Date().toISOString() });
|
||||
|
||||
expect(res.status).toBe(429);
|
||||
});
|
||||
|
||||
it('returns 429 after exceeding /api/elements/sync/v2 write-burst limit', async () => {
|
||||
const ip = '10.10.0.2';
|
||||
for (let i = 0; i < 10; i++) {
|
||||
await request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
.set('X-Forwarded-For', ip)
|
||||
.send({ lastSyncVersion: 0, changes: [] });
|
||||
}
|
||||
|
||||
const res = await request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
.set('X-Forwarded-For', ip)
|
||||
.send({ lastSyncVersion: 0, changes: [] });
|
||||
|
||||
expect(res.status).toBe(429);
|
||||
});
|
||||
|
||||
it('sync 429 responses include rate-limit headers', async () => {
|
||||
const ip = '10.10.0.3';
|
||||
for (let i = 0; i < 10; i++) {
|
||||
await request(app)
|
||||
.post('/api/elements/sync')
|
||||
.set('X-Forwarded-For', ip)
|
||||
.send({ elements: [], timestamp: new Date().toISOString() });
|
||||
}
|
||||
|
||||
const res = await request(app)
|
||||
.post('/api/elements/sync')
|
||||
.set('X-Forwarded-For', ip)
|
||||
.send({ elements: [], timestamp: new Date().toISOString() });
|
||||
|
||||
expect(res.status).toBe(429);
|
||||
expect(res.headers).toHaveProperty('ratelimit-policy');
|
||||
});
|
||||
});
|
||||
@@ -107,6 +107,36 @@ describe('Input validation - sync endpoints', () => {
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('POST /api/elements/sync rejects null elements → 400 not 500', async () => {
|
||||
const res = await request(app)
|
||||
.post('/api/elements/sync')
|
||||
.send({ elements: null });
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.success).toBe(false);
|
||||
});
|
||||
|
||||
it('POST /api/elements/sync rejects missing elements field → 400 not 500', async () => {
|
||||
const res = await request(app)
|
||||
.post('/api/elements/sync')
|
||||
.send({});
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.success).toBe(false);
|
||||
});
|
||||
|
||||
it('POST /api/elements/sync/v2 rejects invalid element type in upsert → 400', async () => {
|
||||
const res = await request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
.send({
|
||||
lastSyncVersion: 0,
|
||||
changes: [{ id: 'test-id', action: 'upsert', element: { type: 'malicious<script>', x: 0, y: 0 } }]
|
||||
});
|
||||
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.success).toBe(false);
|
||||
});
|
||||
|
||||
it('POST /api/elements/sync/v2 rejects non-number lastSyncVersion', async () => {
|
||||
const res = await request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import request from 'supertest';
|
||||
import { initDb, closeDb, setActiveTenant } from '../../src/db.js';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import fs from 'fs';
|
||||
|
||||
let dbPath: string;
|
||||
let app: any;
|
||||
const frontendDir = path.join(process.cwd(), 'dist/frontend');
|
||||
const frontendHtmlPath = path.join(frontendDir, 'index.html');
|
||||
let originalFrontendHtml: string | null = null;
|
||||
let hadFrontendHtml = false;
|
||||
|
||||
beforeEach(async () => {
|
||||
dbPath = path.join(os.tmpdir(), `excalidraw-smoke-test-${Date.now()}-${Math.random().toString(36).slice(2)}.db`);
|
||||
initDb(dbPath);
|
||||
setActiveTenant('default');
|
||||
hadFrontendHtml = fs.existsSync(frontendHtmlPath);
|
||||
originalFrontendHtml = hadFrontendHtml ? fs.readFileSync(frontendHtmlPath, 'utf8') : null;
|
||||
fs.mkdirSync(frontendDir, { recursive: true });
|
||||
fs.writeFileSync(frontendHtmlPath, '<!doctype html><html><head><title>Smoke</title></head><body><div id="root"></div></body></html>');
|
||||
const mod = await import('../../src/server.js');
|
||||
app = mod.default;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete process.env.EXCALIDRAW_API_KEY;
|
||||
closeDb();
|
||||
if (hadFrontendHtml && originalFrontendHtml !== null) {
|
||||
fs.writeFileSync(frontendHtmlPath, originalFrontendHtml);
|
||||
} else {
|
||||
try { fs.unlinkSync(frontendHtmlPath); } catch {}
|
||||
}
|
||||
for (const suffix of ['', '-wal', '-shm']) {
|
||||
try { fs.unlinkSync(dbPath + suffix); } catch {}
|
||||
}
|
||||
});
|
||||
|
||||
describe('Smoke checks', () => {
|
||||
it('serves the health endpoint and frontend shell', async () => {
|
||||
const healthRes = await request(app).get('/health');
|
||||
expect(healthRes.status).toBe(200);
|
||||
expect(healthRes.body.status).toBe('healthy');
|
||||
|
||||
const rootRes = await request(app).get('/');
|
||||
expect(rootRes.status).toBe(200);
|
||||
expect(rootRes.text).toContain('<div id="root"></div>');
|
||||
});
|
||||
|
||||
it('supports a keyed create-list-delete smoke flow', async () => {
|
||||
process.env.EXCALIDRAW_API_KEY = 'smoke-secret';
|
||||
|
||||
const createRes = await request(app)
|
||||
.post('/api/elements')
|
||||
.set('X-API-Key', 'smoke-secret')
|
||||
.send({ id: 'smoke-el', type: 'rectangle', x: 0, y: 0, width: 100, height: 50 });
|
||||
expect(createRes.status).toBe(200);
|
||||
|
||||
const listRes = await request(app)
|
||||
.get('/api/elements')
|
||||
.set('X-API-Key', 'smoke-secret');
|
||||
expect(listRes.status).toBe(200);
|
||||
expect(listRes.body.count).toBe(1);
|
||||
expect(listRes.body.elements[0].id).toBe('smoke-el');
|
||||
|
||||
const searchRes = await request(app)
|
||||
.get('/api/elements/search')
|
||||
.set('X-API-Key', 'smoke-secret')
|
||||
.query({ q: 'rectangle' });
|
||||
expect(searchRes.status).toBe(200);
|
||||
|
||||
const deleteRes = await request(app)
|
||||
.delete('/api/elements/smoke-el')
|
||||
.set('X-API-Key', 'smoke-secret');
|
||||
expect(deleteRes.status).toBe(200);
|
||||
|
||||
const finalListRes = await request(app)
|
||||
.get('/api/elements')
|
||||
.set('X-API-Key', 'smoke-secret');
|
||||
expect(finalListRes.body.count).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -8,6 +8,7 @@ import fs from 'fs';
|
||||
|
||||
let dbPath: string;
|
||||
let app: any;
|
||||
let clientCounter = 0;
|
||||
|
||||
function makeElement(overrides: Partial<ServerElement> = {}): ServerElement {
|
||||
return {
|
||||
@@ -22,12 +23,34 @@ function makeElement(overrides: Partial<ServerElement> = {}): ServerElement {
|
||||
};
|
||||
}
|
||||
|
||||
function nextClientIp(): string {
|
||||
clientCounter += 1;
|
||||
const third = Math.floor(clientCounter / 255);
|
||||
const fourth = (clientCounter % 255) || 1;
|
||||
return `10.42.${third}.${fourth}`;
|
||||
}
|
||||
|
||||
function postSyncV2(body: Record<string, unknown>, clientIp = nextClientIp()) {
|
||||
return request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
.set('X-Forwarded-For', clientIp)
|
||||
.send(body);
|
||||
}
|
||||
|
||||
function postLegacySync(body: Record<string, unknown>, clientIp = nextClientIp()) {
|
||||
return request(app)
|
||||
.post('/api/elements/sync')
|
||||
.set('X-Forwarded-For', clientIp)
|
||||
.send(body);
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
dbPath = path.join(os.tmpdir(), `excalidraw-sync-test-${Date.now()}-${Math.random().toString(36).slice(2)}.db`);
|
||||
initDb(dbPath);
|
||||
setActiveTenant('default');
|
||||
const mod = await import('../../src/server.js');
|
||||
app = mod.default;
|
||||
app.set('trust proxy', 1);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
@@ -47,9 +70,7 @@ describe('Delta sync v2 - deletion flows', () => {
|
||||
|
||||
const v0 = getCurrentSyncVersion();
|
||||
|
||||
const res = await request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
.send({
|
||||
const res = await postSyncV2({
|
||||
lastSyncVersion: v0,
|
||||
changes: [
|
||||
{ id: 'a', action: 'delete' },
|
||||
@@ -73,9 +94,7 @@ describe('Delta sync v2 - deletion flows', () => {
|
||||
|
||||
const v0 = getCurrentSyncVersion();
|
||||
|
||||
const res = await request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
.send({
|
||||
const res = await postSyncV2({
|
||||
lastSyncVersion: v0,
|
||||
changes: [
|
||||
{ id: 'x', action: 'delete' },
|
||||
@@ -89,9 +108,7 @@ describe('Delta sync v2 - deletion flows', () => {
|
||||
});
|
||||
|
||||
it('delete for non-existent element does not crash', async () => {
|
||||
const res = await request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
.send({
|
||||
const res = await postSyncV2({
|
||||
lastSyncVersion: 0,
|
||||
changes: [{ id: 'ghost', action: 'delete' }],
|
||||
});
|
||||
@@ -106,9 +123,7 @@ describe('Delta sync v2 - deletion flows', () => {
|
||||
|
||||
const v0 = getCurrentSyncVersion();
|
||||
|
||||
await request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
.send({
|
||||
await postSyncV2({
|
||||
lastSyncVersion: v0,
|
||||
changes: [{ id: 'persist-1', action: 'delete' }],
|
||||
});
|
||||
@@ -125,9 +140,7 @@ describe('Delta sync v2 - deletion flows', () => {
|
||||
const v0 = getCurrentSyncVersion();
|
||||
|
||||
// Simulate: frontend syncs deletions
|
||||
await request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
.send({
|
||||
await postSyncV2({
|
||||
lastSyncVersion: v0,
|
||||
changes: [
|
||||
{ id: 'reload-1', action: 'delete' },
|
||||
@@ -153,9 +166,7 @@ describe('Delta sync v2 - mixed operations', () => {
|
||||
|
||||
const v0 = getCurrentSyncVersion();
|
||||
|
||||
const res = await request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
.send({
|
||||
const res = await postSyncV2({
|
||||
lastSyncVersion: v0,
|
||||
changes: [
|
||||
{ id: 'a', action: 'delete' },
|
||||
@@ -181,9 +192,7 @@ describe('Delta sync v2 - mixed operations', () => {
|
||||
const v0 = getCurrentSyncVersion();
|
||||
|
||||
// Delete it
|
||||
await request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
.send({
|
||||
await postSyncV2({
|
||||
lastSyncVersion: v0,
|
||||
changes: [{ id: 'revive', action: 'delete' }],
|
||||
});
|
||||
@@ -192,9 +201,7 @@ describe('Delta sync v2 - mixed operations', () => {
|
||||
|
||||
// Re-create it
|
||||
const v1 = getCurrentSyncVersion();
|
||||
await request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
.send({
|
||||
await postSyncV2({
|
||||
lastSyncVersion: v1,
|
||||
changes: [{ id: 'revive', action: 'upsert', element: makeElement({ id: 'revive', x: 999 }) }],
|
||||
});
|
||||
@@ -215,9 +222,7 @@ describe('Delta sync v2 - bidirectional sync', () => {
|
||||
setElement('mcp-2', makeElement({ id: 'mcp-2' }));
|
||||
|
||||
// Client syncs from version 0 with its own new element
|
||||
const res = await request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
.send({
|
||||
const res = await postSyncV2({
|
||||
lastSyncVersion: 0,
|
||||
changes: [
|
||||
{ id: 'fe-1', action: 'upsert', element: makeElement({ id: 'fe-1' }) },
|
||||
@@ -241,9 +246,7 @@ describe('Delta sync v2 - bidirectional sync', () => {
|
||||
const v1 = getCurrentSyncVersion();
|
||||
|
||||
// Client syncs from before the delete
|
||||
const res = await request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
.send({ lastSyncVersion: v0, changes: [] });
|
||||
const res = await postSyncV2({ lastSyncVersion: v0, changes: [] });
|
||||
|
||||
const deleteChange = res.body.serverChanges.find((c: any) => c.id === 'srv-del');
|
||||
expect(deleteChange).toBeDefined();
|
||||
@@ -253,9 +256,7 @@ describe('Delta sync v2 - bidirectional sync', () => {
|
||||
it('excludes client-sent IDs from serverChanges', async () => {
|
||||
setElement('shared', makeElement({ id: 'shared', x: 0 }));
|
||||
|
||||
const res = await request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
.send({
|
||||
const res = await postSyncV2({
|
||||
lastSyncVersion: 0,
|
||||
changes: [
|
||||
{ id: 'shared', action: 'upsert', element: makeElement({ id: 'shared', x: 50 }) },
|
||||
@@ -273,9 +274,7 @@ describe('Delta sync v2 - bidirectional sync', () => {
|
||||
describe('Delta sync v2 - multiple rounds', () => {
|
||||
it('tracks sync version across multiple sync rounds', async () => {
|
||||
// Round 1: create elements
|
||||
const r1 = await request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
.send({
|
||||
const r1 = await postSyncV2({
|
||||
lastSyncVersion: 0,
|
||||
changes: [
|
||||
{ id: 'r1-a', action: 'upsert', element: makeElement({ id: 'r1-a' }) },
|
||||
@@ -287,9 +286,7 @@ describe('Delta sync v2 - multiple rounds', () => {
|
||||
const v1 = r1.body.currentSyncVersion;
|
||||
|
||||
// Round 2: update one, delete one, create one
|
||||
const r2 = await request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
.send({
|
||||
const r2 = await postSyncV2({
|
||||
lastSyncVersion: v1,
|
||||
changes: [
|
||||
{ id: 'r1-a', action: 'upsert', element: makeElement({ id: 'r1-a', x: 999 }) },
|
||||
@@ -315,9 +312,7 @@ describe('Delta sync v2 - multiple rounds', () => {
|
||||
setElement('existing', makeElement({ id: 'existing' }));
|
||||
const v0 = getCurrentSyncVersion();
|
||||
|
||||
const res = await request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
.send({ lastSyncVersion: v0, changes: [] });
|
||||
const res = await postSyncV2({ lastSyncVersion: v0, changes: [] });
|
||||
|
||||
expect(res.body.success).toBe(true);
|
||||
expect(res.body.appliedCount).toBe(0);
|
||||
@@ -337,18 +332,14 @@ describe('Sync version monotonicity', () => {
|
||||
versions.push(getCurrentSyncVersion());
|
||||
|
||||
// Update via sync
|
||||
await request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
.send({
|
||||
await postSyncV2({
|
||||
lastSyncVersion: 0,
|
||||
changes: [{ id: 'mono-a', action: 'upsert', element: makeElement({ id: 'mono-a', x: 50 }) }],
|
||||
});
|
||||
versions.push(getCurrentSyncVersion());
|
||||
|
||||
// Delete via sync
|
||||
await request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
.send({
|
||||
await postSyncV2({
|
||||
lastSyncVersion: versions[versions.length - 1],
|
||||
changes: [{ id: 'mono-a', action: 'delete' }],
|
||||
});
|
||||
@@ -396,9 +387,7 @@ describe('Sync version monotonicity', () => {
|
||||
describe('Concurrent sync requests', () => {
|
||||
it('parallel sync requests all complete without data loss', async () => {
|
||||
const promises = Array.from({ length: 5 }, (_, i) =>
|
||||
request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
.send({
|
||||
postSyncV2({
|
||||
lastSyncVersion: 0,
|
||||
changes: [
|
||||
{ id: `par-${i}`, action: 'upsert', element: makeElement({ id: `par-${i}`, x: i * 100 }) },
|
||||
@@ -423,9 +412,7 @@ describe('Concurrent sync requests', () => {
|
||||
const v0 = getCurrentSyncVersion();
|
||||
|
||||
const promises = Array.from({ length: 5 }, (_, i) =>
|
||||
request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
.send({
|
||||
postSyncV2({
|
||||
lastSyncVersion: v0,
|
||||
changes: [{ id: `pd-${i}`, action: 'delete' }],
|
||||
})
|
||||
@@ -442,14 +429,12 @@ describe('Sync after clear', () => {
|
||||
it('elements created after clear persist correctly', async () => {
|
||||
setElement('pre-clear', makeElement({ id: 'pre-clear' }));
|
||||
|
||||
await request(app).delete('/api/elements/clear');
|
||||
await request(app).delete('/api/elements/clear?confirm=true');
|
||||
expect(getAllElements()).toHaveLength(0);
|
||||
|
||||
const v0 = getCurrentSyncVersion();
|
||||
|
||||
const res = await request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
.send({
|
||||
const res = await postSyncV2({
|
||||
lastSyncVersion: v0,
|
||||
changes: [
|
||||
{ id: 'post-clear', action: 'upsert', element: makeElement({ id: 'post-clear' }) },
|
||||
@@ -480,9 +465,7 @@ describe('POST /api/elements/sync (legacy overwrite)', () => {
|
||||
setElement('old-1', makeElement({ id: 'old-1' }));
|
||||
setElement('old-2', makeElement({ id: 'old-2' }));
|
||||
|
||||
const res = await request(app)
|
||||
.post('/api/elements/sync')
|
||||
.send({
|
||||
const res = await postLegacySync({
|
||||
elements: [makeElement({ id: 'new-1' })],
|
||||
});
|
||||
|
||||
@@ -501,9 +484,7 @@ describe('POST /api/elements/sync (legacy overwrite)', () => {
|
||||
it('overwrite with empty array clears all elements', async () => {
|
||||
setElement('gone', makeElement({ id: 'gone' }));
|
||||
|
||||
await request(app)
|
||||
.post('/api/elements/sync')
|
||||
.send({ elements: [] });
|
||||
await postLegacySync({ elements: [] });
|
||||
|
||||
expect(getAllElements()).toHaveLength(0);
|
||||
|
||||
@@ -527,9 +508,7 @@ describe('GET /api/sync/version', () => {
|
||||
const r1 = await request(app).get('/api/sync/version');
|
||||
const v1 = r1.body.syncVersion;
|
||||
|
||||
await request(app)
|
||||
.post('/api/elements/sync/v2')
|
||||
.send({
|
||||
await postSyncV2({
|
||||
lastSyncVersion: 0,
|
||||
changes: [{ id: 'bump', action: 'upsert', element: makeElement({ id: 'bump' }) }],
|
||||
});
|
||||
|
||||
@@ -194,7 +194,7 @@ describe('Element isolation per tenant', () => {
|
||||
|
||||
// Clear tenant A
|
||||
await request(app)
|
||||
.delete('/api/elements/clear')
|
||||
.delete('/api/elements/clear?confirm=true')
|
||||
.set('X-Tenant-Id', 'clr-a');
|
||||
|
||||
const resA = await request(app)
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import request from 'supertest';
|
||||
import { initDb, closeDb, setActiveTenant } from '../../src/db.js';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import fs from 'fs';
|
||||
|
||||
let dbPath: string;
|
||||
let app: any;
|
||||
|
||||
beforeEach(async () => {
|
||||
dbPath = path.join(os.tmpdir(), `excalidraw-validation-test-${Date.now()}-${Math.random().toString(36).slice(2)}.db`);
|
||||
initDb(dbPath);
|
||||
setActiveTenant('default');
|
||||
const mod = await import('../../src/server.js');
|
||||
app = mod.default;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
closeDb();
|
||||
for (const suffix of ['', '-wal', '-shm']) {
|
||||
try { fs.unlinkSync(dbPath + suffix); } catch {}
|
||||
}
|
||||
});
|
||||
|
||||
// ─── Prototype Pollution ─────────────────────────────────────────────────────
|
||||
// The sanitizeBody middleware strips dangerous keys from req.body and returns
|
||||
// 400 when they are detected, so that nothing reaches the route handlers.
|
||||
|
||||
describe('Prototype pollution prevention', () => {
|
||||
it('rejects __proto__ key in POST /api/elements → 400', async () => {
|
||||
// Send raw JSON string (real attack vector — not via JS object)
|
||||
const res = await request(app)
|
||||
.post('/api/elements')
|
||||
.set('Content-Type', 'application/json')
|
||||
.send('{"__proto__":{"admin":true},"type":"rectangle","x":0,"y":0,"width":100,"height":50}');
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects constructor key in POST /api/elements → 400', async () => {
|
||||
const res = await request(app)
|
||||
.post('/api/elements')
|
||||
.set('Content-Type', 'application/json')
|
||||
.send('{"constructor":{"name":"pwned"},"type":"rectangle","x":0,"y":0,"width":100,"height":50}');
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('rejects __proto__ key in PUT /api/elements/:id → 400', async () => {
|
||||
const res = await request(app)
|
||||
.put('/api/elements/some-id')
|
||||
.set('Content-Type', 'application/json')
|
||||
.send('{"__proto__":{"admin":true},"x":10,"y":10}');
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('allows clean body in POST /api/elements → not 400', async () => {
|
||||
const res = await request(app)
|
||||
.post('/api/elements')
|
||||
.send({ type: 'rectangle', x: 0, y: 0, width: 100, height: 50 });
|
||||
expect(res.status).not.toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Mermaid Injection ───────────────────────────────────────────────────────
|
||||
|
||||
describe('Mermaid diagram validation', () => {
|
||||
it('rejects diagram > 50KB → 400', async () => {
|
||||
const res = await request(app)
|
||||
.post('/api/elements/from-mermaid')
|
||||
.send({ mermaidDiagram: 'graph TD\n' + 'A-->B\n'.repeat(9000) }); // ~54KB > 50KB limit
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.success).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects config with > 10 keys → 400', async () => {
|
||||
const config: Record<string, number> = {};
|
||||
for (let i = 0; i < 15; i++) config[`key${i}`] = i;
|
||||
const res = await request(app)
|
||||
.post('/api/elements/from-mermaid')
|
||||
.send({ mermaidDiagram: 'graph TD\nA-->B', config });
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
|
||||
it('accepts valid small diagram → not 400', async () => {
|
||||
const res = await request(app)
|
||||
.post('/api/elements/from-mermaid')
|
||||
.send({ mermaidDiagram: 'graph TD\nA-->B' });
|
||||
// 200 (no WS client) or 503 (no frontend connected) — both valid
|
||||
expect(res.status).not.toBe(400);
|
||||
expect(res.status).not.toBe(413);
|
||||
});
|
||||
|
||||
it('rejects non-string mermaid diagram → 400', async () => {
|
||||
const res = await request(app)
|
||||
.post('/api/elements/from-mermaid')
|
||||
.send({ mermaidDiagram: 12345 });
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Search Filter Sanitization ──────────────────────────────────────────────
|
||||
|
||||
describe('Search filter sanitization', () => {
|
||||
it('handles empty search query without crashing → 200', async () => {
|
||||
const res = await request(app).get('/api/elements/search');
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it('search with unmatched quote returns 400, not 500', async () => {
|
||||
const res = await request(app)
|
||||
.get('/api/elements/search')
|
||||
.query({ q: '"unterminated' });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error).toBe('Invalid search query');
|
||||
});
|
||||
|
||||
it("search with bare FTS operator 'AND' returns 400, not 500", async () => {
|
||||
const res = await request(app)
|
||||
.get('/api/elements/search')
|
||||
.query({ q: 'AND' });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error).toBe('Invalid search query');
|
||||
});
|
||||
|
||||
it("search with 'NEAR/3' returns 400, not 500", async () => {
|
||||
const res = await request(app)
|
||||
.get('/api/elements/search')
|
||||
.query({ q: 'NEAR/3' });
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.error).toBe('Invalid search query');
|
||||
});
|
||||
|
||||
it("search 400 response does not contain 'fts5' or 'sqlite' in error message", async () => {
|
||||
const res = await request(app)
|
||||
.get('/api/elements/search')
|
||||
.query({ q: 'AND' });
|
||||
expect(res.status).toBe(400);
|
||||
expect(String(res.body.error).toLowerCase()).not.toContain('fts5');
|
||||
expect(String(res.body.error).toLowerCase()).not.toContain('sqlite');
|
||||
});
|
||||
|
||||
it('search with valid query still returns 200', async () => {
|
||||
const createRes = await request(app)
|
||||
.post('/api/elements')
|
||||
.send({ type: 'rectangle', x: 0, y: 0, width: 100, height: 50 });
|
||||
expect(createRes.status).toBe(200);
|
||||
|
||||
const res = await request(app)
|
||||
.get('/api/elements/search')
|
||||
.query({ q: 'rectangle' });
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
// ─── Import Validation ───────────────────────────────────────────────────────
|
||||
|
||||
describe('POST /api/elements/import validation', () => {
|
||||
it('rejects non-array elements in import body → 400', async () => {
|
||||
const res = await request(app)
|
||||
.post('/api/elements/import')
|
||||
.send({ elements: 'not-an-array' });
|
||||
// 400 = validation rejected, 404 = endpoint doesn't exist — both are safe
|
||||
expect([400, 404]).toContain(res.status);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,250 @@
|
||||
import { describe, it, expect, beforeAll, afterAll, beforeEach } from 'vitest';
|
||||
import {
|
||||
initDb,
|
||||
closeDb,
|
||||
clearElements,
|
||||
ensureTenant,
|
||||
getDefaultProjectForTenant,
|
||||
setActiveTenant,
|
||||
setElement,
|
||||
} from '../../src/db.js';
|
||||
import type { ServerElement } from '../../src/types.js';
|
||||
import WebSocket from 'ws';
|
||||
import path from 'path';
|
||||
import os from 'os';
|
||||
import fs from 'fs';
|
||||
|
||||
let dbPath: string;
|
||||
let port: number;
|
||||
let startCanvasServer: () => Promise<void>;
|
||||
let stopCanvasServer: () => Promise<void>;
|
||||
|
||||
function connectAndCollect(waitMs = 300): Promise<{ ws: WebSocket; messages: any[] }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const messages: any[] = [];
|
||||
const ws = new WebSocket(`ws://localhost:${port}`);
|
||||
ws.on('message', (raw) => messages.push(JSON.parse(raw.toString())));
|
||||
ws.on('open', () => setTimeout(() => resolve({ ws, messages }), waitMs));
|
||||
ws.on('error', reject);
|
||||
});
|
||||
}
|
||||
|
||||
function waitForMessageOfType(ws: WebSocket, type: string, timeoutMs = 5000): Promise<any> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => reject(new Error(`Timeout waiting for message type: ${type}`)), timeoutMs);
|
||||
const handler = (data: WebSocket.RawData) => {
|
||||
const msg = JSON.parse(data.toString());
|
||||
if (msg.type === type) {
|
||||
clearTimeout(timer);
|
||||
ws.off('message', handler);
|
||||
resolve(msg);
|
||||
}
|
||||
};
|
||||
ws.on('message', handler);
|
||||
});
|
||||
}
|
||||
|
||||
function waitForClose(ws: WebSocket, timeoutMs = 7000): Promise<{ code: number; reason: string }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => reject(new Error('Timeout waiting for close')), timeoutMs);
|
||||
ws.on('close', (code, reason) => {
|
||||
clearTimeout(timer);
|
||||
resolve({ code, reason: reason.toString() });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function collectMessagesFor(ws: WebSocket, durationMs: number): Promise<any[]> {
|
||||
return new Promise((resolve) => {
|
||||
const messages: any[] = [];
|
||||
const handler = (data: WebSocket.RawData) => messages.push(JSON.parse(data.toString()));
|
||||
ws.on('message', handler);
|
||||
setTimeout(() => {
|
||||
ws.off('message', handler);
|
||||
resolve(messages);
|
||||
}, durationMs);
|
||||
});
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
port = 3400 + Math.floor(Math.random() * 100);
|
||||
process.env.CANVAS_PORT = String(port);
|
||||
process.env.HOST = 'localhost';
|
||||
|
||||
dbPath = path.join(os.tmpdir(), `excalidraw-ws-auth-test-${Date.now()}.db`);
|
||||
initDb(dbPath);
|
||||
|
||||
const mod = await import('../../src/server.js');
|
||||
startCanvasServer = mod.startCanvasServer;
|
||||
stopCanvasServer = mod.stopCanvasServer;
|
||||
await startCanvasServer();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
delete process.env.EXCALIDRAW_API_KEY;
|
||||
await stopCanvasServer();
|
||||
closeDb();
|
||||
for (const suffix of ['', '-wal', '-shm']) {
|
||||
try { fs.unlinkSync(dbPath + suffix); } catch {}
|
||||
}
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
delete process.env.EXCALIDRAW_API_KEY;
|
||||
setActiveTenant('default');
|
||||
clearElements();
|
||||
});
|
||||
|
||||
describe('WebSocket auth gate', () => {
|
||||
it('auth enabled: WS connection receives auth_required and no element data before hello', async () => {
|
||||
process.env.EXCALIDRAW_API_KEY = 'test-secret';
|
||||
const { ws, messages } = await connectAndCollect();
|
||||
|
||||
const types = messages.map(m => m.type);
|
||||
expect(types).toContain('auth_required');
|
||||
expect(types).not.toContain('tenant_switched');
|
||||
expect(types).not.toContain('initial_elements');
|
||||
expect(types).not.toContain('files_added');
|
||||
expect(types).not.toContain('sync_status');
|
||||
|
||||
ws.terminate();
|
||||
});
|
||||
|
||||
it('auth enabled: WS closes with 4001 if no valid hello arrives within 5s', async () => {
|
||||
process.env.EXCALIDRAW_API_KEY = 'test-secret';
|
||||
const { ws, messages } = await connectAndCollect();
|
||||
expect(messages.some(m => m.type === 'auth_required')).toBe(true);
|
||||
|
||||
const authFailedPromise = waitForMessageOfType(ws, 'auth_failed', 7000);
|
||||
const closePromise = waitForClose(ws, 7000);
|
||||
const [authFailed, close] = await Promise.all([authFailedPromise, closePromise]);
|
||||
|
||||
expect(authFailed.reason).toBe('timeout');
|
||||
expect(close.code).toBe(4001);
|
||||
});
|
||||
|
||||
it('auth enabled: hello with valid apiKey and no tenantId bootstraps the active tenant', async () => {
|
||||
process.env.EXCALIDRAW_API_KEY = 'test-secret';
|
||||
ensureTenant('boot-tenant', 'Boot Tenant', 'workspace/boot-tenant');
|
||||
setActiveTenant('boot-tenant');
|
||||
|
||||
const { ws, messages } = await connectAndCollect();
|
||||
expect(messages.some(m => m.type === 'auth_required')).toBe(true);
|
||||
|
||||
const ackPromise = waitForMessageOfType(ws, 'hello_ack', 5000);
|
||||
ws.send(JSON.stringify({ type: 'hello', apiKey: 'test-secret' }));
|
||||
const ack = await ackPromise;
|
||||
|
||||
expect(ack.tenantId).toBe('boot-tenant');
|
||||
expect(ack.tenant.id).toBe('boot-tenant');
|
||||
expect(ack.projectId).toBe(getDefaultProjectForTenant('boot-tenant'));
|
||||
|
||||
ws.close();
|
||||
});
|
||||
|
||||
it('auth enabled: hello with wrong apiKey sends auth_failed and closes 4001', async () => {
|
||||
process.env.EXCALIDRAW_API_KEY = 'test-secret';
|
||||
const { ws, messages } = await connectAndCollect();
|
||||
expect(messages.some(m => m.type === 'auth_required')).toBe(true);
|
||||
|
||||
const authFailedPromise = waitForMessageOfType(ws, 'auth_failed', 5000);
|
||||
const closePromise = waitForClose(ws, 5000);
|
||||
|
||||
ws.send(JSON.stringify({ type: 'hello', apiKey: 'wrong-key' }));
|
||||
|
||||
const [authFailed, close] = await Promise.all([authFailedPromise, closePromise]);
|
||||
expect(authFailed.reason).toBe('invalid_key');
|
||||
expect(close.code).toBe(4001);
|
||||
});
|
||||
|
||||
it('auth enabled: hello with valid apiKey and unknown tenantId sends error and no elements', async () => {
|
||||
process.env.EXCALIDRAW_API_KEY = 'test-secret';
|
||||
const { ws, messages } = await connectAndCollect();
|
||||
expect(messages.some(m => m.type === 'auth_required')).toBe(true);
|
||||
|
||||
const errorPromise = waitForMessageOfType(ws, 'error', 5000);
|
||||
ws.send(JSON.stringify({ type: 'hello', apiKey: 'test-secret', tenantId: 'missing-tenant' }));
|
||||
|
||||
const error = await errorPromise;
|
||||
expect(error.message).toBe('Unknown tenant');
|
||||
|
||||
const trailingMessages = await collectMessagesFor(ws, 300);
|
||||
expect(trailingMessages.some(msg => msg.type === 'hello_ack')).toBe(false);
|
||||
|
||||
ws.close();
|
||||
});
|
||||
|
||||
it('auth enabled: invalid projectId falls back to the tenant default project', async () => {
|
||||
process.env.EXCALIDRAW_API_KEY = 'test-secret';
|
||||
ensureTenant('scope-a', 'Scope A', 'workspace/scope-a');
|
||||
ensureTenant('scope-b', 'Scope B', 'workspace/scope-b');
|
||||
|
||||
const defaultProjectId = getDefaultProjectForTenant('scope-a');
|
||||
const otherProjectId = getDefaultProjectForTenant('scope-b');
|
||||
|
||||
setElement('scope-a-element', {
|
||||
id: 'scope-a-element',
|
||||
type: 'rectangle',
|
||||
x: 10,
|
||||
y: 10,
|
||||
width: 50,
|
||||
height: 50,
|
||||
version: 1,
|
||||
} as ServerElement, defaultProjectId);
|
||||
setElement('scope-b-element', {
|
||||
id: 'scope-b-element',
|
||||
type: 'ellipse',
|
||||
x: 20,
|
||||
y: 20,
|
||||
width: 60,
|
||||
height: 60,
|
||||
version: 1,
|
||||
} as ServerElement, otherProjectId);
|
||||
|
||||
const { ws, messages } = await connectAndCollect();
|
||||
expect(messages.some(m => m.type === 'auth_required')).toBe(true);
|
||||
|
||||
const ackPromise = waitForMessageOfType(ws, 'hello_ack', 5000);
|
||||
ws.send(JSON.stringify({
|
||||
type: 'hello',
|
||||
apiKey: 'test-secret',
|
||||
tenantId: 'scope-a',
|
||||
projectId: otherProjectId,
|
||||
}));
|
||||
|
||||
const ack = await ackPromise;
|
||||
expect(ack.tenantId).toBe('scope-a');
|
||||
expect(ack.projectId).toBe(defaultProjectId);
|
||||
expect(ack.elements.map((element: any) => element.id)).toContain('scope-a-element');
|
||||
expect(ack.elements.map((element: any) => element.id)).not.toContain('scope-b-element');
|
||||
|
||||
ws.close();
|
||||
});
|
||||
|
||||
it('auth disabled: WS connection receives tenant_switched and initial_elements immediately', async () => {
|
||||
delete process.env.EXCALIDRAW_API_KEY;
|
||||
const { ws, messages } = await connectAndCollect();
|
||||
|
||||
const types = messages.map(m => m.type);
|
||||
expect(types).toContain('tenant_switched');
|
||||
expect(types).toContain('initial_elements');
|
||||
expect(types).toContain('sync_status');
|
||||
expect(types).not.toContain('auth_required');
|
||||
|
||||
ws.close();
|
||||
});
|
||||
|
||||
it('auth disabled: hello without apiKey still works and receives hello_ack', async () => {
|
||||
delete process.env.EXCALIDRAW_API_KEY;
|
||||
const { ws } = await connectAndCollect();
|
||||
const ackPromise = waitForMessageOfType(ws, 'hello_ack', 5000);
|
||||
|
||||
ws.send(JSON.stringify({ type: 'hello', tenantId: 'default' }));
|
||||
|
||||
const ack = await ackPromise;
|
||||
expect(ack.tenantId).toBe('default');
|
||||
expect(Array.isArray(ack.elements)).toBe(true);
|
||||
|
||||
ws.close();
|
||||
});
|
||||
});
|
||||
@@ -198,7 +198,7 @@ describe('WebSocket broadcasts', () => {
|
||||
|
||||
const clearedPromise = waitForMessageOfType(ws, 'canvas_cleared');
|
||||
|
||||
await fetch(`http://localhost:${port}/api/elements/clear`, { method: 'DELETE' });
|
||||
await fetch(`http://localhost:${port}/api/elements/clear?confirm=true`, { method: 'DELETE' });
|
||||
|
||||
const msg = await clearedPromise;
|
||||
expect(msg.type).toBe('canvas_cleared');
|
||||
|
||||
@@ -1,9 +1,19 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
const API = 'http://localhost:3100';
|
||||
const API = 'http://127.0.0.1:3100';
|
||||
|
||||
async function resetCanvas(request: any): Promise<void> {
|
||||
const listRes = await request.get(`${API}/api/elements`);
|
||||
const listBody = await listRes.json();
|
||||
await Promise.all(
|
||||
(listBody.elements ?? []).map((element: { id: string }) =>
|
||||
request.delete(`${API}/api/elements/${element.id}`)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
test.beforeEach(async ({ request }) => {
|
||||
await request.delete(`${API}/api/elements/clear`);
|
||||
await resetCanvas(request);
|
||||
});
|
||||
|
||||
// ─── Fix 3: Hello handshake → real-time sync works immediately ──
|
||||
|
||||
@@ -1,9 +1,19 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
const API = 'http://localhost:3100';
|
||||
const API = 'http://127.0.0.1:3100';
|
||||
|
||||
async function resetCanvas(request: any): Promise<void> {
|
||||
const listRes = await request.get(`${API}/api/elements`);
|
||||
const listBody = await listRes.json();
|
||||
await Promise.all(
|
||||
(listBody.elements ?? []).map((element: { id: string }) =>
|
||||
request.delete(`${API}/api/elements/${element.id}`)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
test.beforeEach(async ({ request }) => {
|
||||
await request.delete(`${API}/api/elements/clear`);
|
||||
await resetCanvas(request);
|
||||
});
|
||||
|
||||
// ─── Page Load ───────────────────────────────────────────────
|
||||
@@ -103,7 +113,7 @@ test.describe('Element CRUD via API', () => {
|
||||
},
|
||||
});
|
||||
|
||||
const clearRes = await request.delete(`${API}/api/elements/clear`);
|
||||
const clearRes = await request.delete(`${API}/api/elements/clear?confirm=true`);
|
||||
expect(clearRes.ok()).toBe(true);
|
||||
const clearBody = await clearRes.json();
|
||||
expect(clearBody.count).toBe(2);
|
||||
@@ -150,7 +160,7 @@ test.describe('Real-time Canvas Sync', () => {
|
||||
});
|
||||
await page.waitForTimeout(300);
|
||||
|
||||
await request.delete(`${API}/api/elements/clear`);
|
||||
await request.delete(`${API}/api/elements/clear?confirm=true`);
|
||||
await page.waitForTimeout(500);
|
||||
|
||||
const listRes = await request.get(`${API}/api/elements`);
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
|
||||
const API = 'http://127.0.0.1:3100';
|
||||
|
||||
test.beforeEach(async ({ request }) => {
|
||||
await request.put(`${API}/api/settings/clear_canvas_skip_confirm`, {
|
||||
data: { value: 'false' },
|
||||
});
|
||||
await request.delete(`${API}/api/elements/clear?confirm=true`);
|
||||
});
|
||||
|
||||
test.describe('Clear canvas preference', () => {
|
||||
test('checking "Don\'t ask again" persists and skips the next confirmation dialog', async ({ page, request }) => {
|
||||
await request.post(`${API}/api/elements`, {
|
||||
data: { id: 'pref-el-1', type: 'rectangle', x: 0, y: 0, width: 100, height: 50 },
|
||||
});
|
||||
|
||||
await page.goto('/');
|
||||
await expect(page.locator('.status span')).toContainText('Connected', { timeout: 5000 });
|
||||
|
||||
await page.locator('button:has-text("Clear Canvas")').click();
|
||||
await expect(page.locator('.confirm-dialog')).toBeVisible();
|
||||
await page.locator('.confirm-checkbox-label input').check();
|
||||
await page.locator('.confirm-dialog button:has-text("Clear")').click();
|
||||
await expect(page.locator('.confirm-dialog')).not.toBeVisible();
|
||||
|
||||
await expect.poll(async () => {
|
||||
const res = await request.get(`${API}/api/settings/clear_canvas_skip_confirm`);
|
||||
const body = await res.json() as { value?: string };
|
||||
return body.value;
|
||||
}).toBe('true');
|
||||
|
||||
await request.post(`${API}/api/elements`, {
|
||||
data: { id: 'pref-el-2', type: 'rectangle', x: 20, y: 20, width: 80, height: 40 },
|
||||
});
|
||||
|
||||
await page.locator('button:has-text("Clear Canvas")').click();
|
||||
await expect(page.locator('.confirm-dialog')).not.toBeVisible();
|
||||
|
||||
await expect.poll(async () => {
|
||||
const res = await request.get(`${API}/api/elements`);
|
||||
const body = await res.json() as { count: number };
|
||||
return body.count;
|
||||
}).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,19 @@
|
||||
import { test, expect, type Page } from '@playwright/test';
|
||||
|
||||
const API = 'http://localhost:3100';
|
||||
const API = 'http://127.0.0.1:3100';
|
||||
|
||||
async function resetCanvas(request: any): Promise<void> {
|
||||
const listRes = await request.get(`${API}/api/elements`);
|
||||
const listBody = await listRes.json();
|
||||
await Promise.all(
|
||||
(listBody.elements ?? []).map((element: { id: string }) =>
|
||||
request.delete(`${API}/api/elements/${element.id}`)
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
test.beforeEach(async ({ request }) => {
|
||||
await request.delete(`${API}/api/elements/clear`);
|
||||
await resetCanvas(request);
|
||||
});
|
||||
|
||||
// ─── Helpers ────────────────────────────────────────────────
|
||||
@@ -357,7 +367,7 @@ test.describe('Clear canvas persistence', () => {
|
||||
await page.waitForTimeout(500);
|
||||
|
||||
// Clear
|
||||
await request.delete(`${API}/api/elements/clear`);
|
||||
await request.delete(`${API}/api/elements/clear?confirm=true`);
|
||||
await page.waitForTimeout(500);
|
||||
|
||||
// Verify gone
|
||||
@@ -394,7 +404,7 @@ test.describe('Snapshots E2E', () => {
|
||||
expect((await snapRes.json()).success).toBe(true);
|
||||
|
||||
// Clear
|
||||
await request.delete(`${API}/api/elements/clear`);
|
||||
await request.delete(`${API}/api/elements/clear?confirm=true`);
|
||||
expect(await getServerElementCount(request)).toBe(0);
|
||||
|
||||
// List snapshots
|
||||
|
||||
Reference in New Issue
Block a user