16 Commits

Author SHA1 Message Date
b1fe286be8 Merge pull request 'Plugins' (#14) from Plugins into main
All checks were successful
Queue Release Build / prepare (push) Successful in 20s
Deploy Web Apps / deploy (push) Successful in 8m30s
Queue Release Build / build-windows (push) Successful in 25m24s
Queue Release Build / build-linux (push) Successful in 41m32s
Queue Release Build / finalize (push) Successful in 30s
Reviewed-on: #14
2026-04-29 23:18:22 +00:00
Myx
0a714428f6 docs: improve doucmentation
improve doucmentation and fix small store changes
2026-04-30 01:16:48 +02:00
Myx
3f92e74350 feat: expose more apis 2026-04-29 23:39:09 +02:00
Myx
fa2cca6fa4 fix: improve plugins functionality with server management 2026-04-29 20:33:54 +02:00
Myx
b8f6d58d99 test: repair broken tests 2026-04-29 19:05:38 +02:00
Myx
e1ac1d1bc0 feat: server image 2026-04-29 18:54:08 +02:00
Myx
3d81c34159 feat: Add browser documentation 2026-04-29 17:15:01 +02:00
Myx
d261bac0ed feat: plugins v1.7 2026-04-29 15:24:56 +02:00
Myx
eabbc08896 feat: plugins v1.5 2026-04-29 01:14:30 +02:00
Myx
6920f93b41 feat: plugins v1 2026-04-29 01:14:14 +02:00
Myx
ec3802ade6 test: fix broken dm test
All checks were successful
Queue Release Build / prepare (push) Successful in 23s
Deploy Web Apps / deploy (push) Successful in 6m5s
Queue Release Build / build-windows (push) Successful in 17m1s
Queue Release Build / build-linux (push) Successful in 29m15s
Queue Release Build / finalize (push) Successful in 38s
2026-04-27 22:48:45 +02:00
Myx
66c6f34cd3 feat: Add game activity status (Experimental)
All checks were successful
Queue Release Build / prepare (push) Successful in 21s
Deploy Web Apps / deploy (push) Successful in 5m14s
Queue Release Build / build-windows (push) Successful in 16m18s
Queue Release Build / build-linux (push) Successful in 29m20s
Queue Release Build / finalize (push) Successful in 36s
2026-04-27 11:02:34 +02:00
Myx
3858beb28e feat: Data management 2026-04-27 03:29:41 +02:00
Myx
1b91eacb5b feat: Theme studio v2 2026-04-27 03:02:13 +02:00
Myx
11c2588e45 feat: Add pm 2026-04-27 01:02:39 +02:00
Myx
bc2fa7de22 fix: multiple bug fixes
isolated users, db backup, weird disconnect issues for long voice sessions,
2026-04-26 22:54:13 +02:00
346 changed files with 53733 additions and 1606 deletions

View File

@@ -52,7 +52,7 @@ jobs:
uses: https://github.com/actions/cache@v4 uses: https://github.com/actions/cache@v4
with: with:
path: /root/.npm path: /root/.npm
key: npm-linux-${{ hashFiles('package-lock.json', 'server/package-lock.json') }} key: npm-linux-${{ hashFiles('package-lock.json', 'server/package-lock.json', 'docs-site/package-lock.json') }}
restore-keys: npm-linux- restore-keys: npm-linux-
- name: Restore Electron cache - name: Restore Electron cache
@@ -71,6 +71,7 @@ jobs:
apt-get update && apt-get install -y --no-install-recommends zip apt-get update && apt-get install -y --no-install-recommends zip
npm ci npm ci
cd server && npm ci cd server && npm ci
cd ../docs-site && npm ci
- name: Set CI release version - name: Set CI release version
run: > run: >
@@ -83,6 +84,7 @@ jobs:
cd toju-app cd toju-app
npx ng build --configuration production --base-href='./' npx ng build --configuration production --base-href='./'
cd .. cd ..
npm run build:docs
npx --package typescript tsc -p tsconfig.electron.json npx --package typescript tsc -p tsconfig.electron.json
cd server cd server
node ../tools/sync-server-build-version.js node ../tools/sync-server-build-version.js
@@ -124,7 +126,7 @@ jobs:
uses: https://github.com/actions/cache@v4 uses: https://github.com/actions/cache@v4
with: with:
path: ~/AppData/Local/npm-cache path: ~/AppData/Local/npm-cache
key: npm-windows-${{ hashFiles('package-lock.json', 'server/package-lock.json') }} key: npm-windows-${{ hashFiles('package-lock.json', 'server/package-lock.json', 'docs-site/package-lock.json') }}
restore-keys: npm-windows- restore-keys: npm-windows-
- name: Restore Electron cache - name: Restore Electron cache
@@ -142,6 +144,7 @@ jobs:
run: | run: |
npm ci npm ci
npm ci --prefix server npm ci --prefix server
npm ci --prefix docs-site
- name: Set CI release version - name: Set CI release version
run: > run: >
@@ -154,6 +157,7 @@ jobs:
Push-Location "toju-app" Push-Location "toju-app"
npx ng build --configuration production --base-href='./' npx ng build --configuration production --base-href='./'
Pop-Location Pop-Location
npm run build:docs
npx --package typescript tsc -p tsconfig.electron.json npx --package typescript tsc -p tsconfig.electron.json
Push-Location server Push-Location server
node ../tools/sync-server-build-version.js node ../tools/sync-server-build-version.js
@@ -194,6 +198,7 @@ jobs:
Copy-Item -Path (Join-Path $projectRoot 'package.json') -Destination (Join-Path $electronBuilderWorkspace 'package.json') -Force Copy-Item -Path (Join-Path $projectRoot 'package.json') -Destination (Join-Path $electronBuilderWorkspace 'package.json') -Force
Copy-Item -Path (Join-Path $projectRoot 'package-lock.json') -Destination (Join-Path $electronBuilderWorkspace 'package-lock.json') -Force Copy-Item -Path (Join-Path $projectRoot 'package-lock.json') -Destination (Join-Path $electronBuilderWorkspace 'package-lock.json') -Force
Invoke-RoboCopy (Join-Path $projectRoot 'dist') (Join-Path $electronBuilderWorkspace 'dist') Invoke-RoboCopy (Join-Path $projectRoot 'dist') (Join-Path $electronBuilderWorkspace 'dist')
Invoke-RoboCopy (Join-Path $projectRoot 'docs-site/build') (Join-Path $electronBuilderWorkspace 'docs-site/build')
Invoke-RoboCopy (Join-Path $projectRoot 'images') (Join-Path $electronBuilderWorkspace 'images') Invoke-RoboCopy (Join-Path $projectRoot 'images') (Join-Path $electronBuilderWorkspace 'images')
Invoke-RoboCopy (Join-Path $projectRoot 'node_modules') (Join-Path $electronBuilderWorkspace 'node_modules') Invoke-RoboCopy (Join-Path $projectRoot 'node_modules') (Join-Path $electronBuilderWorkspace 'node_modules')

3
.gitignore vendored
View File

@@ -16,6 +16,7 @@ yarn-error.log
dist-electron dist-electron
node_modules/* node_modules/*
*server/node_modules/* *server/node_modules/*
/docs-site/node_modules/
.angular .angular
# IDEs and editors # IDEs and editors
.idea/ .idea/
@@ -39,6 +40,8 @@ node_modules/*
.sass-cache/ .sass-cache/
/connect.lock /connect.lock
/coverage /coverage
/docs-site/.docusaurus/
/docs-site/build/
/libpeerconnection.log /libpeerconnection.log
testem.log testem.log
/typings /typings

View File

@@ -13,13 +13,15 @@ MetoYou is a desktop-first chat stack managed as an npm monorepo. The repository
| `server/` | Signaling server, server-directory API, and websocket runtime | [server/README.md](server/README.md) | | `server/` | Signaling server, server-directory API, and websocket runtime | [server/README.md](server/README.md) |
| `e2e/` | Playwright end-to-end coverage for the product client | [e2e/README.md](e2e/README.md) | | `e2e/` | Playwright end-to-end coverage for the product client | [e2e/README.md](e2e/README.md) |
| `website/` | Angular 19 marketing site served separately from the product client | [website/README.md](website/README.md) | | `website/` | Angular 19 marketing site served separately from the product client | [website/README.md](website/README.md) |
| `docs-site/` | Docusaurus app and plugin documentation served by the Electron Local API | [docs-site/docs/intro.md](docs-site/docs/intro.md) |
## Install ## Install
1. Run `npm install` from the repository root. 1. Run `npm install` from the repository root.
2. Run `cd server && npm install` for the server package. 2. Run `cd server && npm install` for the server package.
3. If you need to work on the marketing site, run `cd website && npm install`. 3. If you need to work on the marketing site, run `cd website && npm install`.
4. Copy `.env.example` to `.env`. 4. If you need to work on the Docusaurus docs, run `cd docs-site && npm install`.
5. Copy `.env.example` to `.env`.
## Configuration ## Configuration
@@ -36,8 +38,9 @@ MetoYou is a desktop-first chat stack managed as an npm monorepo. The repository
- `npm run electron:dev` starts the Angular product client and Electron together. - `npm run electron:dev` starts the Angular product client and Electron together.
- `npm run server:dev` starts only the server with reload. - `npm run server:dev` starts only the server with reload.
- `npm run build` builds the Angular product client to `dist/client`. - `npm run build` builds the Angular product client to `dist/client`.
- `npm run build:docs` builds the Docusaurus documentation site to `docs-site/build`.
- `npm run build:electron` builds the Electron code to `dist/electron`. - `npm run build:electron` builds the Electron code to `dist/electron`.
- `npm run build:all` builds the product client, Electron, and server. - `npm run build:all` builds the product client, Docusaurus docs, Electron, and server.
- `npm run test` runs the product-client Vitest suite. - `npm run test` runs the product-client Vitest suite.
- `npm run lint` runs ESLint across the repo. - `npm run lint` runs ESLint across the repo.
- `npm run lint:fix` formats Angular templates, sorts template properties, and applies ESLint fixes. - `npm run lint:fix` formats Angular templates, sorts template properties, and applies ESLint fixes.
@@ -54,6 +57,7 @@ MetoYou is a desktop-first chat stack managed as an npm monorepo. The repository
| `server/src/` | Express app, websocket runtime, config, CQRS, and persistence layers | | `server/src/` | Express app, websocket runtime, config, CQRS, and persistence layers |
| `e2e/` | Playwright tests, helpers, fixtures, and page objects | | `e2e/` | Playwright tests, helpers, fixtures, and page objects |
| `website/src/` | Marketing-site pages, assets, and SSR entry points | | `website/src/` | Marketing-site pages, assets, and SSR entry points |
| `docs-site/` | Docusaurus source for Electron-hosted application and plugin documentation |
| `tools/` | Build, release, formatting, and packaging scripts | | `tools/` | Build, release, formatting, and packaging scripts |
## Product Client Docs ## Product Client Docs

View File

@@ -0,0 +1,75 @@
---
sidebar_position: 3
---
# Desktop and Local API
## Electron Hosting Model
The desktop app hosts local documentation through the existing Electron Local API server. This server is implemented with Node's `http` module in the Electron main process and uses async request handlers for routing, file reads, and streamed responses.
The endpoint is manually activated. Opening the Docusaurus docs from the desktop title bar enables the local server and docs endpoint if necessary, then opens the system browser to the generated static site.
This avoids:
- starting a Docusaurus development server inside Electron;
- blocking the renderer thread;
- serving docs from a remote host;
- exposing the endpoint unless the user chooses to activate it.
## Local Server Settings
| Setting | Default | Meaning |
| --- | --- | --- |
| `enabled` | `false` | Starts or stops the local HTTP server. |
| `port` | `17878` | Listening port. |
| `exposeOnLan` | `false` | Uses `127.0.0.1` by default; when true, binds to `0.0.0.0`. |
| `scalarEnabled` | `false` | Enables `/docs` for the Scalar OpenAPI reference. |
| `docusaurusEnabled` | `false` | Enables `/docusaurus` for the built Docusaurus documentation. |
| `allowedSignalingServers` | `[]` | Server URLs allowed for Local API login. |
## Routes
| Endpoint | Purpose | Auth |
| --- | --- | --- |
| `GET /api/health` | Liveness, app version, timestamp, and LAN exposure status. | No |
| `GET /api/openapi.json` | OpenAPI 3.1 document for local automation clients. | No |
| `GET /docs` | Scalar API reference when Scalar docs are enabled. | No |
| `GET /docusaurus` | Docusaurus documentation entrypoint when Docusaurus docs are enabled. | No |
| `GET /docusaurus/*` | Static Docusaurus assets and pages. | No |
| `POST /api/auth/login` | Exchanges username, password, and allowed signaling server URL for a local bearer token. | No |
| `POST /api/auth/logout` | Revokes the current local bearer token. | Bearer |
| `GET /api/profile` | Reads the current local user profile. | Bearer |
| `GET /api/rooms` | Lists rooms known to this device. | Bearer |
| `GET /api/rooms/{roomId}/messages` | Reads local room messages with `limit` and `offset`. | Bearer |
## Authentication Flow
1. Add trusted signaling server URLs in desktop settings.
2. Start the Local API server.
3. Call `POST /api/auth/login` with `username`, `password`, and `serverUrl`.
4. MetoYou validates credentials through the signaling server.
5. The desktop app issues an opaque local bearer token.
6. Use `Authorization: Bearer <token>` for protected routes.
Bearer tokens are local to the running desktop app and are cleared when the Local API server stops.
## Static Documentation Build
Docusaurus is a static site generator. The repo builds `docs-site/` into `docs-site/build/`, and Electron serves those files from the local API server.
Development commands:
```bash
cd docs-site
npm install
npm run start
```
Build command:
```bash
npm run build:docs
```
Packaged desktop builds include the generated static output as an Electron extra resource.

View File

@@ -0,0 +1,87 @@
---
sidebar_position: 1
---
# Contributing
MetoYou is an npm-managed monorepo.
## Packages
| Path | Purpose |
| --- | --- |
| `toju-app/` | Angular renderer, chat client, voice UI, plugin runtime. |
| `electron/` | Electron main process, preload bridge, local database, local REST API, docs host. |
| `server/` | Node/TypeScript signaling server and server-directory HTTP API. |
| `website/` | Angular marketing site. |
| `docs-site/` | Docusaurus documentation site. |
| `e2e/` | Playwright browser and WebRTC tests. |
## Setup
Install root dependencies:
```bash
npm install
```
Install server dependencies when working on the signaling server:
```bash
cd server
npm install
```
## Development Commands
From the repository root:
```bash
npm run dev
```
Useful focused commands:
```bash
npm run build
npm run build:electron
npm run build:docs
npm run server:build
npm run lint
npm run test
npm run test:e2e -- tests/chat-dm-flow.spec.ts
```
Run the Docusaurus dev server:
```bash
cd docs-site
npm install
npm run start
```
Build static docs for Electron packaging:
```bash
npm run build:docs
```
## Repository Rules
- Keep changes inside the package that owns the behavior.
- Do not edit generated output in `dist/`, `dist-electron/`, `dist-server/`, `server/dist/`, `.angular/`, or `node_modules/`.
- Renderer-facing Electron capabilities must stay aligned across implementation, preload, and renderer bridge types.
- Signal-server plugin support stores metadata only. Plugin execution belongs to the client runtime.
- Update this documentation when user workflows, plugin APIs, REST routes, DOM structure, or development commands change.
## Documentation Checklist
When you change a related area, update these pages:
| Change | Docs to check |
| --- | --- |
| Voice UI or settings | User Guide: Voice Channels and Calls, Developer Guide: App Pages and DOM Structure. |
| Text channels, messages, DMs | User Guide: Text and Direct Messages, plugin message API pages. |
| Plugin manifest/API/runtime | Plugin Development pages and LLM Plugin Builder Guide. |
| Local REST API routes or schemas | Developer Guide: Local REST API and `electron/api/openapi.ts`. |
| Docusaurus hosting | Developer Guide: Docusaurus Site and Desktop and Local API. |

View File

@@ -0,0 +1,65 @@
---
sidebar_position: 2
---
# Docusaurus Site
The Docusaurus documentation lives in `docs-site/` and builds to static files in `docs-site/build/`.
## Structure
```text
docs-site/
docusaurus.config.ts
sidebars.ts
docs/
intro.md
user-guide/
developer/
plugin-development/
src/css/custom.css
```
## Development
Use the Docusaurus development server while writing docs:
```bash
cd docs-site
npm run start
```
Build the static site:
```bash
npm run build
```
From the repo root, use:
```bash
npm run build:docs
```
## Electron Hosting
Electron serves the built site through the local API server when Docusaurus docs are enabled.
| Route | Purpose |
| --- | --- |
| `/docusaurus` | Docusaurus entrypoint. |
| `/docusaurus/*` | Static Docusaurus assets and generated pages. |
The endpoint is off until the user opens documentation from the desktop app or enables it through local API settings. Electron serves static files only; it does not run `docusaurus start`.
## Sidebar Rules
Navigation is controlled by `docs-site/sidebars.ts`. Add every new page there unless it is intentionally hidden. Use categories for larger sections so non-technical users can find the user guide separately from developer material.
## Content Rules
- User docs should avoid implementation jargon.
- Developer docs should name exact files, commands, routes, capabilities, and data shapes.
- Plugin API examples should use literal sample input data.
- REST docs should stay aligned with `electron/api/openapi.ts` and `electron/api/router.ts`.
- DOM docs should stay aligned with Angular routes and component selectors.

View File

@@ -0,0 +1,145 @@
---
sidebar_position: 3
---
# App Pages and DOM Structure
This page maps the app routes and important DOM areas. It is useful for plugin authors, testers, and contributors who need stable mental models of where UI mounts.
## Angular Routes
| Route | Component | Purpose |
| --- | --- | --- |
| `/` | Redirect | Redirects to `/search`. |
| `/login` | `LoginComponent` | User login. |
| `/register` | `RegisterComponent` | User registration. |
| `/invite/:inviteId` | `InviteComponent` | Resolve and accept invite links. |
| `/search` | `ServerSearchComponent` | Search and join servers. |
| `/room/:roomId` | `ChatRoomComponent` | Main server page with text, voice, members, and plugin panels. |
| `/dm` | `DmWorkspaceComponent` | Direct-message workspace. |
| `/dm/:conversationId` | `DmWorkspaceComponent` | A selected direct-message conversation. |
| `/settings` | `SettingsComponent` | App, voice, server, plugin, desktop, theme, local API settings. |
| `/plugin-store` | `PluginStoreComponent` | Browse plugin sources and install/update plugins. |
| `/plugins/:pluginId/:pageId` | `PluginPageHostComponent` | Host for plugin app pages registered with `api.ui.registerAppPage()`. |
## Page Shell
The renderer is an Angular app. The common shell contains router outlet content plus persistent app surfaces such as the server rail, title bar integrations, settings modals, and floating voice controls.
High-level structure:
```html
<app-root>
<router-outlet></router-outlet>
<!-- global dialogs, overlays, floating voice controls, and desktop integrations -->
</app-root>
```
## Server Page DOM
The server page is the most important page for plugins.
```html
<app-chat-room>
<app-servers-rail></app-servers-rail>
<app-rooms-side-panel>
<section>Text Channels</section>
<section>Voice Channels</section>
<section data-testid="plugin-room-side-panel">
<app-plugin-render-host></app-plugin-render-host>
</section>
<section>Members</section>
</app-rooms-side-panel>
<main>
<app-voice-workspace></app-voice-workspace>
<app-chat-messages>
<app-message-list></app-message-list>
<app-typing-indicator></app-typing-indicator>
<app-message-composer></app-message-composer>
<app-klipy-gif-picker></app-klipy-gif-picker>
</app-chat-messages>
</main>
</app-chat-room>
```
## Text Channel Area
Text channel UI is owned by the chat domain.
```html
<app-chat-messages>
<app-message-list>
<app-message-item></app-message-item>
</app-message-list>
<app-message-overlays></app-message-overlays>
<app-typing-indicator></app-typing-indicator>
<app-message-composer></app-message-composer>
</app-chat-messages>
```
Plugin touchpoints:
- `api.ui.registerComposerAction()` adds composer actions.
- `api.ui.registerEmbedRenderer()` renders declared custom embed payloads.
- `api.ui.mountElement()` can mount into a selector such as `app-chat-messages` when the plugin has `ui.dom`.
## Voice Area
Voice UI is split between channel membership, controls, and media workspace.
```html
<app-rooms-side-panel>
<section>Voice Channels</section>
</app-rooms-side-panel>
<app-voice-controls></app-voice-controls>
<app-floating-voice-controls></app-floating-voice-controls>
<app-voice-workspace>
<app-voice-workspace-stream-tile></app-voice-workspace-stream-tile>
</app-voice-workspace>
```
Plugin touchpoints:
- `api.media.playAudioClip()` plays local audio.
- `api.media.addCustomAudioStream()` contributes audio to voice handling.
- `api.media.addCustomVideoStream()` contributes a video stream.
- `api.channels.addAudioChannel()` creates a voice channel entry when the plugin has channel management rights.
## Plugin Store and Manager DOM
```html
<app-plugin-store>
<!-- source management, search, plugin cards, install/update/uninstall actions -->
</app-plugin-store>
<app-plugin-manager>
<!-- installed plugins, capability grants, activate/reload/unload, logs, docs -->
</app-plugin-manager>
```
Plugin pages registered through `api.ui.registerAppPage()` render at `/plugins/:pluginId/:pageId`:
```html
<app-plugin-page-host>
<app-plugin-render-host></app-plugin-render-host>
</app-plugin-page-host>
```
## Plugin Render Host
`PluginRenderHostComponent` accepts plugin render functions that return either an `HTMLElement` or a string. Returning an `HTMLElement` is preferred for interactive UI. Returned strings are rendered as simple text content.
## Stable Selectors for Tests and Plugins
Prefer plugin APIs over DOM selectors. When direct DOM mounting is necessary, use stable app selectors and keep cleanup through the returned disposable.
Common targets:
| Selector | Area |
| --- | --- |
| `body` | Global overlays or modals. |
| `app-chat-messages` | Main text channel surface. |
| `app-rooms-side-panel` | Server side panel. |
| `[data-testid="plugin-room-side-panel"]` | Plugin side-panel area in the server sidebar. |
Avoid depending on Tailwind utility classes; they are layout details and may change.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,300 @@
---
sidebar_position: 4
---
# Local REST API
The MetoYou desktop app exposes an optional local HTTP API for scripts and tools. It is implemented in Electron and reads local desktop data.
## Enable the API
1. Open Settings.
2. Open Local API settings.
3. Enable the local server.
4. Choose a port. The default is `17878`.
5. Add trusted signaling server URLs for authentication.
6. Enable Scalar docs if you want `/docs`.
7. Enable Docusaurus docs if you want `/docusaurus`.
By default the server binds to `127.0.0.1`. Only enable LAN exposure when you understand the risk.
## Authentication
Protected routes require a bearer token. Get one by posting username, password, and an allowed signaling server URL.
```bash
curl -s http://127.0.0.1:17878/api/auth/login \
-H 'Content-Type: application/json' \
-d '{
"username": "alice",
"password": "correct horse battery staple",
"serverUrl": "https://tojusignal.example.com"
}'
```
Example response:
```json
{
"token": "local_4cddf95c5b8c4b6f9e0c",
"expiresAt": 1777477200000,
"user": {
"id": "user-alice-01",
"username": "alice",
"displayName": "Alice"
}
}
```
Use the token:
```bash
curl -s http://127.0.0.1:17878/api/profile \
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
```
Logout revokes the current token:
```bash
curl -i -X POST http://127.0.0.1:17878/api/auth/logout \
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
```
## OpenAPI and Scalar
| Route | Auth | Purpose |
| --- | --- | --- |
| `GET /api/openapi.json` | No | OpenAPI 3.1 document. |
| `GET /docs` | No | Scalar API reference when enabled. |
## Public Routes
### GET /api/health
Checks whether the local API server is running.
```bash
curl -s http://127.0.0.1:17878/api/health
```
Example response:
```json
{
"status": "ok",
"version": "1.0.0",
"timestamp": 1777473600000,
"exposeOnLan": false
}
```
### GET /api/openapi.json
Returns the machine-readable API document.
```bash
curl -s http://127.0.0.1:17878/api/openapi.json
```
### POST /api/auth/login
Issues a local bearer token after credentials are validated by an allowed signaling server.
Request body:
```json
{
"username": "alice",
"password": "correct horse battery staple",
"serverUrl": "https://tojusignal.example.com"
}
```
Common errors:
| Status | Error code | Meaning |
| --- | --- | --- |
| 400 | `INVALID_REQUEST` | Missing username, password, or server URL. |
| 403 | `NO_ALLOWED_SERVERS` | No allowed signaling servers are configured. |
| 403 | `SERVER_NOT_ALLOWED` | The server URL is not in the allowed list. |
| 401 | `INVALID_CREDENTIALS` | Signaling server rejected the login. |
| 502 | `UPSTREAM_UNREACHABLE` | The signaling server could not be reached. |
## Protected Routes
All routes below require:
```http
Authorization: Bearer local_4cddf95c5b8c4b6f9e0c
```
### GET /api/profile
Reads the current local user profile.
```bash
curl -s http://127.0.0.1:17878/api/profile \
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
```
### GET /api/rooms
Lists rooms known to this device.
```bash
curl -s http://127.0.0.1:17878/api/rooms \
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
```
### GET `/api/rooms/{roomId}`
Reads one room by id.
```bash
curl -s http://127.0.0.1:17878/api/rooms/room-7ebdde75 \
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
```
### GET `/api/rooms/{roomId}/users`
Lists users known for a room.
```bash
curl -s http://127.0.0.1:17878/api/rooms/room-7ebdde75/users \
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
```
### GET `/api/rooms/{roomId}/messages`
Lists local messages for a room. `limit` defaults to `100` and is clamped from `1` to `500`. `offset` defaults to `0`.
```bash
curl -s 'http://127.0.0.1:17878/api/rooms/room-7ebdde75/messages?limit=50&offset=0' \
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
```
### GET `/api/rooms/{roomId}/messages/since`
Lists local messages after a required timestamp.
```bash
curl -s 'http://127.0.0.1:17878/api/rooms/room-7ebdde75/messages/since?sinceTimestamp=1777470000000' \
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
```
### GET `/api/rooms/{roomId}/bans`
Lists active bans for a room.
```bash
curl -s http://127.0.0.1:17878/api/rooms/room-7ebdde75/bans \
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
```
### GET `/api/rooms/{roomId}/bans/{userId}`
Checks whether a user is banned in a room.
```bash
curl -s http://127.0.0.1:17878/api/rooms/room-7ebdde75/bans/user-muse-01 \
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
```
Example response:
```json
{ "isBanned": false }
```
### GET `/api/messages/{messageId}`
Reads one local message by id.
```bash
curl -s http://127.0.0.1:17878/api/messages/msg-20260429-001 \
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
```
### GET `/api/messages/{messageId}/reactions`
Lists reactions for a message.
```bash
curl -s http://127.0.0.1:17878/api/messages/msg-20260429-001/reactions \
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
```
### GET `/api/messages/{messageId}/attachments`
Lists attachments for a message.
```bash
curl -s http://127.0.0.1:17878/api/messages/msg-20260429-001/attachments \
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
```
### GET `/api/users/{userId}`
Reads one user by id.
```bash
curl -s http://127.0.0.1:17878/api/users/user-muse-01 \
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
```
### GET /api/attachments
Lists all attachments stored on this device.
```bash
curl -s http://127.0.0.1:17878/api/attachments \
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
```
### GET /api/plugin-data
Reads a plugin data value from the local desktop database. `scope` must be `local` or `server`. Provide `serverId` when reading server-scoped data.
```bash
curl -s 'http://127.0.0.1:17878/api/plugin-data?pluginId=example.soundboard&key=favorites&scope=server&serverId=room-7ebdde75' \
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
```
Example response:
```json
{
"value": [
{ "label": "Chime", "url": "https://cdn.example.com/chime.wav" }
]
}
```
### GET `/api/meta/{key}`
Reads a desktop metadata value by key.
```bash
curl -s http://127.0.0.1:17878/api/meta/metoyou_currentUserId \
-H 'Authorization: Bearer local_4cddf95c5b8c4b6f9e0c'
```
Example response:
```json
{
"key": "metoyou_currentUserId",
"value": "user-alice-01"
}
```
## Data Model Notes
Rooms, users, messages, reactions, attachments, and bans are returned from local desktop persistence. Many schemas allow additional properties because the local database can carry richer app state than the REST docs need to guarantee.
## Security Notes
- Keep the API bound to `127.0.0.1` unless LAN access is required.
- Only add signaling servers you trust to the allowed list.
- Bearer tokens are local to the running desktop app.
- Stop the local API server to clear issued tokens.

48
docs-site/docs/intro.md Normal file
View File

@@ -0,0 +1,48 @@
---
slug: /
sidebar_position: 1
---
# MetoYou Documentation
MetoYou is a desktop-first chat app with text channels, voice channels, direct messages, plugins, local desktop storage, a local REST API, and a Docusaurus documentation site bundled into the app.
This site is split into three paths:
- **User Guide** explains the app in non-technical terms: servers, text channels, voice channels, screen sharing, direct messages, plugins, and desktop settings.
- **Developer Guide** explains how to run the repo, how the app is structured, how Docusaurus is served, the app DOM/page structure, and the local REST API.
- **Plugin Development** explains how to build plugins, declare capabilities, distribute bundles, and call every exposed plugin API with concrete examples.
The Electron app can host this documentation locally. The docs endpoint is not a separate web server process: it is served from the same opt-in local HTTP server used for the Local API, and it only serves static files generated by Docusaurus.
## What Is Included
| Area | What it covers |
| --- | --- |
| Product client | Login, server discovery, channels, messages, voice, direct messages, themes, and plugin UI. |
| Desktop shell | Window controls, notifications, tray behavior, app data import/export, updates, local plugins, and hosted documentation. |
| Local HTTP API | A loopback-first API for local scripts and tools, with OpenAPI and Scalar reference docs. |
| Plugin runtime | Browser-safe client plugins with explicit capabilities, lifecycle hooks, UI contributions, data storage, message bus, and server plugin requirements. |
## Runtime Boundaries
MetoYou keeps responsibilities split by package:
- `toju-app/` is the Angular product client and plugin runtime.
- `electron/` is the main process, preload bridge, IPC, local persistence, and local HTTP host.
- `server/` is the signaling and server-directory service.
- `e2e/` contains Playwright coverage for browser and WebRTC workflows.
- `docs-site/` is this Docusaurus site.
The desktop documentation endpoint serves the static `docs-site/build` output. It does not run the Docusaurus development server inside Electron.
## Fast Links
- Start using the app: [First Steps](./user-guide/first-steps.md)
- Join voice: [Voice Channels and Calls](./user-guide/voice-channels.md)
- Install plugins: [Plugins for Users](./user-guide/plugins.md)
- Run the repo: [Contributing](./developer/contributing.md)
- Understand pages and DOM: [App Pages and DOM Structure](./developer/dom-structure.md)
- Use the REST API: [Local REST API](./developer/rest-api.md)
- Build a plugin: [Create a Plugin](./plugin-development/create-a-plugin.md)
- Give an LLM plugin context: [LLM Plugin Builder Guide](./developer/llm-plugin-builder-guide.md)

View File

@@ -0,0 +1,329 @@
---
sidebar_position: 4
---
# Plugin API Reference
`TojuClientPluginApi` is the object passed to a plugin activation context. The runtime freezes the API object before passing it to plugin code.
This page is the compact map. Use the focused API pages for concrete copy-paste examples with literal input data.
## Focused API Pages
- [Context and Logging](./api/context-and-logging.md)
- [Profile API](./api/profile.md)
- [Users and Roles API](./api/users-and-roles.md)
- [Server API](./api/server.md)
- [Channels API](./api/channels.md)
- [Messages and Typing API](./api/messages-and-typing.md)
- [Events API](./api/events.md)
- [Message Bus API](./api/message-bus.md)
- [P2P and Media API](./api/p2p-and-media.md)
- [Storage API](./api/storage.md)
- [UI API](./api/ui.md)
## Activation Types
```ts
interface TojuPluginDisposable {
dispose: () => void;
}
interface TojuPluginActivationContext {
api: TojuClientPluginApi;
manifest: TojuPluginManifest;
pluginId: string;
subscriptions: TojuPluginDisposable[];
}
interface TojuClientPluginModule {
activate?: (context: TojuPluginActivationContext) => Promise<void> | void;
deactivate?: (context: TojuPluginActivationContext) => Promise<void> | void;
onPluginDataChanged?: (context: TojuPluginActivationContext, event: unknown) => Promise<void> | void;
onServerRequirementsChanged?: (context: TojuPluginActivationContext, snapshot: PluginRequirementsSnapshot) => Promise<void> | void;
ready?: (context: TojuPluginActivationContext) => Promise<void> | void;
}
```
## Profiles
```ts
interface PluginApiProfileUpdate {
description?: string;
displayName: string;
}
interface PluginApiAvatarUpdate {
avatarHash: string;
avatarMime: string;
avatarUrl: string;
}
```
| Method | Capability | Description |
| --- | --- | --- |
| `profile.getCurrent()` | `profile.read` | Returns the current `User` or `null`. |
| `profile.update(profile)` | `profile.write` | Updates display name and optional description. |
| `profile.updateAvatar(avatar)` | `profile.write` | Updates avatar URL, MIME type, and hash metadata. |
## Users and Roles
| Method | Capability | Description |
| --- | --- | --- |
| `users.getCurrent()` | `users.read` | Returns current `User` or `null`. |
| `users.list()` | `users.read` | Returns known users. |
| `users.readMembers()` | `users.read` | Returns active room members. |
| `users.setRole(userId, role)` | `roles.manage` | Updates a user's role. |
| `users.kick(userId)` | `users.manage` | Kicks a user. |
| `users.ban(userId, reason?)` | `users.manage` | Bans a user with optional reason. |
| `roles.list()` | `roles.read` | Returns room roles. |
| `roles.setAssignments(assignments)` | `roles.manage` | Replaces role assignments. |
## Server
```ts
interface PluginApiServerSettingsUpdate {
description?: string;
isPrivate?: boolean;
maxUsers?: number;
name?: string;
password?: string;
topic?: string;
}
interface PluginApiPluginUserRequest {
avatarUrl?: string;
displayName: string;
id?: string;
}
```
| Method | Capability | Description |
| --- | --- | --- |
| `server.getCurrent()` | `server.read` | Returns the current `Room` or `null`. |
| `server.registerPluginUser(request)` | `users.manage` | Adds a plugin-owned user and returns its id. |
| `server.updatePermissions(permissions)` | `server.manage` | Updates partial room permissions. |
| `server.updateSettings(settings)` | `server.manage` | Updates room settings. |
## Channels
```ts
interface PluginApiChannelRequest {
id?: string;
name: string;
position?: number;
}
```
| Method | Capability | Description |
| --- | --- | --- |
| `channels.list()` | `channels.read` | Returns current room channels. |
| `channels.select(channelId)` | `channels.read` | Selects a channel. |
| `channels.addAudioChannel(request)` | `channels.manage` | Adds a voice channel. |
| `channels.addVideoChannel(request)` | `channels.manage` | Registers a video channel section. |
| `channels.rename(channelId, name)` | `channels.manage` | Renames a channel. |
| `channels.remove(channelId)` | `channels.manage` | Removes a channel. |
## Messages
```ts
interface PluginApiMessageAsPluginUserRequest {
channelId?: string;
content: string;
pluginUserId: string;
}
```
| Method | Capability | Description |
| --- | --- | --- |
| `messages.readCurrent()` | `messages.read` | Returns current visible messages. |
| `messages.send(content, channelId?)` | `messages.send` | Sends a message and returns the created `Message`. |
| `messages.sendAsPluginUser(request)` | `messages.send` | Emits a message from a registered plugin user. |
| `messages.setTyping(isTyping, channelId?)` | `messages.send` | Broadcasts current typing state for a channel. |
| `messages.subscribeTyping(handler)` | `messages.read` | Subscribes to peer typing state. |
| `messages.edit(messageId, content)` | `messages.editOwn` | Edits a plugin message. |
| `messages.delete(messageId)` | `messages.deleteOwn` | Deletes a plugin message. |
| `messages.moderateDelete(messageId)` | `messages.moderate` | Performs a moderation delete. |
| `messages.sync(messages)` | `messages.sync` | Syncs an array of messages into state. |
## Events
```ts
interface PluginApiEventSubscription {
eventName: string;
handler: (event: PluginEventEnvelope) => void;
}
interface PluginEventEnvelope<TPayload = unknown> {
emittedAt?: number;
eventId?: string;
eventName: string;
payload: TPayload;
pluginId: string;
serverId: string;
sourcePluginUserId?: string;
sourceUserId?: string;
type: 'plugin_event';
}
```
| Method | Capability | Description |
| --- | --- | --- |
| `events.publishServer(eventName, payload)` | `events.server.publish` | Sends a declared plugin event through the signaling server. |
| `events.subscribeServer(subscription)` | `events.server.subscribe` | Subscribes to a declared server plugin event. |
| `events.publishP2p(eventName, payload)` | `events.p2p.publish` | Sends a declared plugin event over peer paths. |
| `events.subscribeP2p(subscription)` | `events.p2p.subscribe` | Registers a P2P event subscription. |
## Message Bus
```ts
interface PluginApiMessageBusEnvelope {
channelId?: string;
eventId: string;
messages?: Message[];
payload?: unknown;
pluginId: string;
roomId: string;
sentAt: number;
sourcePeerId?: string;
sourceUserId?: string;
topic: string;
}
interface PluginApiMessageBusLatestRequest {
channelId?: string;
includeDeleted?: boolean;
limit?: number;
sinceTimestamp?: number;
targetPeerId?: string;
topic?: string;
}
interface PluginApiMessageBusPublishRequest extends PluginApiMessageBusLatestRequest {
includeLatestMessages?: boolean;
includeSelf?: boolean;
payload?: unknown;
topic: string;
}
interface PluginApiMessageBusSubscription {
channelId?: string;
handler: (event: PluginApiMessageBusEnvelope) => void;
latestMessageLimit?: number;
replayLatest?: boolean;
topic?: string;
}
```
| Method | Capability | Description |
| --- | --- | --- |
| `messageBus.publish(request)` | `events.p2p.publish`, optionally `messages.read` | Publishes a plugin-bus event, optionally including latest messages. |
| `messageBus.sendLatestMessages(request?)` | `events.p2p.publish` and `messages.read` | Sends a latest-message snapshot. |
| `messageBus.subscribe(subscription)` | `events.p2p.subscribe`, optionally `messages.read` | Subscribes to plugin-bus events, optionally replaying latest messages. |
## P2P and Media
```ts
interface PluginApiAudioClipRequest {
volume?: number;
url: string;
}
interface PluginApiCustomStreamRequest {
label?: string;
stream: MediaStream;
}
```
| Method | Capability | Description |
| --- | --- | --- |
| `p2p.connectedPeers()` | `p2p.data` | Returns connected peer ids. |
| `p2p.broadcastData(eventName, payload)` | `p2p.data` | Broadcasts plugin data. |
| `p2p.sendData(peerId, eventName, payload)` | `p2p.data` | Sends plugin data targeted to a peer. |
| `media.playAudioClip(request)` | `media.playAudio` | Plays an audio URL at optional volume. |
| `media.addCustomAudioStream(request)` | `media.addAudioStream` | Contributes an audio `MediaStream`. |
| `media.addCustomVideoStream(request)` | `media.addVideoStream` | Registers a video `MediaStream` contribution. |
| `media.setInputVolume(volume)` | `audio.volume` | Sets local input volume. |
| `media.setOutputVolume(volume)` | `audio.volume` | Sets local output volume. |
## Storage
| Method | Capability | Description |
| --- | --- | --- |
| `clientData.read(key)` | `storage.local` | Reads async plugin-local data. |
| `clientData.write(key, value)` | `storage.local` | Writes async plugin-local data. |
| `clientData.remove(key)` | `storage.local` | Removes async plugin-local data. |
| `serverData.read(key)` | `storage.serverData.read` | Reads local per-user/per-server data. |
| `serverData.write(key, value)` | `storage.serverData.write` | Writes local per-user/per-server data. |
| `serverData.remove(key)` | `storage.serverData.write` | Removes local per-user/per-server data. |
| `storage.get(key)` | `storage.local` | Legacy synchronous local read. |
| `storage.set(key, value)` | `storage.local` | Legacy synchronous local write. |
| `storage.remove(key)` | `storage.local` | Legacy synchronous local remove. |
## UI Contributions
```ts
interface PluginApiActionContribution {
icon?: string;
label: string;
run: () => Promise<void> | void;
}
interface PluginApiPageContribution {
label: string;
path: string;
render: () => HTMLElement | string;
}
interface PluginApiPanelContribution {
label: string;
order?: number;
render: () => HTMLElement | string;
}
interface PluginApiSettingsPageContribution {
label: string;
order?: number;
render: () => HTMLElement | string;
settingsKey?: string;
}
interface PluginApiChannelSectionContribution {
label: string;
order?: number;
type?: 'audio' | 'custom' | 'video';
}
interface PluginApiEmbedRendererContribution {
embedType: string;
render: (payload: unknown) => HTMLElement | string;
}
interface PluginApiDomMountRequest {
element: HTMLElement;
position?: InsertPosition;
target: Element | string;
}
```
| Method | Capability | Description |
| --- | --- | --- |
| `ui.registerAppPage(id, contribution)` | `ui.pages` | Adds a plugin app page. |
| `ui.registerSettingsPage(id, contribution)` | `ui.settings` | Adds a plugin settings page. |
| `ui.registerSidePanel(id, contribution)` | `ui.sidePanel` | Adds a side panel. |
| `ui.registerChannelSection(id, contribution)` | `ui.channelsSection` | Adds a channel section. |
| `ui.registerComposerAction(id, contribution)` | `ui.pages` | Adds a composer action. |
| `ui.registerProfileAction(id, contribution)` | `ui.pages` | Adds a profile action. |
| `ui.registerToolbarAction(id, contribution)` | `ui.pages` | Adds a toolbar action. |
| `ui.registerEmbedRenderer(id, contribution)` | `ui.embeds` | Adds an embed renderer. |
| `ui.mountElement(id, request)` | `ui.dom` | Mounts plugin-owned DOM into a target element or selector. |
## Context and Logger
| Method | Capability | Description |
| --- | --- | --- |
| `context.getCurrent()` | None | Reads current user, server, active text channel, and active voice channel. |
| `logger.debug(message, data?)` | None | Writes a debug plugin log entry. |
| `logger.info(message, data?)` | None | Writes an info plugin log entry. |
| `logger.warn(message, data?)` | None | Writes a warning plugin log entry. |
| `logger.error(message, data?)` | None | Writes an error plugin log entry. |

View File

@@ -0,0 +1,85 @@
---
sidebar_position: 5
---
# Channels API
The channels API reads, selects, creates, renames, and removes server channels.
## Required Capabilities
| Method | Capability |
| --- | --- |
| `channels.list()` | `channels.read` |
| `channels.select(channelId)` | `channels.read` |
| `channels.addAudioChannel(request)` | `channels.manage` |
| `channels.addVideoChannel(request)` | `channels.manage` |
| `channels.rename(channelId, name)` | `channels.manage` |
| `channels.remove(channelId)` | `channels.manage` |
## List Channels
```js
export function activate(context) {
const channels = context.api.channels.list();
context.api.logger.info('Channels', channels.map((channel) => ({
id: channel.id,
name: channel.name,
type: channel.type
})));
}
```
Example channel list:
```json
[
{ "id": "general", "name": "general", "type": "text", "position": 0 },
{ "id": "support", "name": "support", "type": "text", "position": 1 },
{ "id": "lobby", "name": "Lobby", "type": "audio", "position": 10 }
]
```
## Select a Channel
```js
export function activate(context) {
context.api.channels.select('support');
}
```
## Add a Voice Channel
```js
export function activate(context) {
context.api.channels.addAudioChannel({
id: 'raid-voice',
name: 'Raid Voice',
position: 20
});
}
```
## Add a Video Channel Section
```js
export function activate(context) {
context.api.channels.addVideoChannel({
id: 'watch-party-video',
name: 'Watch Party',
position: 30
});
}
```
## Rename and Remove
```js
export function activate(context) {
context.api.channels.rename('raid-voice', 'Raid Voice - Tonight');
context.api.channels.remove('old-event-room');
}
```
Channel creation, rename, and removal should be user-confirmed because they change the shared server structure.

View File

@@ -0,0 +1,73 @@
---
sidebar_position: 1
---
# Context and Logging
Context and logging are available to every plugin. They do not require privileged capabilities.
## context.getCurrent()
Reads the current interaction context.
```js
export function activate(context) {
const current = context.api.context.getCurrent();
context.api.logger.info('Current context', {
serverName: current.server?.name ?? 'No server open',
textChannel: current.textChannel?.name ?? 'No text channel selected',
voiceChannel: current.voiceChannel?.name ?? 'Not connected to voice',
user: current.user?.displayName ?? 'No user'
});
}
```
Example context shape:
```json
{
"source": "manual",
"server": { "id": "room-7ebdde75", "name": "Friday Game Night" },
"textChannel": { "id": "general", "name": "general", "type": "text" },
"voiceChannel": { "id": "lobby", "name": "Lobby", "type": "audio" },
"user": { "id": "user-alice-01", "displayName": "Alice" }
}
```
## Action Context
Composer, toolbar, and profile actions receive context directly.
```js
export function activate(context) {
context.subscriptions.push(context.api.ui.registerToolbarAction('where-am-i', {
label: 'Where am I?',
run: (actionContext) => {
context.api.logger.info('Toolbar action context', {
source: actionContext.source,
serverId: actionContext.server?.id,
textChannelId: actionContext.textChannel?.id,
voiceChannelId: actionContext.voiceChannel?.id
});
}
}));
}
```
Capability required: `ui.pages` for the toolbar action. The context object itself needs no extra capability.
## Logger Methods
```js
export function activate(context) {
const { logger } = context.api;
logger.debug('Preparing plugin', { pluginId: context.pluginId });
logger.info('Plugin activated', { version: context.manifest.version });
logger.warn('Optional service unavailable', { service: 'weather.example.com' });
logger.error('Failed to parse saved preference', { key: 'soundboard:favorites' });
}
```
Logs are visible in the Plugin Manager. Avoid logging passwords, bearer tokens, or private message contents.

View File

@@ -0,0 +1,100 @@
---
sidebar_position: 7
---
# Events API
Plugin events allow plugins to publish and subscribe to declared server or P2P events.
## Required Capabilities
| Method | Capability |
| --- | --- |
| `events.publishServer(eventName, payload)` | `events.server.publish` |
| `events.subscribeServer(subscription)` | `events.server.subscribe` |
| `events.publishP2p(eventName, payload)` | `events.p2p.publish` |
| `events.subscribeP2p(subscription)` | `events.p2p.subscribe` |
## Declare Events in the Manifest
```json
{
"events": [
{
"eventName": "poll:vote",
"direction": "p2pHint",
"scope": "channel",
"maxPayloadBytes": 2048
},
{
"eventName": "moderation:flag",
"direction": "serverRelay",
"scope": "server",
"maxPayloadBytes": 4096
}
]
}
```
## Publish and Subscribe to P2P Events
```js
export function activate(context) {
context.subscriptions.push(context.api.events.subscribeP2p({
eventName: 'poll:vote',
handler: (event) => {
context.api.logger.info('Vote received', {
optionId: event.payload?.optionId,
voterName: event.payload?.voterName,
eventId: event.eventId
});
}
}));
context.api.events.publishP2p('poll:vote', {
pollId: 'raid-night-2026-04-29',
optionId: 'dungeon',
voterName: 'Alice'
});
}
```
## Publish and Subscribe to Server Events
```js
export function activate(context) {
context.subscriptions.push(context.api.events.subscribeServer({
eventName: 'moderation:flag',
handler: (event) => {
context.api.logger.warn('Moderation flag received', {
messageId: event.payload?.messageId,
reason: event.payload?.reason
});
}
}));
context.api.events.publishServer('moderation:flag', {
messageId: 'msg-20260429-flagged',
reason: 'Possible spam link',
reportedBy: 'user-alice-01'
});
}
```
Example event envelope:
```json
{
"type": "plugin_event",
"eventName": "poll:vote",
"pluginId": "example.polls",
"serverId": "room-7ebdde75",
"eventId": "event-1777473600000-1",
"emittedAt": 1777473600000,
"payload": {
"pollId": "raid-night-2026-04-29",
"optionId": "dungeon",
"voterName": "Alice"
}
}
```

View File

@@ -0,0 +1,95 @@
---
sidebar_position: 8
---
# Message Bus API
The plugin message bus sends plugin-only P2P events. It can also include bounded latest-message snapshots for plugins that coordinate around recent chat state.
## Required Capabilities
| Method | Capability |
| --- | --- |
| `messageBus.publish(request)` | `events.p2p.publish`, plus `messages.read` if `includeLatestMessages` is true |
| `messageBus.sendLatestMessages(request?)` | `events.p2p.publish` and `messages.read` |
| `messageBus.subscribe(subscription)` | `events.p2p.subscribe`, plus `messages.read` if replaying latest messages |
## Subscribe
```js
export function activate(context) {
context.subscriptions.push(context.api.messageBus.subscribe({
topic: 'poll:votes',
channelId: 'general',
replayLatest: true,
latestMessageLimit: 10,
handler: (event) => {
context.api.logger.info('Poll bus event', {
topic: event.topic,
choice: event.payload?.choice,
messageCount: event.messages?.length ?? 0
});
}
}));
}
```
## Publish
```js
export function activate(context) {
const envelope = context.api.messageBus.publish({
topic: 'poll:votes',
channelId: 'general',
payload: {
pollId: 'raid-night-2026-04-29',
choice: 'healer',
voter: 'Alice'
},
includeLatestMessages: true,
includeSelf: true,
latestMessageLimit: 10,
sinceTimestamp: 1777470000000
});
context.api.logger.info('Published poll event', { eventId: envelope.eventId });
}
```
Example envelope:
```json
{
"eventId": "plugin-bus-1777473600000-1",
"pluginId": "example.polls",
"roomId": "room-7ebdde75",
"channelId": "general",
"topic": "poll:votes",
"sentAt": 1777473600000,
"payload": {
"pollId": "raid-night-2026-04-29",
"choice": "healer",
"voter": "Alice"
},
"messages": [
{ "id": "msg-1", "content": "Raid tonight?", "channelId": "general" }
]
}
```
## Send Latest Messages
```js
export function activate(context) {
context.api.messageBus.sendLatestMessages({
topic: 'chat:snapshot',
channelId: 'support',
limit: 25,
includeDeleted: false,
sinceTimestamp: 1777460000000,
targetPeerId: 'peer-muse-laptop'
});
}
```
Use the message bus for plugin coordination. Do not use it for normal user chat messages; use `messages.send()` for that.

View File

@@ -0,0 +1,144 @@
---
sidebar_position: 6
---
# Messages and Typing API
The messages API reads current messages, sends messages, edits or deletes plugin-owned messages, moderates messages, syncs messages, and exposes typing state.
## Required Capabilities
| Method | Capability |
| --- | --- |
| `messages.readCurrent()` | `messages.read` |
| `messages.send(content, channelId?)` | `messages.send` |
| `messages.sendAsPluginUser(request)` | `messages.send` |
| `messages.setTyping(isTyping, channelId?)` | `messages.send` |
| `messages.subscribeTyping(handler)` | `messages.read` |
| `messages.edit(messageId, content)` | `messages.editOwn` |
| `messages.delete(messageId)` | `messages.deleteOwn` |
| `messages.moderateDelete(messageId)` | `messages.moderate` |
| `messages.sync(messages)` | `messages.sync` |
## Read Current Messages
```js
export function activate(context) {
const messages = context.api.messages.readCurrent();
context.api.logger.info('Current messages', messages.slice(-3).map((message) => ({
id: message.id,
channelId: message.channelId,
senderName: message.senderName,
content: message.content
})));
}
```
## Send a Message
```js
export function activate(context) {
const created = context.api.messages.send(
'Reminder: raid starts at 20:00. Bring repairs and snacks.',
'general'
);
context.api.logger.info('Sent reminder', { messageId: created.id });
}
```
## Send as a Plugin User
```js
export function activate(context) {
const botUserId = context.api.server.registerPluginUser({
id: 'poll-bot',
displayName: 'Poll Bot'
});
context.api.messages.sendAsPluginUser({
pluginUserId: botUserId,
channelId: 'general',
content: 'Poll is open: react with 1 for dungeon, 2 for arena, 3 for crafting.'
});
}
```
Capabilities required: `users.manage` and `messages.send`.
## Edit and Delete Plugin-Owned Messages
```js
export function activate(context) {
const message = context.api.messages.send('Draft event reminder', 'announcements');
context.api.messages.edit(message.id, 'Event reminder: voice meetup starts in 15 minutes.');
context.api.messages.delete(message.id);
}
```
## Moderation Delete
```js
export function activate(context) {
context.api.messages.moderateDelete('msg-spam-20260429-001');
}
```
Use moderation from explicit moderator actions, not automatic activation.
## Typing State
```js
export function activate(context) {
context.api.messages.setTyping(true, 'general');
setTimeout(() => {
context.api.messages.setTyping(false, 'general');
}, 1500);
context.subscriptions.push(context.api.messages.subscribeTyping((event) => {
context.api.logger.info('Typing event', {
displayName: event.displayName,
isTyping: event.isTyping,
channelId: event.channelId,
serverId: event.serverId,
voiceChannel: event.voiceChannel?.name ?? null
});
}));
}
```
Example typing event:
```json
{
"serverId": "room-7ebdde75",
"channelId": "general",
"userId": "user-muse-01",
"displayName": "Muse",
"isTyping": true
}
```
## Sync Messages
```js
export function activate(context) {
context.api.messages.sync([
{
id: 'external-standup-001',
roomId: 'room-7ebdde75',
channelId: 'standup',
senderId: 'standup-importer',
senderName: 'Standup Importer',
content: 'Imported note: Alice is working on plugin docs.',
timestamp: 1777473600000,
isDeleted: false
}
]);
}
```
Sync should preserve message ids and timestamps from the source system when possible.

View File

@@ -0,0 +1,128 @@
---
sidebar_position: 9
---
# P2P and Media API
P2P APIs send plugin data to connected peers. Media APIs play audio and contribute custom streams.
## Required Capabilities
| Method | Capability |
| --- | --- |
| `p2p.connectedPeers()` | `p2p.data` |
| `p2p.broadcastData(eventName, payload)` | `p2p.data` |
| `p2p.sendData(peerId, eventName, payload)` | `p2p.data` |
| `media.playAudioClip(request)` | `media.playAudio` |
| `media.addCustomAudioStream(request)` | `media.addAudioStream` |
| `media.addCustomVideoStream(request)` | `media.addVideoStream` |
| `media.setInputVolume(volume)` | `audio.volume` |
| `media.setOutputVolume(volume)` | `audio.volume` |
## Connected Peers
```js
export function activate(context) {
const peerIds = context.api.p2p.connectedPeers();
context.api.logger.info('Connected peers', { peerIds });
}
```
## Broadcast Data
```js
export function activate(context) {
context.api.p2p.broadcastData('soundboard:played', {
soundId: 'airhorn-short',
label: 'Airhorn',
playedBy: 'Alice',
playedAt: 1777473600000
});
}
```
## Send Data to One Peer
```js
export function activate(context) {
context.api.p2p.sendData('peer-muse-laptop', 'private-tool:ping', {
requestId: 'ping-20260429-001',
message: 'Are you receiving plugin data?'
});
}
```
## Play an Audio Clip
```js
export async function activate(context) {
await context.api.media.playAudioClip({
url: 'https://cdn.example.com/metoyou/sounds/chime.wav',
volume: 0.65
});
}
```
## Add a Custom Audio Stream
```js
export async function activate(context) {
const audioContext = new AudioContext();
const oscillator = audioContext.createOscillator();
const gain = audioContext.createGain();
const destination = audioContext.createMediaStreamDestination();
oscillator.type = 'sine';
oscillator.frequency.value = 440;
gain.gain.value = 0.03;
oscillator.connect(gain);
gain.connect(destination);
oscillator.start();
await context.api.media.addCustomAudioStream({
label: 'Tuning tone',
stream: destination.stream
});
setTimeout(async () => {
oscillator.stop();
await audioContext.close();
}, 1000);
}
```
## Add a Custom Video Stream
```js
export async function activate(context) {
const canvas = document.createElement('canvas');
canvas.width = 1280;
canvas.height = 720;
const ctx = canvas.getContext('2d');
ctx.fillStyle = '#111827';
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = '#ffffff';
ctx.font = '48px sans-serif';
ctx.fillText('Plugin camera scene', 80, 120);
const stream = canvas.captureStream(15);
await context.api.media.addCustomVideoStream({
label: 'Plugin camera scene',
stream
});
}
```
## Set Volumes
```js
export function activate(context) {
context.api.media.setInputVolume(0.85);
context.api.media.setOutputVolume(0.75);
}
```
Use media APIs with visible controls and clear user consent. Unexpected audio or video is a poor user experience.

View File

@@ -0,0 +1,66 @@
---
sidebar_position: 2
---
# Profile API
The profile API reads and updates the current user's local profile details.
## Required Capabilities
| Method | Capability |
| --- | --- |
| `profile.getCurrent()` | `profile.read` |
| `profile.update(profile)` | `profile.write` |
| `profile.updateAvatar(avatar)` | `profile.write` |
## Read Current Profile
```js
export function activate(context) {
const user = context.api.profile.getCurrent();
context.api.logger.info('Current profile', {
id: user?.id,
displayName: user?.displayName,
username: user?.username
});
}
```
Example result:
```json
{
"id": "user-alice-01",
"username": "alice",
"displayName": "Alice",
"description": "Raids on Fridays",
"avatarUrl": "/avatars/alice.webp"
}
```
## Update Display Profile
```js
export function activate(context) {
context.api.profile.update({
displayName: 'Alice - Support Lead',
description: 'Available for onboarding and support questions.'
});
}
```
## Update Avatar
```js
export function activate(context) {
context.api.profile.updateAvatar({
avatarUrl: 'https://cdn.example.com/metoyou/avatars/alice-support.png',
avatarMime: 'image/png',
avatarHash: 'sha256:9df5d5e4b0d8f41f3a3cf5d1f5a2c1f4'
});
}
```
Use `profile.write` carefully. A plugin that changes a user's identity should explain why in its readme and UI.

View File

@@ -0,0 +1,81 @@
---
sidebar_position: 4
---
# Server API
The server API reads the active server, registers plugin-owned users, and updates server settings or permissions.
## Required Capabilities
| Method | Capability |
| --- | --- |
| `server.getCurrent()` | `server.read` |
| `server.registerPluginUser(request)` | `users.manage` |
| `server.updatePermissions(permissions)` | `server.manage` |
| `server.updateSettings(settings)` | `server.manage` |
## Read Current Server
```js
export function activate(context) {
const server = context.api.server.getCurrent();
context.api.logger.info('Current server', {
id: server?.id,
name: server?.name,
topic: server?.topic,
isPrivate: server?.isPrivate
});
}
```
## Register a Plugin User
Plugin users are useful for bot-style messages.
```js
export function activate(context) {
const botUserId = context.api.server.registerPluginUser({
id: 'standup-helper-bot',
displayName: 'Standup Helper',
avatarUrl: 'https://cdn.example.com/metoyou/plugins/standup-helper.png'
});
context.api.messages.sendAsPluginUser({
pluginUserId: botUserId,
channelId: 'general',
content: 'Standup reminder: share yesterday, today, and blockers.'
});
}
```
Capabilities required: `users.manage` and `messages.send`.
## Update Server Settings
```js
export function activate(context) {
context.api.server.updateSettings({
name: 'Friday Game Night',
topic: 'Co-op games, voice chat, and clips',
description: 'A friendly server for Friday sessions.',
maxUsers: 64,
isPrivate: false
});
}
```
## Update Permissions
```js
export function activate(context) {
context.api.server.updatePermissions({
allowVoice: true,
allowVideo: true,
allowScreenShare: true
});
}
```
Only update settings or permissions as part of an explicit admin flow. Plugins should not silently rename servers or change access rules.

View File

@@ -0,0 +1,101 @@
---
sidebar_position: 10
---
# Storage API
Plugins can store local client data and per-server data. Desktop builds use Electron persistence when available; browser fallback uses renderer storage.
## Required Capabilities
| Method | Capability |
| --- | --- |
| `clientData.read(key)` | `storage.local` |
| `clientData.write(key, value)` | `storage.local` |
| `clientData.remove(key)` | `storage.local` |
| `serverData.read(key)` | `storage.serverData.read` |
| `serverData.write(key, value)` | `storage.serverData.write` |
| `serverData.remove(key)` | `storage.serverData.write` |
| `storage.get(key)` | `storage.local` |
| `storage.set(key, value)` | `storage.local` |
| `storage.remove(key)` | `storage.local` |
## Client Data
Client data belongs to this local user and client.
```js
export async function activate(context) {
await context.api.clientData.write('soundboard:volume', {
masterVolume: 0.7,
updatedAt: 1777473600000
});
const value = await context.api.clientData.read('soundboard:volume');
context.api.logger.info('Loaded client data', value);
}
```
## Server Data
Server data is local per-user/per-server state. It is not arbitrary signal-server persistence.
```js
export async function activate(context) {
await context.api.serverData.write('soundboard:favorites', [
{ id: 'chime', label: 'Chime', url: 'https://cdn.example.com/chime.wav' },
{ id: 'ready', label: 'Ready Check', url: 'https://cdn.example.com/ready.wav' }
]);
const favorites = await context.api.serverData.read('soundboard:favorites');
context.api.logger.info('Loaded server favorites', favorites);
}
```
## Remove Data
```js
export async function activate(context) {
await context.api.clientData.remove('soundboard:volume');
await context.api.serverData.remove('soundboard:favorites');
}
```
## Legacy Synchronous Storage
The `storage.*` methods are legacy local storage helpers. Prefer `clientData.*` for new plugins when async reads are acceptable.
```js
export function activate(context) {
context.api.storage.set('quick-toggle', { enabled: true });
const saved = context.api.storage.get('quick-toggle');
context.api.logger.info('Legacy storage value', saved);
context.api.storage.remove('quick-toggle');
}
```
## Manifest Data Declarations
Declare important data keys in the manifest.
```json
{
"data": [
{
"key": "soundboard:volume",
"scope": "client",
"storage": "local"
},
{
"key": "soundboard:favorites",
"scope": "server",
"storage": "serverData"
}
]
}
```

View File

@@ -0,0 +1,235 @@
---
sidebar_position: 11
---
# UI API
The UI API lets plugins add pages, settings pages, side panels, channel sections, actions, embed renderers, and controlled DOM mounts.
Prefer registered UI contributions over direct DOM mounting. Contribution APIs let Angular render the plugin UI when the matching app surface exists. Direct DOM mounting runs immediately and throws if the target selector is not present.
## Required Capabilities
| Method | Capability |
| --- | --- |
| `ui.registerAppPage(id, contribution)` | `ui.pages` |
| `ui.registerSettingsPage(id, contribution)` | `ui.settings` |
| `ui.registerSidePanel(id, contribution)` | `ui.sidePanel` |
| `ui.registerChannelSection(id, contribution)` | `ui.channelsSection` |
| `ui.registerComposerAction(id, contribution)` | `ui.pages` |
| `ui.registerProfileAction(id, contribution)` | `ui.pages` |
| `ui.registerToolbarAction(id, contribution)` | `ui.pages` |
| `ui.registerEmbedRenderer(id, contribution)` | `ui.embeds` |
| `ui.mountElement(id, request)` | `ui.dom` |
Every registration returns a disposable. Push it into `context.subscriptions`.
## App Page
```js
export function activate(context) {
context.subscriptions.push(context.api.ui.registerAppPage('dashboard', {
label: 'Raid Dashboard',
path: '/plugins/example.raid-helper/dashboard',
render: () => {
const root = document.createElement('section');
root.innerHTML = '<h1>Raid Dashboard</h1><p>Tonight: dungeon practice.</p>';
return root;
}
}));
}
```
The page is hosted by `/plugins/:pluginId/:pageId`.
## Settings Page
```js
export function activate(context) {
context.subscriptions.push(context.api.ui.registerSettingsPage('preferences', {
label: 'Raid Helper',
settingsKey: 'raid-helper',
order: 20,
render: () => {
const wrapper = document.createElement('section');
const label = document.createElement('label');
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.checked = true;
label.append(checkbox, ' Enable ready-check reminders');
wrapper.append(label);
return wrapper;
}
}));
}
```
## Side Panel
Use `ui.registerSidePanel` for content that belongs in the server sidebar plugin area. Do not mount directly into `[data-testid="plugin-room-side-panel"]`; that host is route-specific and may not exist during plugin activation.
```js
export function activate(context) {
context.subscriptions.push(context.api.ui.registerSidePanel('soundboard', {
label: 'Soundboard',
order: 10,
render: () => {
const panel = document.createElement('div');
const button = document.createElement('button');
button.type = 'button';
button.textContent = 'Play chime';
button.onclick = () => context.api.media.playAudioClip({
url: 'https://cdn.example.com/chime.wav',
volume: 0.6
});
panel.append(button);
return panel;
}
}));
}
```
Capabilities required: `ui.sidePanel` and `media.playAudio`.
## Channel Section
```js
export function activate(context) {
context.subscriptions.push(context.api.ui.registerChannelSection('events', {
label: 'Event Rooms',
type: 'custom',
order: 50
}));
}
```
## Composer Action
```js
export function activate(context) {
context.subscriptions.push(context.api.ui.registerComposerAction('insert-standup', {
icon: 'ST',
label: 'Insert standup prompt',
run: (actionContext) => {
context.api.messages.send(
'Standup: yesterday I..., today I..., blocked by...',
actionContext.textChannel?.id
);
}
}));
}
```
Capabilities required: `ui.pages` and `messages.send`.
## Profile Action
```js
export function activate(context) {
context.subscriptions.push(context.api.ui.registerProfileAction('wave', {
label: 'Wave',
run: (actionContext) => {
context.api.messages.send(`Waving at ${actionContext.user?.displayName ?? 'someone'}!`);
}
}));
}
```
## Toolbar Action
```js
export function activate(context) {
context.subscriptions.push(context.api.ui.registerToolbarAction('open-dashboard', {
label: 'Raid Helper',
run: () => {
context.api.logger.info('Open the Raid Helper plugin page from /plugins/example.raid-helper/dashboard');
}
}));
}
```
## Embed Renderer
```js
export function activate(context) {
context.subscriptions.push(context.api.ui.registerEmbedRenderer('raid-card', {
embedType: 'raid.card',
render: (payload) => {
const card = document.createElement('article');
const title = document.createElement('h3');
const body = document.createElement('p');
title.textContent = payload?.title ?? 'Raid';
body.textContent = payload?.description ?? 'No description provided.';
card.append(title, body);
return card;
}
}));
}
```
Example message content for this embed:
```text
toju:embed:raid.card:{"title":"Friday Raid","description":"Meet in Lobby at 20:00."}
```
## DOM Mount
Use DOM mounting only when normal UI contribution points are not enough. `ui.mountElement` resolves its target immediately. If the target does not exist, plugin activation fails with `Plugin mount target not found: <selector>`.
Safe uses:
- Mounting a global overlay, badge, or modal into `body` during activation.
- Mounting into a route-specific element only after checking that element exists.
Avoid:
- Mounting sidebar content into `[data-testid="plugin-room-side-panel"]`. Use `ui.registerSidePanel`.
- Mounting chat content into `app-chat-messages` during activation without checking for the element.
```js
export function activate(context) {
const badge = document.createElement('div');
badge.textContent = 'Raid helper active';
badge.style.position = 'fixed';
badge.style.right = '16px';
badge.style.bottom = '16px';
badge.style.padding = '8px 10px';
badge.style.background = '#111827';
badge.style.color = 'white';
badge.style.borderRadius = '6px';
context.subscriptions.push(context.api.ui.mountElement('active-badge', {
target: 'body',
position: 'beforeend',
element: badge
}));
}
```
Route-specific mount example with a guard:
```js
export function activate(context) {
const target = document.querySelector('app-chat-messages');
if (!target) {
context.api.logger.warn('Chat messages host is not rendered yet; skipping chat mount');
return;
}
const banner = document.createElement('div');
banner.textContent = 'Raid helper active in this chat.';
context.subscriptions.push(context.api.ui.mountElement('chat-banner', {
target,
position: 'afterbegin',
element: banner
}));
}
```
The runtime tags plugin-owned DOM and removes it on unload, but plugins should still keep mounts minimal and accessible.

View File

@@ -0,0 +1,89 @@
---
sidebar_position: 3
---
# Users and Roles API
The users and roles APIs read known users, read room members, and perform moderation or role changes when granted.
## Required Capabilities
| Method | Capability |
| --- | --- |
| `users.getCurrent()` | `users.read` |
| `users.list()` | `users.read` |
| `users.readMembers()` | `users.read` |
| `users.setRole(userId, role)` | `roles.manage` |
| `users.kick(userId)` | `users.manage` |
| `users.ban(userId, reason?)` | `users.manage` |
| `roles.list()` | `roles.read` |
| `roles.setAssignments(assignments)` | `roles.manage` |
## Read Users
```js
export function activate(context) {
const currentUser = context.api.users.getCurrent();
const knownUsers = context.api.users.list();
const roomMembers = context.api.users.readMembers();
context.api.logger.info('Room user summary', {
currentUser: currentUser?.displayName,
knownUserCount: knownUsers.length,
memberCount: roomMembers.length
});
}
```
Example member data:
```json
[
{ "id": "member-1", "userId": "user-alice-01", "displayName": "Alice", "role": "admin" },
{ "id": "member-2", "userId": "user-muse-01", "displayName": "Muse", "role": "member" }
]
```
## Read Roles
```js
export function activate(context) {
const roles = context.api.roles.list();
context.api.logger.info('Available roles', roles.map((role) => ({
id: role.id,
name: role.name,
permissions: role.permissions
})));
}
```
## Set a User Role
```js
export function activate(context) {
context.api.users.setRole('user-muse-01', 'moderator');
}
```
## Replace Role Assignments
```js
export function activate(context) {
context.api.roles.setAssignments([
{ userId: 'user-alice-01', roleId: 'admin' },
{ userId: 'user-muse-01', roleId: 'moderator' }
]);
}
```
## Kick or Ban a User
```js
export function activate(context) {
context.api.users.kick('user-spam-01');
context.api.users.ban('user-spam-02', 'Repeated spam in support channels');
}
```
Moderation calls should normally be behind an explicit user action in plugin UI. Do not run destructive moderation automatically on activation.

View File

@@ -0,0 +1,50 @@
---
sidebar_position: 3
---
# Capabilities
Capabilities protect privileged app surfaces. A plugin must declare a capability in its manifest and the user must grant it before the runtime allows the corresponding API call.
| Capability | API areas | Notes |
| --- | --- | --- |
| `profile.read` | `profile.getCurrent()` | Reads the current user. |
| `profile.write` | `profile.update()`, `profile.updateAvatar()` | Updates local profile fields and avatar metadata. |
| `users.read` | `users.getCurrent()`, `users.list()`, `users.readMembers()` | Reads users and server members. |
| `users.manage` | `users.kick()`, `users.ban()`, `server.registerPluginUser()` | Can create plugin users and moderate members. |
| `roles.read` | `roles.list()` | Reads server roles. |
| `roles.manage` | `roles.setAssignments()`, `users.setRole()` | Changes role assignments or user roles. |
| `messages.read` | `messages.readCurrent()`, message bus latest snapshots | Reads current channel messages. |
| `messages.send` | `messages.send()`, `messages.sendAsPluginUser()` | Sends messages as the current user or registered plugin user. |
| `messages.editOwn` | `messages.edit()` | Edits plugin-owned messages. |
| `messages.deleteOwn` | `messages.delete()` | Deletes plugin-owned messages. |
| `messages.moderate` | `messages.moderateDelete()` | Moderation delete path. |
| `messages.sync` | `messages.sync()` | Syncs message arrays into client state. |
| `channels.read` | `channels.list()`, `channels.select()` | Reads and selects channels. |
| `channels.manage` | `channels.addAudioChannel()`, `channels.addVideoChannel()`, `channels.remove()`, `channels.rename()` | Mutates channel or channel-section state. |
| `server.read` | `server.getCurrent()` | Reads active server. |
| `server.manage` | `server.updatePermissions()`, `server.updateSettings()` | Updates server permissions or settings. |
| `p2p.data` | `p2p.connectedPeers()`, `p2p.broadcastData()`, `p2p.sendData()` | Uses plugin peer data paths. |
| `p2p.media` | Reserved peer media features. | Included for media-facing plugins. |
| `media.playAudio` | `media.playAudioClip()` | Plays an audio URL locally. |
| `media.addAudioStream` | `media.addCustomAudioStream()` | Adds a custom stream to voice handling. |
| `media.addVideoStream` | `media.addCustomVideoStream()` | Registers custom video stream contribution. |
| `audio.volume` | `media.setInputVolume()`, `media.setOutputVolume()` | Adjusts local voice volume. |
| `audio.effects` | Reserved audio effect features. | Included for audio processing plugins. |
| `ui.settings` | `ui.registerSettingsPage()` | Adds settings pages. |
| `ui.pages` | `ui.registerAppPage()`, `ui.registerComposerAction()`, `ui.registerProfileAction()`, `ui.registerToolbarAction()` | Adds app pages and actions. |
| `ui.sidePanel` | `ui.registerSidePanel()` | Adds side panels. |
| `ui.channelsSection` | `ui.registerChannelSection()` | Adds channel sections. |
| `ui.embeds` | `ui.registerEmbedRenderer()` | Renders custom embeds. |
| `ui.dom` | `ui.mountElement()` | Mounts plugin-owned DOM into app targets. |
| `storage.local` | `storage.*`, `clientData.*` | Reads and writes plugin-local data. |
| `storage.serverData.read` | `serverData.read()` | Reads local per-user/per-server plugin data. |
| `storage.serverData.write` | `serverData.write()`, `serverData.remove()` | Writes or removes local per-user/per-server plugin data. |
| `events.server.publish` | `events.publishServer()` | Publishes declared server plugin events. |
| `events.server.subscribe` | `events.subscribeServer()` | Subscribes to declared server plugin events. |
| `events.p2p.publish` | `events.publishP2p()`, `messageBus.publish()`, `messageBus.sendLatestMessages()` | Publishes declared P2P/plugin bus events. |
| `events.p2p.subscribe` | `events.subscribeP2p()`, `messageBus.subscribe()` | Subscribes to declared P2P/plugin bus events. |
## Recommended Practice
Request the fewest capabilities possible. Separate broad features into optional plugin modules when a single plugin would otherwise need many unrelated grants.

View File

@@ -0,0 +1,106 @@
---
sidebar_position: 1
---
# Create a Plugin
MetoYou plugins are browser-safe ES modules loaded by the Angular renderer. A plugin receives a frozen `TojuClientPluginApi`, declares every privileged capability in its manifest, and registers cleanup work through disposables.
## Folder Layout
A local desktop plugin is discovered from an immediate child folder under the app data `plugins` directory.
```text
my-plugin/
toju-plugin.json
main.js
README.md
icon.svg
```
The manifest file can be named `toju-plugin.json` or `plugin.json`. Entrypoints and readmes must stay inside the plugin folder.
## Minimal Manifest
```json
{
"schemaVersion": 1,
"id": "example.hello-world",
"title": "Hello World",
"description": "Adds a toolbar action that sends a message.",
"version": "1.0.0",
"kind": "client",
"scope": "client",
"apiVersion": "1.0.0",
"compatibility": {
"minimumTojuVersion": "1.0.0"
},
"entrypoint": "./main.js",
"capabilities": ["messages.send", "ui.pages"]
}
```
## Entrypoint
```js
export function activate(context) {
const { api } = context;
api.logger.info('Hello World activated');
const disposable = api.ui.registerToolbarAction('hello', {
label: 'Hello',
run: () => api.messages.send('Hello from my plugin')
});
context.subscriptions.push(disposable);
}
export function ready(context) {
context.api.logger.info('All ready plugins have loaded');
}
export function deactivate(context) {
context.api.logger.info('Hello World deactivated');
}
```
## Lifecycle Hooks
| Hook | When it runs | Use it for |
| --- | --- | --- |
| `activate(context)` | During explicit plugin activation. | Register UI, subscribe to events, initialize state. |
| `ready(context)` | After the load-order pass has activated ready plugins. | Cross-plugin coordination that needs other plugins loaded. |
| `deactivate(context)` | During unload or reload. | Flush state and log shutdown. Disposables are also cleaned up by the host. |
| `onPluginDataChanged(context, event)` | When plugin data changes are observed. | React to plugin-scoped persistence changes. |
| `onServerRequirementsChanged(context, snapshot)` | When server plugin requirements change. | Adapt to required, optional, blocked, or incompatible server plugins. |
## Cleanup
Every API registration returns a disposable. Push it into `context.subscriptions`.
```js
const subscription = api.messageBus.subscribe({
topic: 'poll:votes',
handler: (event) => api.logger.info('vote received', event.payload)
});
context.subscriptions.push(subscription);
```
The plugin host disposes subscriptions in reverse order when the plugin unloads.
## Capability Grants
A plugin can only call privileged APIs after the matching capability is declared in the manifest and granted by the user. Keep the manifest narrow. For example, a plugin that only adds a settings page does not need message or user management capabilities.
## Testing Locally
1. Create the plugin folder in the desktop plugins directory.
2. Open the Plugin Manager.
3. Register or refresh local plugins.
4. Grant required capabilities.
5. Activate the plugin.
6. Inspect plugin logs in the manager.
For broad API examples, compare against the E2E fixture plugin under `toju-app/public/plugins/e2e-all-api/`.

View File

@@ -0,0 +1,204 @@
---
sidebar_position: 5
---
# Examples
## Toolbar Message Plugin
`toju-plugin.json`
```json
{
"schemaVersion": 1,
"id": "example.toolbar-message",
"title": "Toolbar Message",
"description": "Adds a toolbar action that sends a reusable message.",
"version": "1.0.0",
"kind": "client",
"scope": "client",
"apiVersion": "1.0.0",
"compatibility": {
"minimumTojuVersion": "1.0.0",
"verifiedTojuVersion": "1.0.0"
},
"entrypoint": "./main.js",
"capabilities": ["messages.send", "ui.pages"]
}
```
`main.js`
```js
export function activate(context) {
const { api } = context;
context.subscriptions.push(api.ui.registerToolbarAction('standup-message', {
label: 'Standup',
run: () => api.messages.send('Standup: yesterday, today, blocked')
}));
}
```
## Settings Page Plugin
```json
{
"schemaVersion": 1,
"id": "example.settings-page",
"title": "Settings Page Example",
"description": "Adds a plugin settings page and stores a local preference.",
"version": "1.0.0",
"kind": "client",
"apiVersion": "1.0.0",
"compatibility": { "minimumTojuVersion": "1.0.0" },
"entrypoint": "./main.js",
"capabilities": ["ui.settings", "storage.local"],
"settings": {
"type": "object",
"properties": {
"enabled": { "type": "boolean", "default": true }
}
}
}
```
```js
export function activate(context) {
const { api } = context;
context.subscriptions.push(api.ui.registerSettingsPage('preferences', {
label: 'Example Preferences',
render: () => {
const root = document.createElement('section');
const button = document.createElement('button');
button.type = 'button';
button.textContent = 'Remember preference';
button.onclick = () => api.storage.set('enabled', true);
root.append(button);
return root;
}
}));
}
```
## Server-Scoped Soundboard
A server-scoped plugin can be installed as a server requirement and auto-installed for server members when marked required.
```json
{
"schemaVersion": 1,
"id": "example.soundboard",
"title": "Server Soundboard",
"description": "Adds a soundboard side panel and announces played sounds.",
"version": "1.0.0",
"kind": "client",
"scope": "server",
"apiVersion": "1.0.0",
"compatibility": { "minimumTojuVersion": "1.0.0" },
"entrypoint": "./main.js",
"capabilities": [
"server.read",
"users.manage",
"ui.sidePanel",
"media.playAudio",
"messages.send"
],
"pluginUser": {
"displayName": "Soundboard",
"label": "Audio helper"
}
}
```
```js
export function activate(context) {
const { api } = context;
const botId = api.server.registerPluginUser({
id: 'soundboard-bot',
displayName: 'Soundboard'
});
context.subscriptions.push(api.ui.registerSidePanel('sounds', {
label: 'Soundboard',
render: () => {
const panel = document.createElement('div');
const button = document.createElement('button');
button.type = 'button';
button.textContent = 'Play chime';
button.onclick = async () => {
await api.media.playAudioClip({ url: './chime.wav', volume: 0.7 });
api.messages.sendAsPluginUser({ pluginUserId: botId, content: 'Played chime' });
};
panel.append(button);
return panel;
}
}));
}
```
## Message Bus Plugin
```json
{
"schemaVersion": 1,
"id": "example.poll-bus",
"title": "Poll Bus",
"description": "Uses the plugin message bus for lightweight P2P poll votes.",
"version": "1.0.0",
"kind": "client",
"apiVersion": "1.0.0",
"compatibility": { "minimumTojuVersion": "1.0.0" },
"entrypoint": "./main.js",
"capabilities": ["events.p2p.publish", "events.p2p.subscribe", "messages.read"]
}
```
```js
export function activate(context) {
const { api } = context;
context.subscriptions.push(api.messageBus.subscribe({
topic: 'poll:votes',
replayLatest: true,
latestMessageLimit: 20,
handler: (event) => api.logger.info('Vote received', event.payload)
}));
api.messageBus.publish({
topic: 'poll:votes',
payload: { option: 'A' },
includeLatestMessages: true,
includeSelf: true,
latestMessageLimit: 20
});
}
```
## Custom DOM Mount
Use `ui.dom` sparingly and cleanly. The runtime tags mounted elements with plugin ownership metadata and removes remaining mounted elements when the plugin unloads.
```js
export function activate(context) {
const badge = document.createElement('div');
badge.textContent = 'Plugin active';
badge.style.position = 'absolute';
badge.style.right = '1rem';
badge.style.bottom = '1rem';
context.subscriptions.push(context.api.ui.mountElement('active-badge', {
target: 'body',
element: badge
}));
}
```
## All-API Fixture
The repo includes an E2E fixture at `toju-app/public/plugins/e2e-all-api/`. It intentionally calls every public plugin API surface so Playwright coverage can validate the runtime. Use it as a compatibility reference, not as the minimal style for production plugins.

View File

@@ -0,0 +1,164 @@
---
sidebar_position: 2
---
# Manifest Model
The manifest is the source of truth for plugin identity, compatibility, runtime shape, capabilities, data, events, UI hints, and distribution metadata.
```ts
type TojuPluginInstallScope = 'client' | 'server';
type PluginEventDirection = 'clientToServer' | 'serverRelay' | 'p2pHint';
type PluginEventScope = 'server' | 'channel' | 'user' | 'plugin';
type PluginCapabilityId =
| 'profile.read'
| 'profile.write'
| 'users.read'
| 'users.manage'
| 'roles.read'
| 'roles.manage'
| 'messages.read'
| 'messages.send'
| 'messages.editOwn'
| 'messages.deleteOwn'
| 'messages.moderate'
| 'messages.sync'
| 'channels.read'
| 'channels.manage'
| 'server.read'
| 'server.manage'
| 'p2p.data'
| 'p2p.media'
| 'media.playAudio'
| 'media.addAudioStream'
| 'media.addVideoStream'
| 'audio.volume'
| 'audio.effects'
| 'ui.settings'
| 'ui.pages'
| 'ui.sidePanel'
| 'ui.channelsSection'
| 'ui.embeds'
| 'ui.dom'
| 'storage.local'
| 'storage.serverData.read'
| 'storage.serverData.write'
| 'events.server.publish'
| 'events.server.subscribe'
| 'events.p2p.publish'
| 'events.p2p.subscribe';
interface TojuPluginManifest {
schemaVersion: 1;
id: string;
title: string;
description: string;
version: string;
kind: 'client' | 'library';
scope?: TojuPluginInstallScope;
apiVersion: string;
compatibility: {
minimumTojuVersion: string;
maximumTojuVersion?: string;
verifiedTojuVersion?: string;
};
entrypoint?: string;
bundle?: {
url: string;
entrypoint?: string;
};
readme?: string;
homepage?: string;
bugs?: string;
changelog?: string;
license?: string;
authors?: {
name: string;
email?: string;
url?: string;
}[];
capabilities?: PluginCapabilityId[];
events?: {
eventName: string;
direction: PluginEventDirection;
scope: PluginEventScope;
maxPayloadBytes?: number;
schema?: string;
}[];
data?: {
key: string;
schema?: string;
scope: string;
storage: 'local' | 'serverData';
}[];
relationships?: {
after?: string[];
before?: string[];
conflicts?: string[];
optional?: { id: string; versionRange?: string }[];
requires?: { id: string; versionRange?: string }[];
};
load?: {
priority?: 'bootstrap' | 'high' | 'default' | 'low';
};
pluginUser?: {
avatar?: string;
displayName: string;
label?: string;
};
settings?: Record<string, unknown>;
ui?: Record<string, unknown>;
}
```
## Required Fields
| Field | Meaning |
| --- | --- |
| `schemaVersion` | Manifest schema version. Currently `1`. |
| `id` | Stable plugin id. Use a reverse-DNS or package-style id. |
| `title` | Human-readable plugin name. |
| `description` | Short explanation shown in plugin UI. |
| `version` | Plugin version. |
| `kind` | `client` for runtime plugins, `library` for shared dependency-style entries. |
| `apiVersion` | Plugin API version expected by the plugin. |
| `compatibility.minimumTojuVersion` | Oldest app version the plugin supports. |
## Scope
`scope: "client"` installs the plugin for the current client. Omit `scope` for the same behavior.
`scope: "server"` marks a plugin as server-scoped. Server-scoped store entries can be installed to a chat server as requirements. Required server plugins are auto-installed for members when that server opens; optional requirements stay listed but do not auto-install.
When a user installs a server-scoped plugin into the server they are currently viewing, MetoYou enables that plugin id locally and activates the plugin immediately after the local manifest is registered. Installing a server-scoped plugin for another server records the activation preference so it activates when that server is opened.
## Entrypoint and Bundle
Use `entrypoint` for a browser-resolvable module relative to the manifest. Use `bundle.url` when publishing a cached browser bundle through a plugin source manifest. Desktop installs cache bundle files into app data and load the cached manifest afterward.
## Events
Every server or P2P plugin event should be declared before it is published or subscribed to.
```json
{
"events": [
{
"eventName": "poll:vote",
"direction": "p2pHint",
"scope": "channel",
"maxPayloadBytes": 2048
}
]
}
```
## Data Declarations
Use `data` to document plugin-owned data keys and intended storage.
- `local` maps to client-local plugin data.
- `serverData` maps to local per-user/per-server plugin data.
Signal server HTTP persistence for arbitrary plugin data is disabled by design.

View File

@@ -0,0 +1,66 @@
---
sidebar_position: 1
---
# First Steps
MetoYou is a chat app for servers, text conversations, direct messages, and live voice. You do not need to understand the technical parts to use it.
## Main Words
| Word | Meaning |
| --- | --- |
| Server | A shared space for a community, team, or group. |
| Text channel | A named chat room inside a server. Messages stay in that channel. |
| Voice channel | A named live room inside a server. Join it when you want to talk, share camera, or share screen. |
| Direct message | A private conversation outside a server channel. |
| Plugin | An add-on that can add buttons, panels, tools, integrations, or server-specific features. |
## Sign In
1. Open MetoYou.
2. Sign in with your username and password.
3. If you use more than one signaling server, choose the server endpoint that owns your account.
A signaling server handles accounts, server discovery, membership, and connection setup. In normal use you can think of it as the place MetoYou checks when you log in and join servers.
## Find a Server
1. Open the server search page.
2. Search by server name or browse the available list.
3. Select a server.
4. Join directly if it is public, enter the password if it is protected, or use an invite link if someone sent you one.
After joining, the server appears in the vertical server rail on the left. Click a server icon there to switch servers.
## Read and Send Messages
1. Click a server in the left rail.
2. Pick a text channel under **Text Channels**.
3. Type in the composer at the bottom of the chat.
4. Press Enter or use the send button.
Text channels keep different topics separate. For example, a server might have `general`, `announcements`, and `support` as separate text channels.
## Start Talking
1. Open a server.
2. Pick a voice channel under **Voice Channels**.
3. Click the voice channel to join.
4. Use the voice controls to mute, deafen, start camera, share screen, or leave.
Voice is live. Text messages are written chat. They can happen at the same time, but they are different channel types.
## Use Direct Messages
Direct messages are one-to-one conversations. They are separate from server text channels, so they do not depend on which server you are viewing.
## Open Settings
Settings contain account, voice, plugin, server, desktop, update, local API, theme, and data controls. Desktop users can also manage local data import/export and local documentation/API hosting.
## Install Plugins
Plugins are installed from the Plugin Store or Plugin Manager. Some plugins are global client plugins. Other plugins are server-scoped and only apply to a specific server.
See [Plugins for Users](./plugins.md) for the full non-technical plugin guide.

View File

@@ -0,0 +1,82 @@
---
sidebar_position: 5
---
# Plugins for Users
Plugins add features to MetoYou. They can add pages, buttons, panels, settings, sounds, message tools, custom embeds, or server-specific behavior.
## Types of Plugins
| Type | What it means |
| --- | --- |
| Client plugin | Installed for your app. It follows you across servers when active. |
| Server plugin | Installed for a specific server. It may be required, recommended, optional, blocked, or incompatible. |
| Library plugin | Shared plugin code used by other plugins. It is not normally something users interact with directly. |
## Install from the Plugin Store
1. Open the Plugin Store from the title bar or Settings.
2. Browse or search available plugins.
3. Open the plugin details.
4. Read the description, version, source, and capability list.
5. Choose install.
6. Review and grant only the capabilities you trust.
7. Activate the plugin.
Server-scoped plugins installed to the server you are currently viewing are enabled and activated automatically after install, so their panels, actions, or embeds can appear immediately.
## Install a Local Plugin
Desktop builds can discover local plugin folders from the app data plugins directory.
1. Put the plugin folder in the desktop plugins directory.
2. Open Settings.
3. Open the Plugin Manager.
4. Refresh or register local plugins.
5. Grant capabilities and activate the plugin.
## Server Plugin Prompts
When a server uses plugins, MetoYou may show a prompt.
| Status | Meaning |
| --- | --- |
| Required | You must install the plugin to join or continue using that server. |
| Recommended | The server suggests the plugin, but you can choose. |
| Optional | The plugin is available for the server, but not required. |
| Blocked | The server marks the plugin as not allowed. |
| Incompatible | The plugin version does not work with your app version or the server requirement. |
Required plugins are still installed locally on your device. The signaling server stores requirement metadata only; it does not run plugin code.
## Capability Grants
Plugins must ask for capabilities before using sensitive features.
Examples:
| Capability area | Why a plugin might ask |
| --- | --- |
| Messages | Send messages, read current messages, moderate messages, or render embeds. |
| Users and roles | Read member lists, create plugin users, or manage users. |
| Voice and media | Play audio, add an audio stream, add a video stream, or adjust volume. |
| UI | Add pages, settings pages, side panels, toolbar buttons, or DOM elements. |
| Storage | Save plugin preferences locally or per server. |
Only grant capabilities to plugins you trust.
## Manage Plugins
The Plugin Manager lets you:
- activate, deactivate, reload, or unload plugins;
- grant or revoke capabilities;
- inspect plugin logs;
- see plugin UI contribution counts;
- review server plugin requirements;
- uninstall plugins.
## Plugin Safety Notes
Plugins are browser-safe JavaScript modules loaded by the client. They do not run on the signaling server. A plugin can only call privileged MetoYou APIs when its manifest declares the capability and you grant it.

View File

@@ -0,0 +1,65 @@
---
sidebar_position: 2
---
# Servers and Channels
A server is the main shared space in MetoYou. Servers contain members, channels, permissions, optional plugins, and server settings.
## Server Rail
The server rail is the vertical list of servers on the left side of the app.
- Click a server icon to open it.
- Use the add/search control to find or join more servers.
- A badge can show unread activity.
- Server context actions can include invite, leave, or server settings depending on your permissions.
## Text Channels
Text channels are written conversations. Each text channel has its own message list.
Common examples:
| Channel | Use |
| --- | --- |
| `general` | Everyday chat. |
| `announcements` | Updates from owners or admins. |
| `support` | Help requests. |
| `clips` | Shared media or links. |
Messages, replies, reactions, attachments, GIFs, typing indicators, and plugin-created messages are scoped to the active text channel.
## Voice Channels
Voice channels are live spaces. Joining a voice channel connects your microphone and lets you use camera or screen sharing when enabled.
Voice channel examples:
| Channel | Use |
| --- | --- |
| `Lobby` | Casual drop-in voice. |
| `Gaming` | In-game voice. |
| `Meeting` | Focused calls. |
| `Support Room` | Live help. |
## Text Channels vs Voice Channels
| Text channel | Voice channel |
| --- | --- |
| Written messages. | Live audio and media. |
| You can read later. | You join and leave in real time. |
| Uses the message composer. | Uses voice controls. |
| Good for searchable discussions. | Good for conversations, calls, screen shares, and quick coordination. |
## Server Members
The member list shows people known to the server. Online members appear separately from offline members. Depending on permissions, owners, admins, or moderators can move users between voice channels, kick users, ban users, or change roles.
## Invites
Invite links help other users join a server. If a server is private or password-protected, the invite or password controls who can enter.
## Server Plugins
A server can recommend or require plugins. Required server plugins may block joining until you choose whether to install them. Optional and recommended plugins can be skipped.

View File

@@ -0,0 +1,33 @@
---
sidebar_position: 6
---
# Settings and Data
Settings control the app, voice, plugins, servers, themes, updates, local APIs, and desktop behavior.
## Common Settings
| Area | What you can manage |
| --- | --- |
| Account | Current profile, display details, and avatar metadata. |
| Voice | Devices, volumes, bitrate, latency, noise reduction, screen share preferences. |
| Plugins | Installed plugins, capability grants, plugin logs, and plugin store sources. |
| Server | Server details, channels, roles, moderation, plugin requirements, and member controls. |
| Theme | App colors and visual preferences. |
| Desktop | Tray behavior, auto-start, hardware acceleration, updates, and local data tools. |
| Local API | Local HTTP server, API docs, Docusaurus docs, and allowed signaling servers. |
## Local Data
Desktop MetoYou stores local app data on your device. That can include rooms, messages, users, plugin data, settings, and metadata. The desktop settings include data import/export tools.
## Local API and Documentation Hosting
The desktop app can start a local HTTP server. It is off by default. When enabled, it can serve:
- Local REST API endpoints under `/api/...`;
- Scalar REST API docs at `/docs`;
- this Docusaurus site at `/docusaurus`.
Authentication for protected local API routes uses a local bearer token. Login is checked against an allowed signaling server that you configure in settings.

View File

@@ -0,0 +1,37 @@
---
sidebar_position: 3
---
# Text and Direct Messages
Text channels and direct messages both use written chat, but they are meant for different situations.
## Text Channels
Text channels belong to a server. Everyone with access to that server and channel can participate.
You can use text channels to:
- send normal messages;
- edit or delete your own messages when allowed;
- react to messages;
- send attachments;
- browse and send GIFs when available;
- see typing indicators;
- read synced message history stored on your device.
## Direct Messages
Direct messages are private conversations outside a server channel. Use them when a message is meant for one person instead of the server.
## Attachments and Media
Attachments can appear as files, images, audio, or video depending on the file type and what the app can preview. If an image or link cannot load directly, the app can use fallback paths where available.
## Message Sync
MetoYou stores messages locally and syncs recent messages with peers when connections are available. If you were offline, messages may appear after peers reconnect and exchange their recent message lists.
## Plugin Messages
Some plugins can send messages, create bot-style plugin users, render custom embeds, or add composer buttons. MetoYou asks for plugin capability grants before plugins can use privileged message features.

View File

@@ -0,0 +1,73 @@
---
sidebar_position: 4
---
# Voice Channels and Calls
Voice channels are live rooms inside a server. Join one when you want to talk, share camera, or share your screen.
## Join a Voice Channel
1. Open the server from the left server rail.
2. Find **Voice Channels** in the server side panel.
3. Click the voice channel you want to join.
4. Allow microphone access if your system asks.
5. Use the voice controls to manage your call.
When you join, other users in the same voice channel can hear you unless you are muted. Users in other voice channels are not part of your live voice room.
## Voice Controls
The voice controls can include:
| Control | What it does |
| --- | --- |
| Mute microphone | Stops sending your microphone audio. |
| Deafen | Stops playback and usually mutes your microphone too. |
| Camera | Starts or stops webcam video. |
| Screen share | Shares a screen or window. |
| Settings | Opens voice device and quality settings. |
| Leave | Disconnects from the voice channel. |
## Screen Sharing
1. Join a voice channel.
2. Click screen share.
3. Choose a screen or window.
4. Choose whether to include system audio when available.
5. Stop sharing from the voice controls when done.
The screen share picker can show screens and windows. Desktop audio support depends on operating system support and the selected source.
## Voice Workspace
When someone shares camera or screen, the voice workspace can expand into a larger media area. It can show focused streams, a grid of streams, or a minimized mini-window.
## Floating Voice Controls
If you navigate away from the server while still connected to voice, MetoYou can show floating voice controls. Use them to return to the voice server or leave the call.
## Voice Settings
Voice settings can include:
- input device;
- output device;
- input volume;
- output volume;
- audio bitrate;
- latency profile;
- noise reduction;
- screen share quality;
- system audio preference.
## Troubleshooting
| Problem | Try this |
| --- | --- |
| Nobody hears you | Check mute, input device, system microphone permission, and input volume. |
| You hear nobody | Check deafen, output device, output volume, and whether others are in the same voice channel. |
| Screen share is missing | Check desktop permissions and try a different screen or window. |
| Voice drops after switching servers | Return to the server with the active voice session or leave and rejoin the voice channel. |
Voice and screen sharing use peer-to-peer WebRTC media. The signaling server helps users connect, but the media itself travels through peer connections.

View File

@@ -0,0 +1,56 @@
---
sidebar_position: 2
---
# Using MetoYou
## Sign In
MetoYou signs in through a signaling server. The signaling server validates the user account, coordinates server membership, relays selected realtime messages, and helps peers establish WebRTC connections.
For the desktop Local API, the same signaling server allow-list is used before local bearer tokens can be issued. This keeps local automation tied to servers you explicitly trust.
## Find or Join Servers
Use the server search flow to find known servers. A server can be public, private, or password-protected depending on its settings. Invite links can be created from the title bar menu while a server is active.
A server contains:
- basic profile information such as name, topic, description, privacy, and maximum users;
- text channels;
- voice or custom channel sections;
- roles and permissions;
- members and voice state;
- optional server-scoped plugin requirements.
## Text Channels and Messages
Text channels are selected inside the active server. Messages are persisted locally by the client and synchronized through realtime events while connected. Plugins with the relevant capabilities can read, send, edit, delete, moderate, or sync messages.
Direct messages use the same shell but are not part of a room channel context.
## Voice, Video, and Screen Sharing
Voice and media are peer-to-peer. The signaling server coordinates connection setup, while media streams travel through WebRTC peer connections.
Desktop builds include platform integrations such as Linux display-server detection and optional monitor audio routing for screen sharing. Plugin media APIs can contribute custom audio or video streams when the user grants the necessary capabilities.
## Plugins
Open the Plugin Store from the title bar package button or menu. The plugin manager separates global client plugins from server-scoped plugins. Installed plugins can be activated, reloaded, unloaded, disabled, inspected for logs, and granted capabilities.
Plugins are explicit runtime modules. MetoYou loads browser-safe ES modules, passes a frozen API object, and cleans up registered disposables when a plugin unloads.
## Desktop Settings
Desktop settings cover:
- auto-start and close-to-tray behavior;
- hardware acceleration and Linux VA-API video encode options;
- update manifests and target update versions;
- local HTTP API hosting;
- Scalar API documentation;
- Docusaurus app/plugin documentation;
- allowed signaling servers for local API authentication;
- local plugin discovery and store sources;
- themes and user data import/export.

View File

@@ -0,0 +1,71 @@
import type { Config } from '@docusaurus/types';
import type * as Preset from '@docusaurus/preset-classic';
const config: Config = {
title: 'MetoYou Docs',
tagline: 'Desktop chat, local APIs, and plugin development',
url: 'http://127.0.0.1',
baseUrl: '/docusaurus/',
organizationName: 'metoyou',
projectName: 'metoyou',
onBrokenLinks: 'throw',
onBrokenMarkdownLinks: 'warn',
i18n: {
defaultLocale: 'en',
locales: ['en']
},
presets: [
[
'classic',
{
docs: {
routeBasePath: '/',
sidebarPath: './sidebars.ts'
},
blog: false,
theme: {
customCss: './src/css/custom.css'
}
} satisfies Preset.Options
]
],
themeConfig: {
navbar: {
title: 'MetoYou Docs',
items: [
{ type: 'docSidebar', sidebarId: 'mainSidebar', position: 'left', label: 'Guides' },
{ to: '/user-guide/first-steps', label: 'User Guide', position: 'left' },
{ to: '/developer/contributing', label: 'Developer Guide', position: 'left' },
{ to: '/plugin-development/create-a-plugin', label: 'Plugin Guide', position: 'left' },
{ to: '/developer/rest-api', label: 'REST API', position: 'left' }
]
},
footer: {
style: 'dark',
links: [
{
title: 'Docs',
items: [
{ label: 'First Steps', to: '/user-guide/first-steps' },
{ label: 'Voice Channels', to: '/user-guide/voice-channels' },
{ label: 'Plugins for Users', to: '/user-guide/plugins' },
{ label: 'Contributing', to: '/developer/contributing' },
{ label: 'Create a Plugin', to: '/plugin-development/create-a-plugin' },
{ label: 'Plugin API Reference', to: '/plugin-development/api-reference' },
{ label: 'Local REST API', to: '/developer/rest-api' }
]
}
],
copyright: 'MetoYou local documentation. Built with Docusaurus.'
},
prism: {
additionalLanguages: [
'bash',
'json',
'typescript'
]
}
} satisfies Preset.ThemeConfig
};
export default config;

18490
docs-site/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

28
docs-site/package.json Normal file
View File

@@ -0,0 +1,28 @@
{
"name": "metoyou-docs",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "docusaurus start --host 127.0.0.1",
"build": "docusaurus build",
"serve": "docusaurus serve --host 127.0.0.1"
},
"dependencies": {
"@docusaurus/core": "3.10.0",
"@docusaurus/preset-classic": "3.10.0",
"@mdx-js/react": "^3.1.1",
"clsx": "^2.1.1",
"prism-react-renderer": "^2.4.1",
"react": "^19.1.1",
"react-dom": "^19.1.1"
},
"devDependencies": {
"@docusaurus/module-type-aliases": "3.10.0",
"@docusaurus/tsconfig": "3.10.0",
"@docusaurus/types": "3.10.0",
"typescript": "~5.9.2"
},
"overrides": {
"webpack": "5.101.3"
}
}

62
docs-site/sidebars.ts Normal file
View File

@@ -0,0 +1,62 @@
import type { SidebarsConfig } from '@docusaurus/plugin-content-docs';
const sidebars: SidebarsConfig = {
mainSidebar: [
'intro',
{
type: 'category',
label: 'User Guide',
items: [
'user-guide/first-steps',
'user-guide/servers-and-channels',
'user-guide/text-and-direct-messages',
'user-guide/voice-channels',
'user-guide/plugins',
'user-guide/settings',
'using-metoyou'
]
},
{
type: 'category',
label: 'Developer Guide',
items: [
'developer/contributing',
'developer/docusaurus-site',
'developer/dom-structure',
'developer/rest-api',
'developer/llm-plugin-builder-guide',
'desktop-and-local-api'
]
},
{
type: 'category',
label: 'Plugin Development',
items: [
'plugin-development/create-a-plugin',
'plugin-development/manifest',
'plugin-development/capabilities',
'plugin-development/api-reference',
{
type: 'category',
label: 'Plugin API Examples',
items: [
'plugin-development/api/context-and-logging',
'plugin-development/api/profile',
'plugin-development/api/users-and-roles',
'plugin-development/api/server',
'plugin-development/api/channels',
'plugin-development/api/messages-and-typing',
'plugin-development/api/events',
'plugin-development/api/message-bus',
'plugin-development/api/p2p-and-media',
'plugin-development/api/storage',
'plugin-development/api/ui'
]
},
'plugin-development/examples'
]
}
]
};
export default sidebars;

View File

@@ -0,0 +1,40 @@
:root {
--ifm-color-primary: #2f9ab2;
--ifm-color-primary-dark: #2a8ba0;
--ifm-color-primary-darker: #287f94;
--ifm-color-primary-darkest: #216979;
--ifm-color-primary-light: #36abc5;
--ifm-color-primary-lighter: #43b4ce;
--ifm-color-primary-lightest: #6cc5d8;
--ifm-code-font-size: 92%;
--ifm-border-radius: 6px;
}
[data-theme='dark'] {
--ifm-background-color: #101318;
--ifm-background-surface-color: #171b22;
--ifm-navbar-background-color: #12161d;
--ifm-footer-background-color: #0b0e13;
--ifm-color-primary: #58c4dc;
--ifm-color-primary-dark: #36b7d3;
--ifm-color-primary-darker: #27aeca;
--ifm-color-primary-darkest: #208fa6;
--ifm-color-primary-light: #79d1e3;
--ifm-color-primary-lighter: #8bd7e7;
--ifm-color-primary-lightest: #bde9f1;
}
.hero--primary {
--ifm-hero-background-color: #151b24;
--ifm-hero-text-color: #f6f8fb;
}
.theme-doc-markdown table code,
.theme-doc-markdown li code,
.theme-doc-markdown p code {
border: 1px solid var(--ifm-color-emphasis-300);
}
.plugin-api-table td:first-child {
white-space: nowrap;
}

View File

@@ -0,0 +1,3 @@
# E2E Plugin API Fixture
This plugin is intentionally tiny. Tests use its manifest to exercise plugin discovery, server support metadata, server data, and plugin event relay APIs without executing plugin code.

View File

@@ -0,0 +1,6 @@
export default {
id: 'e2e.plugin-api',
activate(api) {
api?.logger?.info?.('E2E Plugin API Fixture activated');
}
};

View File

@@ -0,0 +1,49 @@
{
"apiVersion": "1.0.0",
"capabilities": [
"storage.serverData.read",
"storage.serverData.write",
"events.server.publish",
"events.server.subscribe",
"events.p2p.publish",
"events.p2p.subscribe"
],
"compatibility": {
"minimumTojuVersion": "1.0.0",
"verifiedTojuVersion": "1.0.0"
},
"data": [
{
"key": "settings",
"scope": "server",
"storage": "serverData"
},
{
"key": "presence",
"scope": "user",
"storage": "serverData"
}
],
"description": "Fixture plugin used by automated tests for plugin support APIs.",
"entrypoint": "./dist/main.js",
"events": [
{
"direction": "serverRelay",
"eventName": "e2e:relay",
"maxPayloadBytes": 2048,
"scope": "server"
},
{
"direction": "p2pHint",
"eventName": "e2e:p2p",
"maxPayloadBytes": 512,
"scope": "user"
}
],
"id": "e2e.plugin-api",
"kind": "client",
"readme": "./README.md",
"schemaVersion": 1,
"title": "E2E Plugin API Fixture",
"version": "1.0.0"
}

View File

@@ -0,0 +1,42 @@
import { readFile } from 'node:fs/promises';
import { join } from 'node:path';
export const TEST_PLUGIN_FIXTURE_DIR = join(__dirname, '..', 'fixtures', 'plugins', 'api-test-plugin');
export const TEST_PLUGIN_ID = 'e2e.plugin-api';
export const TEST_PLUGIN_RELAY_EVENT = 'e2e:relay';
export const TEST_PLUGIN_P2P_EVENT = 'e2e:p2p';
export interface PluginApiTestManifestEvent {
direction: 'clientToServer' | 'serverRelay' | 'p2pHint';
eventName: string;
maxPayloadBytes?: number;
scope: 'server' | 'channel' | 'user' | 'plugin';
}
export interface PluginApiTestManifest {
description: string;
events: PluginApiTestManifestEvent[];
id: string;
title: string;
version: string;
}
export async function readPluginApiTestManifest(): Promise<PluginApiTestManifest> {
const manifestPath = join(TEST_PLUGIN_FIXTURE_DIR, 'toju-plugin.json');
const manifestText = await readFile(manifestPath, 'utf8');
return JSON.parse(manifestText) as PluginApiTestManifest;
}
export function getPluginApiTestEvent(
manifest: PluginApiTestManifest,
eventName: string
): PluginApiTestManifestEvent {
const eventDefinition = manifest.events.find((event) => event.eventName === eventName);
if (!eventDefinition) {
throw new Error(`Expected fixture plugin to define ${eventName}`);
}
return eventDefinition;
}

View File

@@ -58,6 +58,10 @@ function buildSeededEndpointStorageState(
function applySeededEndpointStorageState(storageState: SeededEndpointStorageState): void { function applySeededEndpointStorageState(storageState: SeededEndpointStorageState): void {
try { try {
const storage = window.localStorage; const storage = window.localStorage;
const currentUserId = storage.getItem('metoyou_currentUserId')?.trim() || null;
const generalSettings = JSON.stringify({
reopenLastViewedChat: false
});
storage.setItem(storageState.key, JSON.stringify(storageState.endpoints)); storage.setItem(storageState.key, JSON.stringify(storageState.endpoints));
storage.setItem(storageState.removedKey, JSON.stringify([ storage.setItem(storageState.removedKey, JSON.stringify([
@@ -65,11 +69,57 @@ function applySeededEndpointStorageState(storageState: SeededEndpointStorageStat
'toju-primary', 'toju-primary',
'toju-sweden' 'toju-sweden'
])); ]));
storage.setItem('metoyou_general_settings', generalSettings);
if (currentUserId) {
storage.setItem(`metoyou_general_settings__${encodeURIComponent(currentUserId)}`, generalSettings);
}
const keysToRemove: string[] = [];
for (let index = 0; index < storage.length; index += 1) {
const key = storage.key(index);
if (key === 'metoyou_lastViewedChat' || key?.startsWith('metoyou_lastViewedChat__')) {
keysToRemove.push(key);
}
}
for (const key of keysToRemove) {
storage.removeItem(key);
}
} catch { } catch {
// about:blank and some Playwright UI pages deny localStorage access. // about:blank and some Playwright UI pages deny localStorage access.
} }
} }
export async function disableLastViewedChatResume(page: Page): Promise<void> {
await page.evaluate(() => {
const currentUserId = localStorage.getItem('metoyou_currentUserId')?.trim() || null;
const generalSettings = JSON.stringify({ reopenLastViewedChat: false });
const keysToRemove: string[] = [];
localStorage.setItem('metoyou_general_settings', generalSettings);
if (currentUserId) {
localStorage.setItem(`metoyou_general_settings__${encodeURIComponent(currentUserId)}`, generalSettings);
}
for (let index = 0; index < localStorage.length; index += 1) {
const key = localStorage.key(index);
if (key === 'metoyou_lastViewedChat' || key?.startsWith('metoyou_lastViewedChat__')) {
keysToRemove.push(key);
}
}
for (const key of keysToRemove) {
localStorage.removeItem(key);
}
});
}
export async function installTestServerEndpoint( export async function installTestServerEndpoint(
context: BrowserContext, context: BrowserContext,
port: number = Number(process.env.TEST_SERVER_PORT) || 3099 port: number = Number(process.env.TEST_SERVER_PORT) || 3099

View File

@@ -1,6 +1,7 @@
import { type Page, type Locator } from '@playwright/test'; import { type Page, type Locator } from '@playwright/test';
export class LoginPage { export class LoginPage {
readonly form: Locator;
readonly usernameInput: Locator; readonly usernameInput: Locator;
readonly passwordInput: Locator; readonly passwordInput: Locator;
readonly serverSelect: Locator; readonly serverSelect: Locator;
@@ -9,12 +10,15 @@ export class LoginPage {
readonly registerLink: Locator; readonly registerLink: Locator;
constructor(private page: Page) { constructor(private page: Page) {
this.form = page.locator('#login-username').locator('xpath=ancestor::div[contains(@class, "space-y-3")]')
.first();
this.usernameInput = page.locator('#login-username'); this.usernameInput = page.locator('#login-username');
this.passwordInput = page.locator('#login-password'); this.passwordInput = page.locator('#login-password');
this.serverSelect = page.locator('#login-server'); this.serverSelect = page.locator('#login-server');
this.submitButton = page.getByRole('button', { name: 'Login' }); this.submitButton = this.form.getByRole('button', { name: 'Login' });
this.errorText = page.locator('.text-destructive'); this.errorText = page.locator('.text-destructive');
this.registerLink = page.getByRole('button', { name: 'Register' }); this.registerLink = this.form.getByRole('button', { name: 'Register' });
} }
async goto() { async goto() {

View File

@@ -43,8 +43,11 @@ export class RegisterPage {
async register(username: string, displayName: string, password: string) { async register(username: string, displayName: string, password: string) {
await this.usernameInput.fill(username); await this.usernameInput.fill(username);
await expect(this.usernameInput).toHaveValue(username);
await this.displayNameInput.fill(displayName); await this.displayNameInput.fill(displayName);
await expect(this.displayNameInput).toHaveValue(displayName);
await this.passwordInput.fill(password); await this.passwordInput.fill(password);
await expect(this.passwordInput).toHaveValue(password);
await this.submitButton.click(); await this.submitButton.click();
} }
} }

View File

@@ -22,7 +22,7 @@ export class ServerSearchPage {
readonly dialogCancelButton: Locator; readonly dialogCancelButton: Locator;
constructor(private page: Page) { constructor(private page: Page) {
this.searchInput = page.getByPlaceholder('Search servers...'); this.searchInput = page.getByPlaceholder('Search servers and users...');
this.railCreateServerButton = page.locator('button[title="Create Server"]'); this.railCreateServerButton = page.locator('button[title="Create Server"]');
this.searchCreateServerButton = page.getByRole('button', { name: 'Create New Server' }); this.searchCreateServerButton = page.getByRole('button', { name: 'Create New Server' });
this.createServerButton = this.searchCreateServerButton; this.createServerButton = this.searchCreateServerButton;
@@ -79,7 +79,19 @@ export class ServerSearchPage {
await this.page.getByRole('button', { name }).click(); await this.page.getByRole('button', { name }).click();
} }
async joinServerFromSearch(name: string) { async joinServerFromSearch(name: string, options: { acceptPluginDownloads?: boolean } = {}) {
await this.page.locator('button', { hasText: name }).click(); await this.searchInput.fill(name);
const serverCard = this.page.locator('div[title]', { hasText: name }).first();
await expect(serverCard).toBeVisible({ timeout: 15_000 });
await serverCard.dblclick();
if (options.acceptPluginDownloads) {
const pluginConsentDialog = this.page.getByRole('dialog', { name: /uses plugins/ });
await expect(pluginConsentDialog).toBeVisible({ timeout: 20_000 });
await pluginConsentDialog.getByRole('button', { name: 'Accept and join' }).click();
}
} }
} }

View File

@@ -0,0 +1,284 @@
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
chromium,
type BrowserContext,
type Page
} from '@playwright/test';
import { test, expect } from '../../fixtures/multi-client';
import { installTestServerEndpoint } from '../../helpers/seed-test-endpoint';
import { ChatMessagesPage } from '../../pages/chat-messages.page';
import { LoginPage } from '../../pages/login.page';
import { RegisterPage } from '../../pages/register.page';
import { ServerSearchPage } from '../../pages/server-search.page';
interface TestUser {
username: string;
displayName: string;
password: string;
}
interface PersistentClient {
context: BrowserContext;
page: Page;
userDataDir: string;
}
const CLIENT_LAUNCH_ARGS = ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream'];
test.describe('User session data isolation', () => {
test.describe.configure({ timeout: 240_000 });
test('preserves a user saved rooms and local history across app restarts', async ({ testServer }) => {
const suffix = uniqueName('persist');
const userDataDir = await mkdtemp(join(tmpdir(), 'metoyou-auth-persist-'));
const alice: TestUser = {
username: `alice_${suffix}`,
displayName: 'Alice',
password: 'TestPass123!'
};
const aliceServerName = `Alice Session Server ${suffix}`;
const aliceMessage = `Alice persisted message ${suffix}`;
let client: PersistentClient | null = null;
try {
client = await launchPersistentClient(userDataDir, testServer.port);
await test.step('Alice registers and creates local chat history', async () => {
await registerUser(client.page, alice);
await createServerAndSendMessage(client.page, aliceServerName, aliceMessage);
});
await test.step('Alice sees the same saved room and message after a full restart', async () => {
await restartPersistentClient(client, testServer.port);
await openApp(client.page);
await expect(client.page).not.toHaveURL(/\/login/, { timeout: 15_000 });
await expectSavedRoomAndHistory(client.page, aliceServerName, aliceMessage);
});
} finally {
await closePersistentClient(client);
await rm(userDataDir, { recursive: true, force: true });
}
});
test('gives a new user a blank slate and restores only that user local data after account switches', async ({ testServer }) => {
const suffix = uniqueName('isolation');
const userDataDir = await mkdtemp(join(tmpdir(), 'metoyou-auth-isolation-'));
const alice: TestUser = {
username: `alice_${suffix}`,
displayName: 'Alice',
password: 'TestPass123!'
};
const bob: TestUser = {
username: `bob_${suffix}`,
displayName: 'Bob',
password: 'TestPass123!'
};
const aliceServerName = `Alice Private Server ${suffix}`;
const bobServerName = `Bob Private Server ${suffix}`;
const aliceMessage = `Alice history ${suffix}`;
const bobMessage = `Bob history ${suffix}`;
let client: PersistentClient | null = null;
try {
client = await launchPersistentClient(userDataDir, testServer.port);
await test.step('Alice creates persisted local data and verifies it survives a restart', async () => {
await registerUser(client.page, alice);
await createServerAndSendMessage(client.page, aliceServerName, aliceMessage);
await restartPersistentClient(client, testServer.port);
await openApp(client.page);
await expectSavedRoomAndHistory(client.page, aliceServerName, aliceMessage);
});
await test.step('Bob starts from a blank slate in the same browser profile', async () => {
await logoutUser(client.page);
await registerUser(client.page, bob);
await expectBlankSlate(client.page, [aliceServerName]);
});
await test.step('Bob gets only his own saved room and history after a restart', async () => {
await createServerAndSendMessage(client.page, bobServerName, bobMessage);
await restartPersistentClient(client, testServer.port);
await openApp(client.page);
await expectSavedRoomAndHistory(client.page, bobServerName, bobMessage);
await expectSavedRoomHidden(client.page, aliceServerName);
});
await test.step('When Alice logs back in she sees only Alice local data, not Bob data', async () => {
await logoutUser(client.page);
await restartPersistentClient(client, testServer.port);
await loginUser(client.page, alice);
await expectSavedRoomVisible(client.page, aliceServerName);
await expectSavedRoomHidden(client.page, bobServerName);
await expectSavedRoomAndHistory(client.page, aliceServerName, aliceMessage);
});
} finally {
await closePersistentClient(client);
await rm(userDataDir, { recursive: true, force: true });
}
});
});
async function launchPersistentClient(userDataDir: string, testServerPort: number): Promise<PersistentClient> {
const context = await chromium.launchPersistentContext(userDataDir, {
args: CLIENT_LAUNCH_ARGS,
baseURL: 'http://localhost:4200',
permissions: ['microphone', 'camera']
});
await installTestServerEndpoint(context, testServerPort);
const page = context.pages()[0] ?? (await context.newPage());
return {
context,
page,
userDataDir
};
}
async function restartPersistentClient(client: PersistentClient, testServerPort: number): Promise<void> {
await client.context.close();
const restartedClient = await launchPersistentClient(client.userDataDir, testServerPort);
client.context = restartedClient.context;
client.page = restartedClient.page;
}
async function closePersistentClient(client: PersistentClient | null): Promise<void> {
if (!client) {
return;
}
await client.context.close().catch(() => {});
}
async function openApp(page: Page): Promise<void> {
await retryTransientNavigation(() => page.goto('/', { waitUntil: 'domcontentloaded' }));
}
async function registerUser(page: Page, user: TestUser): Promise<void> {
const registerPage = new RegisterPage(page);
await retryTransientNavigation(() => registerPage.goto());
await registerPage.register(user.username, user.displayName, user.password);
await expect(page).toHaveURL(/\/search/, { timeout: 15_000 });
}
async function loginUser(page: Page, user: TestUser): Promise<void> {
const loginPage = new LoginPage(page);
await retryTransientNavigation(() => loginPage.goto());
await loginPage.login(user.username, user.password);
await expect(page).toHaveURL(/\/(search|room)(\/|$)/, { timeout: 15_000 });
}
async function logoutUser(page: Page): Promise<void> {
const menuButton = page.getByRole('button', { name: 'Menu' });
const logoutButton = page.getByRole('button', { name: 'Logout' });
const loginPage = new LoginPage(page);
await expect(menuButton).toBeVisible({ timeout: 10_000 });
await menuButton.click();
await expect(logoutButton).toBeVisible({ timeout: 10_000 });
await logoutButton.click();
await expect(page).toHaveURL(/\/login/, { timeout: 15_000 });
await expect(loginPage.usernameInput).toBeVisible({ timeout: 10_000 });
}
async function createServerAndSendMessage(page: Page, serverName: string, messageText: string): Promise<void> {
const searchPage = new ServerSearchPage(page);
const messagesPage = new ChatMessagesPage(page);
await searchPage.createServer(serverName, {
description: `User session isolation coverage for ${serverName}`
});
await expect(page).toHaveURL(/\/room\//, { timeout: 15_000 });
await messagesPage.sendMessage(messageText);
await expect(messagesPage.getMessageItemByText(messageText)).toBeVisible({ timeout: 20_000 });
}
async function expectSavedRoomAndHistory(page: Page, roomName: string, messageText: string): Promise<void> {
const railRoomButton = getRailSavedRoomButton(page, roomName);
const messagesPage = new ChatMessagesPage(page);
await expect(railRoomButton).toBeVisible({ timeout: 20_000 });
await page.goto('/search', { waitUntil: 'domcontentloaded' });
const searchRoomButton = getSearchSavedRoomButton(page, roomName);
await expect(searchRoomButton).toBeVisible({ timeout: 20_000 });
await searchRoomButton.click();
await expect(page).toHaveURL(/\/room\//, { timeout: 20_000 });
await expect(messagesPage.getMessageItemByText(messageText)).toBeVisible({ timeout: 20_000 });
}
async function expectBlankSlate(page: Page, hiddenRoomNames: string[]): Promise<void> {
const searchPage = new ServerSearchPage(page);
await expect(page).toHaveURL(/\/search/, { timeout: 15_000 });
await expect(searchPage.createServerButton).toBeVisible({ timeout: 15_000 });
for (const roomName of hiddenRoomNames) {
await expectSavedRoomHidden(page, roomName);
}
}
async function expectSavedRoomVisible(page: Page, roomName: string): Promise<void> {
await expect(getRailSavedRoomButton(page, roomName)).toBeVisible({ timeout: 20_000 });
await page.goto('/search', { waitUntil: 'domcontentloaded' });
await expect(getSearchSavedRoomButton(page, roomName)).toBeVisible({ timeout: 20_000 });
}
async function expectSavedRoomHidden(page: Page, roomName: string): Promise<void> {
await expect(getRailSavedRoomButton(page, roomName)).toHaveCount(0);
if (!page.url().includes('/search')) {
await page.goto('/search', { waitUntil: 'domcontentloaded' });
}
await expect(getSearchSavedRoomButton(page, roomName)).toHaveCount(0);
}
function getRailSavedRoomButton(page: Page, roomName: string) {
return page.locator(`button[title="${roomName}"]`).first();
}
function getSearchSavedRoomButton(page: Page, roomName: string) {
return page.locator('app-server-search').getByRole('button', { name: roomName, exact: true });
}
async function retryTransientNavigation<T>(navigate: () => Promise<T>, attempts = 4): Promise<T> {
let lastError: unknown;
for (let attempt = 1; attempt <= attempts; attempt += 1) {
try {
return await navigate();
} catch (error) {
lastError = error;
const message = error instanceof Error ? error.message : String(error);
const isTransientNavigationError = message.includes('ERR_EMPTY_RESPONSE') || message.includes('ERR_CONNECTION_RESET');
if (!isTransientNavigationError || attempt === attempts) {
throw error;
}
}
}
throw lastError instanceof Error ? lastError : new Error(`Navigation failed after ${attempts} attempts`);
}
function uniqueName(prefix: string): string {
return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36)
.slice(2, 8)}`;
}

View File

@@ -18,6 +18,85 @@ const DELETED_MESSAGE_CONTENT = '[Message deleted]';
test.describe('Chat messaging features', () => { test.describe('Chat messaging features', () => {
test.describe.configure({ timeout: 180_000 }); test.describe.configure({ timeout: 180_000 });
test('shows per-server channel lists on first saved-server click', async ({ createClient }) => {
const scenario = await createSingleClientChatScenario(createClient);
const alphaServerName = `Alpha Server ${uniqueName('rail')}`;
const betaServerName = `Beta Server ${uniqueName('rail')}`;
const alphaChannelName = uniqueName('alpha-updates');
const betaChannelName = uniqueName('beta-plans');
const channelsPanel = scenario.room.channelsSidePanel;
await test.step('Create first saved server with a unique text channel', async () => {
await createServerAndOpenRoom(scenario.search, scenario.client.page, alphaServerName, 'Rail switch alpha server');
await scenario.room.ensureTextChannelExists(alphaChannelName);
await expect(
channelsPanel.locator(`button[data-channel-type="text"][data-channel-name="${alphaChannelName}"]`)
).toBeVisible({ timeout: 20_000 });
});
await test.step('Create second saved server with a different text channel', async () => {
await createServerAndOpenRoom(scenario.search, scenario.client.page, betaServerName, 'Rail switch beta server');
await scenario.room.ensureTextChannelExists(betaChannelName);
await expect(
channelsPanel.locator(`button[data-channel-type="text"][data-channel-name="${betaChannelName}"]`)
).toBeVisible({ timeout: 20_000 });
});
await test.step('Opening first server once restores only its channels', async () => {
await openSavedRoomByName(scenario.client.page, alphaServerName);
await expect(
channelsPanel.locator(`button[data-channel-type="text"][data-channel-name="${alphaChannelName}"]`)
).toBeVisible({ timeout: 20_000 });
await expect(
channelsPanel.locator(`button[data-channel-type="text"][data-channel-name="${betaChannelName}"]`)
).toHaveCount(0);
});
await test.step('Opening second server once restores only its channels', async () => {
await openSavedRoomByName(scenario.client.page, betaServerName);
await expect(
channelsPanel.locator(`button[data-channel-type="text"][data-channel-name="${betaChannelName}"]`)
).toBeVisible({ timeout: 20_000 });
await expect(
channelsPanel.locator(`button[data-channel-type="text"][data-channel-name="${alphaChannelName}"]`)
).toHaveCount(0);
});
});
test('shows local room history on first saved-server click', async ({ createClient }) => {
const scenario = await createSingleClientChatScenario(createClient);
const alphaServerName = `History Alpha ${uniqueName('rail')}`;
const betaServerName = `History Beta ${uniqueName('rail')}`;
const alphaMessage = `Alpha history message ${uniqueName('msg')}`;
const betaMessage = `Beta history message ${uniqueName('msg')}`;
await test.step('Create first server and send a local message', async () => {
await createServerAndOpenRoom(scenario.search, scenario.client.page, alphaServerName, 'Rail history alpha server');
await scenario.messages.sendMessage(alphaMessage);
await expect(scenario.messages.getMessageItemByText(alphaMessage)).toBeVisible({ timeout: 20_000 });
});
await test.step('Create second server and send a different local message', async () => {
await createServerAndOpenRoom(scenario.search, scenario.client.page, betaServerName, 'Rail history beta server');
await scenario.messages.sendMessage(betaMessage);
await expect(scenario.messages.getMessageItemByText(betaMessage)).toBeVisible({ timeout: 20_000 });
});
await test.step('Opening first server once restores its history immediately', async () => {
await openSavedRoomByName(scenario.client.page, alphaServerName);
await expect(scenario.messages.getMessageItemByText(alphaMessage)).toBeVisible({ timeout: 20_000 });
});
await test.step('Opening second server once restores its history immediately', async () => {
await openSavedRoomByName(scenario.client.page, betaServerName);
await expect(scenario.messages.getMessageItemByText(betaMessage)).toBeVisible({ timeout: 20_000 });
});
});
test('syncs messages in a newly created text channel', async ({ createClient }) => { test('syncs messages in a newly created text channel', async ({ createClient }) => {
const scenario = await createChatScenario(createClient); const scenario = await createChatScenario(createClient);
const channelName = uniqueName('updates'); const channelName = uniqueName('updates');
@@ -143,6 +222,43 @@ interface ChatScenario {
bobMessages: ChatMessagesPage; bobMessages: ChatMessagesPage;
} }
interface SingleClientChatScenario {
client: Client;
messages: ChatMessagesPage;
room: ChatRoomPage;
search: ServerSearchPage;
}
async function createSingleClientChatScenario(createClient: () => Promise<Client>): Promise<SingleClientChatScenario> {
const suffix = uniqueName('solo');
const client = await createClient();
const credentials = {
username: `solo_${suffix}`,
displayName: 'Solo',
password: 'TestPass123!'
};
await installChatFeatureMocks(client.page);
const registerPage = new RegisterPage(client.page);
await registerPage.goto();
await registerPage.register(
credentials.username,
credentials.displayName,
credentials.password
);
await expect(client.page).toHaveURL(/\/search/, { timeout: 15_000 });
return {
client,
messages: new ChatMessagesPage(client.page),
room: new ChatRoomPage(client.page),
search: new ServerSearchPage(client.page)
};
}
async function createChatScenario(createClient: () => Promise<Client>): Promise<ChatScenario> { async function createChatScenario(createClient: () => Promise<Client>): Promise<ChatScenario> {
const suffix = uniqueName('chat'); const suffix = uniqueName('chat');
const serverName = `Chat Server ${suffix}`; const serverName = `Chat Server ${suffix}`;
@@ -192,11 +308,8 @@ async function createChatScenario(createClient: () => Promise<Client>): Promise<
await expect(alice.page).toHaveURL(/\/room\//, { timeout: 15_000 }); await expect(alice.page).toHaveURL(/\/room\//, { timeout: 15_000 });
const bobSearchPage = new ServerSearchPage(bob.page); const bobSearchPage = new ServerSearchPage(bob.page);
const serverCard = bob.page.locator('button', { hasText: serverName }).first();
await bobSearchPage.searchInput.fill(serverName); await bobSearchPage.joinServerFromSearch(serverName);
await expect(serverCard).toBeVisible({ timeout: 15_000 });
await serverCard.click();
await expect(bob.page).toHaveURL(/\/room\//, { timeout: 15_000 }); await expect(bob.page).toHaveURL(/\/room\//, { timeout: 15_000 });
const aliceRoom = new ChatRoomPage(alice.page); const aliceRoom = new ChatRoomPage(alice.page);
@@ -217,6 +330,52 @@ async function createChatScenario(createClient: () => Promise<Client>): Promise<
}; };
} }
async function createServerAndOpenRoom(
searchPage: ServerSearchPage,
page: Page,
serverName: string,
description: string
): Promise<void> {
await searchPage.createServer(serverName, { description });
await expect(page).toHaveURL(/\/room\//, { timeout: 15_000 });
await waitForCurrentRoomName(page, serverName);
}
async function openSavedRoomByName(page: Page, roomName: string): Promise<void> {
const roomButton = page.locator(`button[title="${roomName}"]`);
await expect(roomButton).toBeVisible({ timeout: 20_000 });
await roomButton.click();
await expect(page).toHaveURL(/\/room\//, { timeout: 20_000 });
await expect(page.locator('app-rooms-side-panel').first()).toBeVisible({ timeout: 20_000 });
await waitForCurrentRoomName(page, roomName);
}
async function waitForCurrentRoomName(page: Page, roomName: string, timeout = 20_000): Promise<void> {
await page.waitForFunction(
(expectedRoomName) => {
interface RoomShape { name?: string }
interface AngularDebugApi {
getComponent: (element: Element) => Record<string, unknown>;
}
const host = document.querySelector('app-rooms-side-panel');
const debugApi = (window as { ng?: AngularDebugApi }).ng;
if (!host || !debugApi?.getComponent) {
return false;
}
const component = debugApi.getComponent(host);
const currentRoom = (component['currentRoom'] as (() => RoomShape | null) | undefined)?.() ?? null;
return currentRoom?.name === expectedRoomName;
},
roomName,
{ timeout }
);
}
async function installChatFeatureMocks(page: Page): Promise<void> { async function installChatFeatureMocks(page: Page): Promise<void> {
await page.route('**/api/klipy/config', async (route) => { await page.route('**/api/klipy/config', async (route) => {
await route.fulfill({ await route.fulfill({

View File

@@ -0,0 +1,116 @@
import { type Page } from '@playwright/test';
import {
test,
expect,
type Client
} from '../../fixtures/multi-client';
import { RegisterPage } from '../../pages/register.page';
import { ServerSearchPage } from '../../pages/server-search.page';
import { ChatMessagesPage } from '../../pages/chat-messages.page';
import { disableLastViewedChatResume } from '../../helpers/seed-test-endpoint';
test.describe('Direct message flow', () => {
test.describe.configure({ timeout: 180_000 });
test('opens a DM from a user card and queues messages while offline', async ({ createClient }) => {
const scenario = await createDmScenario(createClient);
const offlineMessage = `Offline DM ${uniqueName('msg')}`;
await test.step('Alice opens Bob from the room user list', async () => {
const bobUserCard = scenario.alice.page.locator('[data-testid^="room-user-card-"]', { hasText: 'Bob' }).first();
await expect(bobUserCard).toBeVisible({ timeout: 20_000 });
await bobUserCard.getByRole('button', { name: 'Message Bob' }).click();
await expect(scenario.alice.page).toHaveURL(/\/dm\//, { timeout: 15_000 });
await expect(scenario.alice.page.getByRole('heading', { name: 'Bob' })).toBeVisible({ timeout: 10_000 });
});
await test.step('Offline send persists locally as queued', async () => {
await scenario.alice.page.evaluate(() => window.simulateOffline?.());
await scenario.alice.page.getByTestId('dm-input').fill(offlineMessage);
await scenario.alice.page.getByTestId('dm-input').press('Enter');
await expect(scenario.alice.page.locator('app-dm-chat').getByText(offlineMessage)).toBeVisible({ timeout: 10_000 });
await expect(scenario.alice.page.getByTestId('message-status').last()).toContainText('QUEUED');
});
});
test('shows friend and message actions on the search people list', async ({ createClient }) => {
const scenario = await createDmScenario(createClient);
await disableLastViewedChatResume(scenario.alice.page);
await scenario.alice.page.goto('/search', { waitUntil: 'domcontentloaded' });
await expect(scenario.alice.page).toHaveURL(/\/search/, { timeout: 20_000 });
await expect(scenario.alice.page.locator('app-server-search')).toBeVisible({ timeout: 20_000 });
await expect(scenario.alice.page.locator('app-user-search-list')).toBeVisible({ timeout: 20_000 });
const bobPeopleCard = scenario.alice.page
.locator('app-user-search-list [data-testid$="-' + scenario.bobUserId + '"]', { hasText: 'Bob' })
.first();
await expect(bobPeopleCard).toBeVisible({ timeout: 15_000 });
const friendButton = bobPeopleCard.locator(`[data-testid="friend-button-${scenario.bobUserId}"]`);
const messageButton = bobPeopleCard.getByRole('button', { name: 'Message Bob' });
await expect(friendButton).toBeAttached({ timeout: 15_000 });
await expect(messageButton).toBeAttached({ timeout: 15_000 });
});
});
interface DmScenario {
alice: Client;
bob: Client;
bobUserId: string;
aliceSearch: ServerSearchPage;
}
async function createDmScenario(createClient: () => Promise<Client>): Promise<DmScenario> {
const suffix = uniqueName('dm');
const serverName = `DM Server ${suffix}`;
const alice = await createClient();
const bob = await createClient();
await registerUser(alice.page, `alice_${suffix}`, 'Alice');
await registerUser(bob.page, `bob_${suffix}`, 'Bob');
const aliceSearch = new ServerSearchPage(alice.page);
await aliceSearch.createServer(serverName, { description: 'E2E direct message discovery server' });
await expect(alice.page).toHaveURL(/\/room\//, { timeout: 15_000 });
await new ChatMessagesPage(alice.page).waitForReady();
const bobSearch = new ServerSearchPage(bob.page);
await bobSearch.joinServerFromSearch(serverName);
await expect(bob.page).toHaveURL(/\/room\//, { timeout: 15_000 });
await new ChatMessagesPage(bob.page).waitForReady();
const bobRoomCard = alice.page.locator('[data-testid^="room-user-card-"]', { hasText: 'Bob' }).first();
await expect(bobRoomCard).toBeVisible({ timeout: 20_000 });
const bobUserCardTestId = await bobRoomCard.getAttribute('data-testid');
const bobUserId = bobUserCardTestId?.replace('room-user-card-', '');
if (!bobUserId) {
throw new Error('Expected Bob room user card to expose a stable test id.');
}
return {
alice,
bob,
bobUserId,
aliceSearch
};
}
async function registerUser(page: Page, username: string, displayName: string): Promise<void> {
const registerPage = new RegisterPage(page);
await registerPage.goto();
await registerPage.register(username, displayName, 'TestPass123!');
await expect(page).toHaveURL(/\/search/, { timeout: 15_000 });
}
function uniqueName(prefix: string): string {
return `${prefix}-${Date.now()}-${Math.random().toString(36)
.slice(2, 8)}`;
}

View File

@@ -0,0 +1,260 @@
import {
expect,
type Locator,
type Page
} from '@playwright/test';
import { test, type Client } from '../../fixtures/multi-client';
import { RegisterPage } from '../../pages/register.page';
import { ServerSearchPage } from '../../pages/server-search.page';
import { ChatRoomPage } from '../../pages/chat-room.page';
import { ChatMessagesPage } from '../../pages/chat-messages.page';
interface DesktopNotificationRecord {
title: string;
body: string;
}
interface NotificationScenario {
alice: Client;
bob: Client;
aliceRoom: ChatRoomPage;
bobRoom: ChatRoomPage;
bobMessages: ChatMessagesPage;
serverName: string;
channelName: string;
}
test.describe('Chat notifications', () => {
test.describe.configure({ timeout: 180_000 });
test('shows desktop notifications and unread badges for inactive channels', async ({ createClient }) => {
const scenario = await createNotificationScenario(createClient);
const message = `Background notification ${uniqueName('msg')}`;
await test.step('Bob sends a message to Alice\'s inactive channel', async () => {
await clearDesktopNotifications(scenario.alice.page);
await scenario.bobRoom.joinTextChannel(scenario.channelName);
await scenario.bobMessages.sendMessage(message);
});
await test.step('Alice receives a desktop notification with the channel preview', async () => {
const notification = await waitForDesktopNotification(scenario.alice.page);
expect(notification).toEqual({
title: `${scenario.serverName} · #${scenario.channelName}`,
body: `Bob: ${message}`
});
});
await test.step('Alice sees unread badges for the room and the inactive channel', async () => {
await expect(getUnreadBadge(getSavedRoomButton(scenario.alice.page, scenario.serverName))).toHaveText('1', { timeout: 20_000 });
await expect(getUnreadBadge(getTextChannelButton(scenario.alice.page, scenario.channelName))).toHaveText('1', { timeout: 20_000 });
});
});
test('keeps unread badges visible when a muted channel suppresses desktop popups', async ({ createClient }) => {
const scenario = await createNotificationScenario(createClient);
const message = `Muted notification ${uniqueName('msg')}`;
await test.step('Alice mutes the inactive text channel', async () => {
await muteTextChannel(scenario.alice.page, scenario.channelName);
await clearDesktopNotifications(scenario.alice.page);
});
await test.step('Bob sends a message into the muted channel', async () => {
await scenario.bobRoom.joinTextChannel(scenario.channelName);
await scenario.bobMessages.sendMessage(message);
});
await test.step('Alice still sees unread badges for the room and channel', async () => {
await expect(getUnreadBadge(getSavedRoomButton(scenario.alice.page, scenario.serverName))).toHaveText('1', { timeout: 20_000 });
await expect(getUnreadBadge(getTextChannelButton(scenario.alice.page, scenario.channelName))).toHaveText('1', { timeout: 20_000 });
});
await test.step('Alice does not get a muted desktop popup', async () => {
const notificationAppeared = await waitForAnyDesktopNotification(scenario.alice.page, 1_500);
expect(notificationAppeared).toBe(false);
});
});
});
async function createNotificationScenario(createClient: () => Promise<Client>): Promise<NotificationScenario> {
const suffix = uniqueName('notify');
const serverName = `Notifications Server ${suffix}`;
const channelName = uniqueName('updates');
const aliceCredentials = {
username: `alice_${suffix}`,
displayName: 'Alice',
password: 'TestPass123!'
};
const bobCredentials = {
username: `bob_${suffix}`,
displayName: 'Bob',
password: 'TestPass123!'
};
const alice = await createClient();
const bob = await createClient();
await installDesktopNotificationSpy(alice.page);
await registerUser(alice.page, aliceCredentials.username, aliceCredentials.displayName, aliceCredentials.password);
await registerUser(bob.page, bobCredentials.username, bobCredentials.displayName, bobCredentials.password);
const aliceSearch = new ServerSearchPage(alice.page);
await aliceSearch.createServer(serverName, {
description: 'E2E notification coverage server'
});
await expect(alice.page).toHaveURL(/\/room\//, { timeout: 15_000 });
const bobSearch = new ServerSearchPage(bob.page);
await bobSearch.joinServerFromSearch(serverName);
await expect(bob.page).toHaveURL(/\/room\//, { timeout: 15_000 });
const aliceRoom = new ChatRoomPage(alice.page);
const bobRoom = new ChatRoomPage(bob.page);
const aliceMessages = new ChatMessagesPage(alice.page);
const bobMessages = new ChatMessagesPage(bob.page);
await aliceMessages.waitForReady();
await bobMessages.waitForReady();
await aliceRoom.ensureTextChannelExists(channelName);
await expect(getTextChannelButton(alice.page, channelName)).toBeVisible({ timeout: 20_000 });
return {
alice,
bob,
aliceRoom,
bobRoom,
bobMessages,
serverName,
channelName
};
}
async function registerUser(page: Page, username: string, displayName: string, password: string): Promise<void> {
const registerPage = new RegisterPage(page);
await registerPage.goto();
await registerPage.register(username, displayName, password);
await expect(page).toHaveURL(/\/search/, { timeout: 15_000 });
}
async function installDesktopNotificationSpy(page: Page): Promise<void> {
await page.addInitScript(() => {
const notifications: DesktopNotificationRecord[] = [];
class MockNotification {
static permission = 'granted';
onclick: (() => void) | null = null;
constructor(title: string, options?: NotificationOptions) {
notifications.push({
title,
body: options?.body ?? ''
});
}
static async requestPermission(): Promise<NotificationPermission> {
return 'granted';
}
close(): void {
return;
}
}
Object.defineProperty(window, '__desktopNotifications', {
value: notifications,
configurable: true
});
Object.defineProperty(window, 'Notification', {
value: MockNotification,
configurable: true,
writable: true
});
});
}
async function clearDesktopNotifications(page: Page): Promise<void> {
await page.evaluate(() => {
(window as WindowWithDesktopNotifications).__desktopNotifications.length = 0;
});
}
async function waitForDesktopNotification(page: Page): Promise<DesktopNotificationRecord> {
await expect.poll(
async () => (await readDesktopNotifications(page)).length,
{
timeout: 20_000,
message: 'Expected a desktop notification to be emitted'
}
).toBeGreaterThan(0);
const notifications = await readDesktopNotifications(page);
return notifications[notifications.length - 1];
}
async function waitForAnyDesktopNotification(page: Page, timeout: number): Promise<boolean> {
try {
await page.waitForFunction(
() => (window as WindowWithDesktopNotifications).__desktopNotifications.length > 0,
undefined,
{ timeout }
);
return true;
} catch (error) {
if (error instanceof Error && error.name === 'TimeoutError') {
return false;
}
throw error;
}
}
async function readDesktopNotifications(page: Page): Promise<DesktopNotificationRecord[]> {
return page.evaluate(() => {
return [...(window as WindowWithDesktopNotifications).__desktopNotifications];
});
}
async function muteTextChannel(page: Page, channelName: string): Promise<void> {
const channelButton = getTextChannelButton(page, channelName);
const contextMenu = page.locator('app-context-menu');
await expect(channelButton).toBeVisible({ timeout: 20_000 });
await channelButton.click({ button: 'right' });
await expect(contextMenu.getByRole('button', { name: 'Mute Notifications' })).toBeVisible({ timeout: 10_000 });
await contextMenu.getByRole('button', { name: 'Mute Notifications' }).click();
await expect(contextMenu).toHaveCount(0);
}
function getSavedRoomButton(page: Page, roomName: string): Locator {
return page.locator(`button[title="${roomName}"]`).first();
}
function getTextChannelButton(page: Page, channelName: string): Locator {
return page.locator('app-rooms-side-panel').first()
.locator(`button[data-channel-type="text"][data-channel-name="${channelName}"]`)
.first();
}
function getUnreadBadge(container: Locator): Locator {
return container.locator('span.rounded-full').first();
}
function uniqueName(prefix: string): string {
return `${prefix}-${Date.now()}-${Math.random().toString(36)
.slice(2, 8)}`;
}
interface WindowWithDesktopNotifications extends Window {
__desktopNotifications: DesktopNotificationRecord[];
}

View File

@@ -69,6 +69,7 @@ const NETSCAPE_LOOP_EXTENSION = Buffer.from([
]); ]);
const CLIENT_LAUNCH_ARGS = ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream']; const CLIENT_LAUNCH_ARGS = ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream'];
const VOICE_CHANNEL = 'General'; const VOICE_CHANNEL = 'General';
const AVATAR_SYNC_TIMEOUT_MS = 45_000;
test.describe('Profile avatar sync', () => { test.describe('Profile avatar sync', () => {
test.describe.configure({ timeout: 240_000 }); test.describe.configure({ timeout: 240_000 });
@@ -384,11 +385,8 @@ async function registerUser(client: PersistentClient): Promise<void> {
async function joinServerFromSearch(page: Page, serverName: string): Promise<void> { async function joinServerFromSearch(page: Page, serverName: string): Promise<void> {
const searchPage = new ServerSearchPage(page); const searchPage = new ServerSearchPage(page);
const serverCard = page.locator('button', { hasText: serverName }).first();
await searchPage.searchInput.fill(serverName); await searchPage.joinServerFromSearch(serverName);
await expect(serverCard).toBeVisible({ timeout: 15_000 });
await serverCard.click();
await expect(page).toHaveURL(/\/room\//, { timeout: 15_000 }); await expect(page).toHaveURL(/\/room\//, { timeout: 15_000 });
} }
@@ -601,7 +599,7 @@ async function expectSidebarAvatar(page: Page, displayName: string, expectedData
return image.getAttribute('src'); return image.getAttribute('src');
}, { }, {
timeout: 20_000, timeout: AVATAR_SYNC_TIMEOUT_MS,
message: `${displayName} avatar src should update` message: `${displayName} avatar src should update`
}).toBe(expectedDataUrl); }).toBe(expectedDataUrl);
@@ -618,7 +616,7 @@ async function expectSidebarAvatar(page: Page, displayName: string, expectedData
return img.complete && img.naturalWidth > 0 && img.naturalHeight > 0; return img.complete && img.naturalWidth > 0 && img.naturalHeight > 0;
}); });
}, { }, {
timeout: 20_000, timeout: AVATAR_SYNC_TIMEOUT_MS,
message: `${displayName} avatar image should load` message: `${displayName} avatar image should load`
}).toBe(true); }).toBe(true);
} }
@@ -638,7 +636,7 @@ async function expectChatMessageAvatar(page: Page, messageText: string, expected
return image.getAttribute('src'); return image.getAttribute('src');
}, { }, {
timeout: 20_000, timeout: AVATAR_SYNC_TIMEOUT_MS,
message: `Chat message avatar for "${messageText}" should update` message: `Chat message avatar for "${messageText}" should update`
}).toBe(expectedDataUrl); }).toBe(expectedDataUrl);
} }
@@ -665,7 +663,7 @@ async function expectVoiceControlsAvatar(page: Page, expectedDataUrl: string): P
return image.getAttribute('src'); return image.getAttribute('src');
}, { }, {
timeout: 20_000, timeout: AVATAR_SYNC_TIMEOUT_MS,
message: 'Voice controls avatar should update' message: 'Voice controls avatar should update'
}).toBe(expectedDataUrl); }).toBe(expectedDataUrl);
} }

View File

@@ -0,0 +1,503 @@
import { mkdtemp, rm } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import {
chromium,
type BrowserContext,
type Locator,
type Page,
type Route
} from '@playwright/test';
import { test, expect } from '../../fixtures/multi-client';
import { installTestServerEndpoint } from '../../helpers/seed-test-endpoint';
import { installWebRTCTracking } from '../../helpers/webrtc-helpers';
import { LoginPage } from '../../pages/login.page';
import { RegisterPage } from '../../pages/register.page';
import { ServerSearchPage } from '../../pages/server-search.page';
import { ChatMessagesPage } from '../../pages/chat-messages.page';
interface TestUser {
displayName: string;
password: string;
username: string;
}
interface ImageUploadPayload {
buffer: Buffer;
dataUrl: string;
mimeType: string;
name: string;
}
interface PersistentClient {
context: BrowserContext;
page: Page;
user: TestUser;
userDataDir: string;
}
const STATIC_GIF_BASE64 = 'R0lGODlhAQABAPAAAP///wAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw==';
const GIF_FRAME_MARKER = Buffer.from([
0x21,
0xf9,
0x04
]);
const CLIENT_LAUNCH_ARGS = ['--use-fake-device-for-media-stream', '--use-fake-ui-for-media-stream'];
const SERVER_ICON_SYNC_TIMEOUT_MS = 45_000;
test.describe('Server icon sync', () => {
test.describe.configure({ timeout: 240_000 });
test('loads the chat-server image for online, late-joining, restarted, and discovery users', async ({ testServer }) => {
const suffix = uniqueName('server-icon');
const serverName = `Icon Sync Server ${suffix}`;
const icon = buildGifUpload('server-icon');
const aliceUser: TestUser = {
username: `alice_${suffix}`,
displayName: 'Alice',
password: 'TestPass123!'
};
const bobUser: TestUser = {
username: `bob_${suffix}`,
displayName: 'Bob',
password: 'TestPass123!'
};
const carolUser: TestUser = {
username: `carol_${suffix}`,
displayName: 'Carol',
password: 'TestPass123!'
};
const daveUser: TestUser = {
username: `dave_${suffix}`,
displayName: 'Dave',
password: 'TestPass123!'
};
const clients: PersistentClient[] = [];
try {
const alice = await createPersistentClient(aliceUser, testServer.port);
const bob = await createPersistentClient(bobUser, testServer.port);
clients.push(alice, bob);
await test.step('Alice creates a server and Bob joins before the icon changes', async () => {
await registerUser(alice);
await registerUser(bob);
await new ServerSearchPage(alice.page).createServer(serverName, {
description: 'Server icon synchronization E2E coverage'
});
await expect(alice.page).toHaveURL(/\/room\//, { timeout: 15_000 });
await joinServerFromSearch(bob.page, serverName);
await waitForRoomReady(alice.page);
await waitForRoomReady(bob.page);
await waitForConnectedPeerCount(alice.page, 1);
await waitForConnectedPeerCount(bob.page, 1);
});
const roomUrl = alice.page.url();
await test.step('Alice uploads a server icon and sees it in every owner-facing place', async () => {
await uploadServerIconFromSettings(alice.page, serverName, icon);
await expectServerSettingsIcon(alice.page, serverName, icon.dataUrl);
await closeSettingsModal(alice.page);
await expectRoomHeaderIcon(alice.page, serverName, icon.dataUrl);
await expectRailIcon(alice.page, serverName, icon.dataUrl);
});
await test.step('Bob was online during the change and receives the icon live', async () => {
await expectRoomHeaderIcon(bob.page, serverName, icon.dataUrl);
await expectRailIcon(bob.page, serverName, icon.dataUrl);
});
const carol = await createPersistentClient(carolUser, testServer.port);
clients.push(carol);
await test.step('Carol joins after the change and loads the existing server icon', async () => {
await registerUser(carol);
await joinServerFromSearch(carol.page, serverName);
await waitForRoomReady(carol.page);
await waitForConnectedPeerCount(alice.page, 2);
await expectRoomHeaderIcon(carol.page, serverName, icon.dataUrl);
await expectRailIcon(carol.page, serverName, icon.dataUrl);
});
await test.step('Bob keeps the server icon after a full app restart', async () => {
await restartPersistentClient(bob, testServer.port);
await openRoomAfterRestart(bob, roomUrl);
await expectRoomHeaderIcon(bob.page, serverName, icon.dataUrl);
await expectRailIcon(bob.page, serverName, icon.dataUrl);
});
const dave = await createPersistentClient(daveUser, testServer.port);
clients.push(dave);
await test.step('Dave has not joined, but discovery loads the icon through a temporary peer sync', async () => {
await registerUser(dave);
await stripServerIconFromDirectorySearch(dave.page, serverName);
await dave.page.goto('/search', { waitUntil: 'domcontentloaded' });
await new ServerSearchPage(dave.page).searchInput.fill(serverName);
await expectSearchResultIcon(dave.page, serverName, icon.dataUrl);
await expect(dave.page).toHaveURL(/\/search/);
});
} finally {
await Promise.all(
clients.map(async (client) => {
await closePersistentClient(client);
await rm(client.userDataDir, { recursive: true, force: true });
})
);
}
});
});
async function createPersistentClient(user: TestUser, testServerPort: number): Promise<PersistentClient> {
const userDataDir = await mkdtemp(join(tmpdir(), 'metoyou-server-icon-e2e-'));
const session = await launchPersistentSession(userDataDir, testServerPort);
return {
context: session.context,
page: session.page,
user,
userDataDir
};
}
async function restartPersistentClient(client: PersistentClient, testServerPort: number): Promise<void> {
await closePersistentClient(client);
const session = await launchPersistentSession(client.userDataDir, testServerPort);
client.context = session.context;
client.page = session.page;
}
async function closePersistentClient(client: PersistentClient): Promise<void> {
try {
await client.context.close();
} catch {
// Ignore repeated cleanup attempts during finally.
}
}
async function launchPersistentSession(userDataDir: string, testServerPort: number): Promise<{ context: BrowserContext; page: Page }> {
const context = await chromium.launchPersistentContext(userDataDir, {
args: CLIENT_LAUNCH_ARGS,
baseURL: 'http://localhost:4200',
permissions: ['microphone', 'camera']
});
await installTestServerEndpoint(context, testServerPort);
const page = context.pages()[0] ?? (await context.newPage());
await installWebRTCTracking(page);
return { context, page };
}
async function registerUser(client: PersistentClient): Promise<void> {
const registerPage = new RegisterPage(client.page);
await retryTransientNavigation(() => registerPage.goto());
await registerPage.register(client.user.username, client.user.displayName, client.user.password);
await expect(client.page).toHaveURL(/\/search/, { timeout: 15_000 });
}
async function joinServerFromSearch(page: Page, serverName: string): Promise<void> {
await new ServerSearchPage(page).joinServerFromSearch(serverName);
await expect(page).toHaveURL(/\/room\//, { timeout: 15_000 });
}
async function openRoomAfterRestart(client: PersistentClient, roomUrl: string): Promise<void> {
await retryTransientNavigation(() => client.page.goto(roomUrl, { waitUntil: 'domcontentloaded' }));
if (client.page.url().includes('/login')) {
const loginPage = new LoginPage(client.page);
await loginPage.login(client.user.username, client.user.password);
await expect(client.page).toHaveURL(/\/(search|room)\//, { timeout: 15_000 });
await client.page.goto(roomUrl, { waitUntil: 'domcontentloaded' });
}
await waitForRoomReady(client.page);
}
async function uploadServerIconFromSettings(page: Page, serverName: string, icon: ImageUploadPayload): Promise<void> {
await openServerSettings(page, serverName);
const fileInput = page.locator('#server-icon-upload');
await expect(fileInput).toBeAttached({ timeout: 10_000 });
await fileInput.setInputFiles({
name: icon.name,
mimeType: icon.mimeType,
buffer: icon.buffer
});
}
async function openServerSettings(page: Page, serverName: string): Promise<void> {
await page.locator('app-title-bar button[title="Menu"]').click();
const titleBarMenu = page.locator('app-title-bar .absolute.right-0.top-full').first();
await expect(titleBarMenu).toBeVisible({ timeout: 5_000 });
await titleBarMenu.getByRole('button', { name: 'Settings' }).click();
const dialog = page.locator('app-settings-modal');
const serverSettingsTitle = dialog.getByRole('heading', { name: 'Server Settings' });
try {
await expect(serverSettingsTitle).toBeVisible({ timeout: 2_000 });
} catch {
await openSettingsModalThroughAngularDevMode(page);
await expect(serverSettingsTitle).toBeVisible({ timeout: 10_000 });
}
const serverSelect = dialog.locator('select').first();
if ((await serverSelect.count()) > 0) {
await expect(serverSelect).toContainText(serverName, { timeout: 10_000 });
}
await dialog.getByRole('button', { name: 'Server', exact: true }).click();
await expect(page.locator('app-server-settings')).toBeVisible({ timeout: 10_000 });
}
async function openSettingsModalThroughAngularDevMode(page: Page): Promise<void> {
await page.evaluate(() => {
interface SettingsModalComponentHandle {
modal?: {
open: (page: string) => void;
};
}
interface AngularDebugApi {
getComponent: (element: Element) => SettingsModalComponentHandle;
applyChanges?: (component: SettingsModalComponentHandle) => void;
}
const host = document.querySelector('app-settings-modal');
const debugApi = (window as Window & { ng?: AngularDebugApi }).ng;
const component = host && debugApi?.getComponent(host);
if (!component?.modal?.open) {
throw new Error('Angular debug API could not open settings modal');
}
component.modal.open('server');
debugApi.applyChanges?.(component);
});
}
async function closeSettingsModal(page: Page): Promise<void> {
await page.keyboard.press('Escape');
await expect(page.locator('app-settings-modal').getByRole('heading', { name: 'Settings', exact: true })).not.toBeVisible({ timeout: 10_000 });
}
async function stripServerIconFromDirectorySearch(page: Page, serverName: string): Promise<void> {
await page.route('**/api/servers**', async (route: Route) => {
const response = await route.fetch();
const contentType = response.headers()['content-type'] ?? '';
if (!contentType.includes('application/json')) {
await route.fulfill({ response });
return;
}
const body = await response.json();
if (!body || !Array.isArray(body.servers)) {
await route.fulfill({ response, json: body });
return;
}
await route.fulfill({
response,
json: {
...body,
servers: body.servers.map((server: Record<string, unknown>) => {
if (server['name'] !== serverName) {
return server;
}
const { icon: _icon, ...serverWithoutIcon } = server;
return serverWithoutIcon;
})
}
});
});
}
async function waitForRoomReady(page: Page): Promise<void> {
const messagesPage = new ChatMessagesPage(page);
await messagesPage.waitForReady();
await expect(page.locator('app-rooms-side-panel').last()).toBeVisible({ timeout: 15_000 });
}
async function waitForConnectedPeerCount(page: Page, count: number, timeout = 30_000): Promise<void> {
await page.waitForFunction(
(expectedCount) => {
const connections =
(
window as {
__rtcConnections?: RTCPeerConnection[];
}
).__rtcConnections ?? [];
return connections.filter((connection) => connection.connectionState === 'connected').length >= expectedCount;
},
count,
{ timeout }
);
}
async function retryTransientNavigation<T>(navigate: () => Promise<T>, attempts = 4): Promise<T> {
let lastError: unknown;
for (let attempt = 1; attempt <= attempts; attempt++) {
try {
return await navigate();
} catch (error) {
lastError = error;
const message = error instanceof Error ? error.message : String(error);
const isTransientNavigationError = message.includes('ERR_EMPTY_RESPONSE') || message.includes('ERR_CONNECTION_RESET');
if (!isTransientNavigationError || attempt === attempts) {
throw error;
}
}
}
throw lastError instanceof Error ? lastError : new Error(`Navigation failed after ${attempts} attempts`);
}
async function expectServerSettingsIcon(page: Page, serverName: string, expectedDataUrl: string): Promise<void> {
const settingsPanel = page.locator('app-server-settings');
const image = settingsPanel.locator('[style*="background-image"]').first();
await expectBackgroundImageLoadedWithUrl(image, expectedDataUrl, 'settings server icon');
}
async function expectRoomHeaderIcon(page: Page, serverName: string, expectedDataUrl: string): Promise<void> {
const channelsPanel = page.locator('app-rooms-side-panel').first();
const image = channelsPanel.locator('[style*="background-image"]').first();
await expectBackgroundImageLoadedWithUrl(image, expectedDataUrl, 'room header server icon');
}
async function expectRailIcon(page: Page, serverName: string, expectedDataUrl: string): Promise<void> {
const image = page.locator(`app-servers-rail button[title="${serverName}"] [style*="background-image"]`).first();
await expectBackgroundImageLoadedWithUrl(image, expectedDataUrl, 'servers rail icon');
}
async function expectSearchResultIcon(page: Page, serverName: string, expectedDataUrl: string): Promise<void> {
const serverCard = page.locator('app-server-search div[title]', { hasText: serverName }).first();
const image = serverCard.locator('[style*="background-image"]').first();
await expect(serverCard).toBeVisible({ timeout: 20_000 });
await expectBackgroundImageLoadedWithUrl(image, expectedDataUrl, 'search result server icon');
}
async function expectBackgroundImageLoadedWithUrl(image: Locator, expectedDataUrl: string, label: string): Promise<void> {
await expect
.poll(
async () => {
if ((await image.count()) === 0) {
return null;
}
return image.evaluate((element) => getComputedStyle(element).backgroundImage);
},
{
timeout: SERVER_ICON_SYNC_TIMEOUT_MS,
message: `${label} background should update`
}
)
.toContain(expectedDataUrl);
await expect
.poll(
async () => {
if ((await image.count()) === 0) {
return false;
}
return image.evaluate(
(element) =>
new Promise<boolean>((resolve) => {
const backgroundImage = getComputedStyle(element).backgroundImage;
const match = /^url\("?(.*?)"?\)$/.exec(backgroundImage);
const img = new Image();
if (!match?.[1]) {
resolve(false);
return;
}
img.onload = () => resolve(img.naturalWidth > 0 && img.naturalHeight > 0);
img.onerror = () => resolve(false);
img.src = match[1];
})
);
},
{
timeout: SERVER_ICON_SYNC_TIMEOUT_MS,
message: `${label} should load`
}
)
.toBe(true);
}
function buildGifUpload(label: string): ImageUploadPayload {
const baseGif = Buffer.from(STATIC_GIF_BASE64, 'base64');
const frameStart = baseGif.indexOf(GIF_FRAME_MARKER);
if (frameStart < 0) {
throw new Error('Failed to locate GIF frame marker for server icon payload');
}
const header = baseGif.subarray(0, frameStart);
const frame = baseGif.subarray(frameStart, baseGif.length - 1);
const commentData = Buffer.from(label, 'ascii');
const commentExtension = Buffer.concat([
Buffer.from([
0x21,
0xfe,
commentData.length
]),
commentData,
Buffer.from([0x00])
]);
const buffer = Buffer.concat([
header,
commentExtension,
frame,
frame,
Buffer.from([0x3b])
]);
const base64 = buffer.toString('base64');
return {
buffer,
dataUrl: `data:image/gif;base64,${base64}`,
mimeType: 'image/gif',
name: `server-icon-${label}.gif`
};
}
function uniqueName(prefix: string): string {
return `${prefix}-${Date.now()}-${Math.random().toString(36)
.slice(2, 8)}`;
}

View File

@@ -0,0 +1,186 @@
import { type Page } from '@playwright/test';
import {
expect,
test,
type Client
} from '../../fixtures/multi-client';
import { ChatMessagesPage } from '../../pages/chat-messages.page';
import { ChatRoomPage } from '../../pages/chat-room.page';
import { RegisterPage } from '../../pages/register.page';
import { ServerSearchPage } from '../../pages/server-search.page';
const PLUGIN_SOURCE_URL = 'http://localhost:4200/plugins/e2e-plugin-source.json';
const PLUGIN_TITLE = 'E2E All API Plugin';
const EDITED_MESSAGE = 'Plugin API edited message';
const ORIGINAL_MESSAGE = 'Plugin API original message';
const DELETED_MESSAGE = 'Plugin API deleted message';
const DELETED_MESSAGE_CONTENT = '[Message deleted]';
const PLUGIN_BOT_MESSAGE = 'Plugin bot message from all-api fixture';
const CUSTOM_EMBED_TEXT = 'E2E custom embed: Plugin API custom embed';
const SOUND_BOARD_TEXT = 'E2E soundboard ready';
const SOUND_BOARD_LABEL = 'E2E Soundboard';
const SOUND_BOARD_PLAYED_MESSAGE = 'E2E soundboard played Airhorn to voice channel';
const VOICE_CHANNEL = 'Plugin Voice';
test.describe('Plugin API multi-user runtime', () => {
test.describe.configure({ timeout: 180_000 });
test('runs chat, embed, soundboard, and profile APIs between two users', async ({ createClient }) => {
const scenario = await createPluginApiScenario(createClient);
await test.step('Alice has the server plugin active', async () => {
await expect(soundboardComposerButton(scenario.alice.page)).toBeVisible({ timeout: 20_000 });
await expect(scenario.alice.page.getByText(SOUND_BOARD_TEXT, { exact: true })).toBeVisible({ timeout: 20_000 });
await expect(scenario.alice.page.getByTestId('e2e-plugin-owned-dom')).toHaveAttribute('data-plugin-owner', 'e2e.all-api-plugin');
});
await test.step('Activate the server plugin for Bob as the embed/soundboard receiver', async () => {
await installGrantAndActivatePlugin(scenario.bob.page, false);
await closeSettingsModal(scenario.bob.page);
await expect(soundboardComposerButton(scenario.bob.page)).toBeVisible({ timeout: 20_000 });
await expect(scenario.bob.page.getByText(SOUND_BOARD_TEXT, { exact: true })).toBeVisible({ timeout: 20_000 });
await expect(scenario.bob.page.getByTestId('e2e-plugin-owned-dom')).toHaveAttribute('data-plugin-owner', 'e2e.all-api-plugin');
});
await test.step('Alice opens the plugin soundboard modal and plays a sound to voice', async () => {
await soundboardComposerButton(scenario.alice.page).click();
await expect(scenario.alice.page.getByRole('dialog', { name: SOUND_BOARD_LABEL })).toBeVisible({ timeout: 20_000 });
await expect(scenario.alice.page.getByTestId('e2e-soundboard-modal')).toHaveAttribute('data-plugin-owner', 'e2e.all-api-plugin');
await scenario.alice.page.getByRole('button', { name: 'Play airhorn to voice' }).click();
await expect(scenario.alice.page.getByTestId('e2e-soundboard-status')).toHaveText(SOUND_BOARD_PLAYED_MESSAGE, { timeout: 20_000 });
});
await test.step('Bob receives messages sent and edited by Alice through the plugin API', async () => {
await expect(scenario.bobMessages.getMessageItemByText(EDITED_MESSAGE)).toBeVisible({ timeout: 30_000 });
await expect(scenario.bobMessages.getMessageItemByText(ORIGINAL_MESSAGE)).toHaveCount(0);
await expect(scenario.bob.page.getByText('(edited)')).toBeVisible({ timeout: 20_000 });
});
await test.step('Bob sees plugin API deletion state and plugin-user messages', async () => {
await expect(scenario.bobMessages.getMessageItemByText(DELETED_MESSAGE_CONTENT)).toBeVisible({ timeout: 30_000 });
await expect(scenario.bobMessages.getMessageItemByText(DELETED_MESSAGE)).toHaveCount(0);
await expect(scenario.bobMessages.getMessageItemByText(PLUGIN_BOT_MESSAGE)).toBeVisible({ timeout: 30_000 });
await expect(scenario.bobMessages.getMessageItemByText(SOUND_BOARD_PLAYED_MESSAGE)).toBeVisible({ timeout: 30_000 });
});
await test.step('Bob renders Alice custom embed through the plugin embed API', async () => {
await expect(scenario.bob.page.getByTestId('plugin-message-embeds')).toContainText(CUSTOM_EMBED_TEXT, { timeout: 30_000 });
});
await test.step('Bob sees Alice profile name changed by the plugin API', async () => {
await expect(scenario.bobMessages.getMessageItemByText(EDITED_MESSAGE)).toContainText('Alice Plugin Renamed', { timeout: 30_000 });
});
});
});
interface PluginApiScenario {
alice: Client;
aliceRoom: ChatRoomPage;
bob: Client;
bobRoom: ChatRoomPage;
aliceMessages: ChatMessagesPage;
bobMessages: ChatMessagesPage;
}
async function createPluginApiScenario(createClient: () => Promise<Client>): Promise<PluginApiScenario> {
const suffix = uniqueName('plugin-api');
const serverName = `Plugin API Server ${suffix}`;
const alice = await createClient();
const bob = await createClient();
await registerUser(alice.page, `alice_${suffix}`, 'Alice');
await registerUser(bob.page, `bob_${suffix}`, 'Bob');
const aliceSearch = new ServerSearchPage(alice.page);
await aliceSearch.createServer(serverName, { description: 'Two-user plugin API E2E coverage' });
await expect(alice.page).toHaveURL(/\/room\//, { timeout: 30_000 });
const aliceRoom = new ChatRoomPage(alice.page);
await aliceRoom.ensureVoiceChannelExists(VOICE_CHANNEL);
await installGrantAndActivatePlugin(alice.page, true);
await closeSettingsModal(alice.page);
await expect(soundboardComposerButton(alice.page)).toBeVisible({ timeout: 20_000 });
const bobSearch = new ServerSearchPage(bob.page);
await bobSearch.joinServerFromSearch(serverName, { acceptPluginDownloads: true });
await expect(bob.page).toHaveURL(/\/room\//, { timeout: 30_000 });
const bobRoom = new ChatRoomPage(bob.page);
await aliceRoom.joinVoiceChannel(VOICE_CHANNEL);
await bobRoom.joinVoiceChannel(VOICE_CHANNEL);
await expect(aliceRoom.voiceControls).toBeVisible({ timeout: 30_000 });
await expect(bobRoom.voiceControls).toBeVisible({ timeout: 30_000 });
const aliceMessages = new ChatMessagesPage(alice.page);
const bobMessages = new ChatMessagesPage(bob.page);
await aliceMessages.waitForReady();
await bobMessages.waitForReady();
await expect(alice.page.locator('[data-testid^="room-user-card-"]', { hasText: 'Bob' })).toBeVisible({ timeout: 30_000 });
await expect(bob.page.locator('[data-testid^="room-user-card-"]', { hasText: 'Alice' })).toBeVisible({ timeout: 30_000 });
return {
alice,
aliceRoom,
bob,
bobRoom,
aliceMessages,
bobMessages
};
}
async function registerUser(page: Page, username: string, displayName: string): Promise<void> {
const registerPage = new RegisterPage(page);
await registerPage.goto();
await registerPage.register(username, displayName, 'TestPass123!');
await expect(page).toHaveURL(/\/search/, { timeout: 30_000 });
}
async function installGrantAndActivatePlugin(page: Page, installFromStore: boolean): Promise<void> {
await page.getByRole('button', { name: 'Plugin Store' }).click();
await expect(page).toHaveURL(/\/plugin-store/, { timeout: 20_000 });
await expect(page.getByTestId('plugin-store-page')).toBeVisible({ timeout: 20_000 });
if (installFromStore) {
await page.getByLabel('Plugin source manifest URL').fill(PLUGIN_SOURCE_URL);
await page.getByRole('button', { name: 'Add Source' }).click();
await expect(page.getByRole('heading', { name: PLUGIN_TITLE })).toBeVisible({ timeout: 20_000 });
await page.getByRole('button', { exact: true, name: /^(Install|Install to Server)$/ }).click();
await expect(page.getByRole('dialog', { name: PLUGIN_TITLE })).toBeVisible({ timeout: 10_000 });
await page.getByRole('button', { name: 'Install and Activate' }).click();
await expect(page.locator('article', { hasText: PLUGIN_TITLE }).getByText('Installed')).toBeVisible({ timeout: 20_000 });
}
await page.getByRole('button', { name: 'Manage Plugins' }).click();
await expect(page.getByTestId('plugin-manager')).toBeVisible({ timeout: 20_000 });
await expect(page.locator('article', { hasText: PLUGIN_TITLE })).toBeVisible({ timeout: 20_000 });
await page.locator('article', { hasText: PLUGIN_TITLE })
.getByRole('button', { name: 'Select' })
.click();
await page.getByRole('button', { name: 'Grant all requested' }).click();
await page.getByRole('button', { name: 'Activate ready plugins' }).click();
await expect(page.locator('article', { hasText: PLUGIN_TITLE }).getByText('ready', { exact: true })).toBeVisible({ timeout: 30_000 });
await page.getByRole('button', { name: 'Logs' }).click();
await expect(page.getByText('all-api plugin completed')).toBeVisible({ timeout: 30_000 });
}
async function closeSettingsModal(page: Page): Promise<void> {
await page.keyboard.press('Escape');
await expect(page.getByTestId('plugin-manager')).toHaveCount(0);
}
function uniqueName(prefix: string): string {
return `${prefix}-${Date.now()}-${Math.random().toString(36)
.slice(2, 8)}`;
}
function soundboardComposerButton(page: Page) {
return page.locator('app-chat-message-composer')
.getByRole('button', { exact: true, name: SOUND_BOARD_LABEL });
}

View File

@@ -0,0 +1,93 @@
import { expect, test } from '../../fixtures/multi-client';
import { RegisterPage } from '../../pages/register.page';
import { ServerSearchPage } from '../../pages/server-search.page';
test.describe('Plugin manager UI', () => {
test.describe.configure({ timeout: 180_000 });
test('installs, grants, activates, and logs an all-API test plugin', async ({ createClient }) => {
const client = await createClient();
const { page } = client;
const suffix = Date.now();
const register = new RegisterPage(page);
const search = new ServerSearchPage(page);
await test.step('Register user and create server context', async () => {
await register.goto();
await register.register(`plugin_${suffix}`, 'Plugin Tester', 'TestPass123!');
await expect(page.getByPlaceholder('Search servers and users...')).toBeVisible({ timeout: 30_000 });
await search.createServer(`Plugin API Server ${suffix}`, {
description: 'Plugin manager UI E2E coverage'
});
await expect(page).toHaveURL(/\/room\//, { timeout: 30_000 });
});
await test.step('Open visible Plugin Store button', async () => {
await page.getByRole('button', { name: 'Plugin Store' }).click();
await expect(page).toHaveURL(/\/plugin-store/, { timeout: 10_000 });
await expect(page.getByTestId('plugin-store-page')).toBeVisible({ timeout: 10_000 });
});
await test.step('Install fixture plugin from source manifest', async () => {
await page.getByLabel('Plugin source manifest URL').fill('http://localhost:4200/plugins/e2e-plugin-source.json');
await page.getByRole('button', { name: 'Add Source' }).click();
await expect(page.getByRole('heading', { name: 'E2E All API Plugin' })).toBeVisible({ timeout: 15_000 });
await page.getByRole('button', { name: 'Readme' }).click();
await expect(page.getByText('Fixture plugin for Playwright coverage.')).toBeVisible({ timeout: 10_000 });
await page.getByRole('button', { exact: true, name: /^(Install|Install to Server)$/ }).click();
const installDialog = page.getByRole('dialog', { name: 'E2E All API Plugin' });
await expect(installDialog).toBeVisible({ timeout: 10_000 });
await expect(installDialog.getByText('Install to server', { exact: true })).toBeVisible();
await page.getByRole('button', { name: 'Install and Activate' }).click();
await expect(page.locator('article', { hasText: 'E2E All API Plugin' }).getByText('Installed')).toBeVisible({ timeout: 10_000 });
});
await test.step('Open plugin manager from the store page', async () => {
await page.getByRole('button', { name: 'Manage Plugins' }).click();
await expect(page.getByTestId('plugin-manager')).toBeVisible({ timeout: 10_000 });
await expect(page.getByTestId('plugin-manager').getByRole('heading', { name: 'Server plugins' })).toBeVisible();
await expect(page.getByText('E2E All API Plugin')).toBeVisible();
});
await test.step('Grant capabilities and activate runtime', async () => {
const manager = page.getByTestId('plugin-manager');
const pluginCard = manager.locator('article', { hasText: 'E2E All API Plugin' });
await manager.getByRole('button', { name: 'Installed' }).click();
await expect(pluginCard).toBeVisible({ timeout: 10_000 });
await pluginCard.getByRole('button', { name: 'Select' }).click();
await page.getByRole('button', { name: 'Grant all requested' }).click();
await page.getByRole('button', { name: 'Activate ready plugins' }).click();
await expect(page.locator('article', { hasText: 'E2E All API Plugin' }).getByText('ready', { exact: true })).toBeVisible({ timeout: 20_000 });
});
await test.step('Verify plugin exercised APIs through logs and extension points', async () => {
const manager = page.getByTestId('plugin-manager');
await manager.getByRole('button', { name: 'Logs' }).click();
await expect(page.getByText('all-api plugin completed')).toBeVisible({ timeout: 20_000 });
await expect(page.getByText('all-api plugin ready')).toBeVisible({ timeout: 10_000 });
await manager.getByRole('button', { name: 'Extension points' }).click();
await expect(page.getByTestId('plugin-extension-counts')).toContainText('Settings pages');
await expect(page.getByTestId('plugin-extension-counts')).toContainText('Embed renderers');
await expect(page.getByTestId('plugin-extension-counts')).toContainText('1');
await expect(page.getByTestId('plugin-conflict-diagnostics')).toContainText(
'No duplicate route, action, embed, channel, panel, or settings contribution ids detected.'
);
await manager.getByRole('button', { exact: true, name: 'Requirements' }).click();
await expect(page.getByTestId('plugin-server-requirements')).toContainText('E2E All API Plugin');
await expect(page.getByTestId('plugin-server-requirements')).toContainText('enabled');
await manager.getByRole('button', { exact: true, name: 'Settings' }).click();
await expect(page.getByTestId('plugin-generated-settings')).toContainText('E2E settings contribution');
await expect(page.getByTestId('plugin-generated-settings')).toContainText('"enabled"');
await manager.getByRole('button', { exact: true, name: 'Docs' }).click();
await expect(page.getByTestId('plugin-installed-docs')).toContainText('Calls every public Toju plugin API surface');
});
});
});

View File

@@ -0,0 +1,369 @@
import type { APIRequestContext, APIResponse } from '@playwright/test';
import WebSocket from 'ws';
import { expect, test } from '../../fixtures/multi-client';
import {
getPluginApiTestEvent,
readPluginApiTestManifest,
TEST_PLUGIN_ID,
TEST_PLUGIN_P2P_EVENT,
TEST_PLUGIN_RELAY_EVENT
} from '../../helpers/plugin-api-test-fixture';
const OWNER_USER_ID = 'plugin-api-owner';
interface CreatedServerResponse {
id: string;
}
interface PluginRequirementResponse {
requirement: {
pluginId: string;
reason?: string;
status: string;
versionRange?: string;
};
}
interface PluginEventDefinitionResponse {
eventDefinition: {
direction: string;
eventName: string;
maxPayloadBytes: number;
pluginId: string;
scope: string;
};
}
interface PluginSnapshotResponse {
eventDefinitions: PluginEventDefinitionResponse['eventDefinition'][];
requirements: PluginRequirementResponse['requirement'][];
serverId: string;
}
interface SocketMessage {
[key: string]: unknown;
type?: string;
}
interface TestSocket {
close: () => Promise<void>;
messages: SocketMessage[];
send: (message: SocketMessage) => void;
}
test.describe('Plugin support API', () => {
test('covers plugin requirement, event, data, and websocket APIs with the fixture plugin', async ({ request, testServer }) => {
const manifest = await readPluginApiTestManifest();
const server = await createServer(request, testServer.url, `Plugin API ${Date.now()}`);
const relayEvent = getPluginApiTestEvent(manifest, TEST_PLUGIN_RELAY_EVENT);
const p2pEvent = getPluginApiTestEvent(manifest, TEST_PLUGIN_P2P_EVENT);
const pluginsApi = `${testServer.url}/api/servers/${encodeURIComponent(server.id)}/plugins`;
await test.step('Initial snapshot is empty', async () => {
const snapshot = await expectJson<PluginSnapshotResponse>(await request.get(pluginsApi));
expect(snapshot).toEqual(expect.objectContaining({
eventDefinitions: [],
requirements: [],
serverId: server.id
}));
});
await test.step('Requirement API enforces server management permission', async () => {
const response = await request.put(`${pluginsApi}/${TEST_PLUGIN_ID}/requirement`, {
data: {
actorUserId: 'not-the-owner',
status: 'required'
}
});
const body = await expectJson<{ errorCode: string }>(response, 403);
expect(body.errorCode).toBe('NOT_AUTHORIZED');
});
await test.step('Requirement and event definition APIs persist the test plugin contract', async () => {
const requirement = await expectJson<PluginRequirementResponse>(await request.put(`${pluginsApi}/${TEST_PLUGIN_ID}/requirement`, {
data: {
actorUserId: OWNER_USER_ID,
reason: manifest.description,
status: 'required',
versionRange: `^${manifest.version}`
}
}));
expect(requirement.requirement).toEqual(expect.objectContaining({
pluginId: TEST_PLUGIN_ID,
reason: manifest.description,
status: 'required',
versionRange: `^${manifest.version}`
}));
const relayDefinition = await upsertEventDefinition(request, pluginsApi, relayEvent);
const p2pDefinition = await upsertEventDefinition(request, pluginsApi, p2pEvent);
expect(relayDefinition.eventDefinition).toEqual(expect.objectContaining({
direction: 'serverRelay',
eventName: TEST_PLUGIN_RELAY_EVENT,
pluginId: TEST_PLUGIN_ID,
scope: 'server'
}));
expect(p2pDefinition.eventDefinition).toEqual(expect.objectContaining({
direction: 'p2pHint',
eventName: TEST_PLUGIN_P2P_EVENT,
pluginId: TEST_PLUGIN_ID,
scope: 'user'
}));
const snapshot = await expectJson<PluginSnapshotResponse>(await request.get(pluginsApi));
expect(snapshot.requirements.map((entry) => entry.pluginId)).toEqual([TEST_PLUGIN_ID]);
expect(snapshot.eventDefinitions.map((entry) => entry.eventName).sort()).toEqual([TEST_PLUGIN_P2P_EVENT, TEST_PLUGIN_RELAY_EVENT]);
});
await test.step('Plugin data API refuses arbitrary server persistence', async () => {
const stored = await expectJson<{ errorCode: string }>(await request.put(`${pluginsApi}/${TEST_PLUGIN_ID}/data/settings`, {
data: {
actorUserId: OWNER_USER_ID,
schemaVersion: 1,
scope: 'server',
value: {
enabled: true,
pluginVersion: manifest.version
}
}
}), 410);
expect(stored.errorCode).toBe('PLUGIN_DATA_DISABLED');
const listed = await expectJson<{ errorCode: string }>(await request.get(`${pluginsApi}/${TEST_PLUGIN_ID}/data`, {
params: {
key: 'settings',
scope: 'server',
userId: OWNER_USER_ID
}
}), 410);
expect(listed.errorCode).toBe('PLUGIN_DATA_DISABLED');
const afterDelete = await expectJson<{ errorCode: string }>(await request.delete(`${pluginsApi}/${TEST_PLUGIN_ID}/data/settings`, {
data: {
actorUserId: OWNER_USER_ID,
scope: 'server'
}
}), 410);
expect(afterDelete.errorCode).toBe('PLUGIN_DATA_DISABLED');
});
await test.step('WebSocket plugin API sends snapshots, relays server events, and rejects p2p relays', async () => {
const alice = await openTestSocket(testServer.url);
const bob = await openTestSocket(testServer.url);
try {
alice.send({ type: 'identify', oderId: OWNER_USER_ID, displayName: 'Plugin Owner' });
bob.send({ type: 'identify', oderId: 'plugin-api-peer', displayName: 'Plugin Peer' });
alice.send({ type: 'join_server', serverId: server.id });
bob.send({ type: 'join_server', serverId: server.id });
const aliceSnapshot = await waitForSocketMessage(alice, (message) => message.type === 'plugin_requirements');
const bobSnapshot = await waitForSocketMessage(bob, (message) => message.type === 'plugin_requirements');
const bobEventNames = (bobSnapshot['snapshot'] as PluginSnapshotResponse).eventDefinitions
.map((entry) => entry.eventName)
.sort();
expect((aliceSnapshot['snapshot'] as PluginSnapshotResponse).requirements[0]?.pluginId).toBe(TEST_PLUGIN_ID);
expect(bobEventNames).toEqual([TEST_PLUGIN_P2P_EVENT, TEST_PLUGIN_RELAY_EVENT]);
alice.send({
type: 'plugin_event',
eventId: 'relay-event-1',
eventName: TEST_PLUGIN_RELAY_EVENT,
payload: { message: 'hello from fixture plugin' },
pluginId: TEST_PLUGIN_ID,
serverId: server.id,
sourcePluginUserId: 'fixture-plugin-user'
});
const relayedEvent = await waitForSocketMessage(bob, (message) => message.type === 'plugin_event');
expect(relayedEvent).toEqual(expect.objectContaining({
eventId: 'relay-event-1',
eventName: TEST_PLUGIN_RELAY_EVENT,
pluginId: TEST_PLUGIN_ID,
serverId: server.id,
sourcePluginUserId: 'fixture-plugin-user',
sourceUserId: OWNER_USER_ID
}));
expect(relayedEvent['payload']).toEqual({ message: 'hello from fixture plugin' });
expect(typeof relayedEvent['emittedAt']).toBe('number');
alice.send({
type: 'plugin_event',
eventId: 'p2p-event-1',
eventName: TEST_PLUGIN_P2P_EVENT,
payload: { hint: true },
pluginId: TEST_PLUGIN_ID,
serverId: server.id
});
const p2pError = await waitForSocketMessage(
alice,
(message) => message.type === 'plugin_error' && message['eventId'] === 'p2p-event-1'
);
expect(p2pError['code']).toBe('PLUGIN_EVENT_NOT_RELAYABLE');
alice.send({
type: 'plugin_event',
eventId: 'missing-event-1',
eventName: 'e2e:missing',
payload: {},
pluginId: TEST_PLUGIN_ID,
serverId: server.id
});
const missingError = await waitForSocketMessage(
alice,
(message) => message.type === 'plugin_error' && message['eventId'] === 'missing-event-1'
);
expect(missingError['code']).toBe('PLUGIN_EVENT_NOT_REGISTERED');
} finally {
await Promise.all([alice.close(), bob.close()]);
}
});
await test.step('Delete APIs remove event definitions and requirements', async () => {
await expectJson<{ ok: boolean }>(await request.delete(`${pluginsApi}/${TEST_PLUGIN_ID}/events/${TEST_PLUGIN_RELAY_EVENT}`, {
data: { actorUserId: OWNER_USER_ID }
}));
await expectJson<{ ok: boolean }>(await request.delete(`${pluginsApi}/${TEST_PLUGIN_ID}/events/${TEST_PLUGIN_P2P_EVENT}`, {
data: { actorUserId: OWNER_USER_ID }
}));
await expectJson<{ ok: boolean }>(await request.delete(`${pluginsApi}/${TEST_PLUGIN_ID}/requirement`, {
data: { actorUserId: OWNER_USER_ID }
}));
const snapshot = await expectJson<PluginSnapshotResponse>(await request.get(pluginsApi));
expect(snapshot.eventDefinitions).toEqual([]);
expect(snapshot.requirements).toEqual([]);
});
});
});
async function createServer(
request: APIRequestContext,
baseUrl: string,
serverName: string
): Promise<CreatedServerResponse> {
const response = await request.post(`${baseUrl}/api/servers`, {
data: {
channels: [
{
id: 'general-text',
name: 'general',
position: 0,
type: 'text'
}
],
description: 'Server for plugin API E2E coverage',
id: `plugin-api-${Date.now()}`,
isPrivate: false,
name: serverName,
ownerId: OWNER_USER_ID,
ownerPublicKey: 'plugin-api-owner-public-key',
tags: ['plugins']
}
});
return await expectJson<CreatedServerResponse>(response, 201);
}
async function upsertEventDefinition(
request: APIRequestContext,
pluginsApi: string,
eventDefinition: ReturnType<typeof getPluginApiTestEvent>
): Promise<PluginEventDefinitionResponse> {
return await expectJson<PluginEventDefinitionResponse>(await request.put(
`${pluginsApi}/${TEST_PLUGIN_ID}/events/${encodeURIComponent(eventDefinition.eventName)}`,
{
data: {
actorUserId: OWNER_USER_ID,
direction: eventDefinition.direction,
maxPayloadBytes: eventDefinition.maxPayloadBytes,
schemaJson: '{"type":"object"}',
scope: eventDefinition.scope
}
}
));
}
async function expectJson<T>(response: APIResponse, status = 200): Promise<T> {
expect(response.status()).toBe(status);
return await response.json() as T;
}
async function openTestSocket(baseUrl: string): Promise<TestSocket> {
const socketUrl = baseUrl.replace(/^http/, 'ws');
const socket = new WebSocket(socketUrl);
const messages: SocketMessage[] = [];
socket.on('message', (data) => {
messages.push(JSON.parse(data.toString()) as SocketMessage);
});
await new Promise<void>((resolve, reject) => {
socket.once('open', () => resolve());
socket.once('error', reject);
});
await waitForSocketMessage({ messages, send: () => {}, close: async () => {} }, (message) => message.type === 'connected');
return {
close: async () => {
if (socket.readyState === WebSocket.CLOSED) {
return;
}
await new Promise<void>((resolve) => {
socket.once('close', () => resolve());
socket.close();
});
},
messages,
send: (message: SocketMessage) => {
socket.send(JSON.stringify(message));
}
};
}
async function waitForSocketMessage(
socket: Pick<TestSocket, 'messages'>,
predicate: (message: SocketMessage) => boolean,
timeoutMs = 10_000
): Promise<SocketMessage> {
const startedAt = Date.now();
return await new Promise((resolve, reject) => {
const interval = setInterval(() => {
const message = socket.messages.find(predicate);
if (message) {
clearInterval(interval);
resolve(message);
return;
}
if (Date.now() - startedAt > timeoutMs) {
clearInterval(interval);
reject(new Error('Timed out waiting for websocket message'));
}
}, 25);
});
}

View File

@@ -56,12 +56,7 @@ async function setupServerWithBothUsers(
// Bob joins server // Bob joins server
const bobSearch = new ServerSearchPage(bob.page); const bobSearch = new ServerSearchPage(bob.page);
await bobSearch.searchInput.fill(SERVER_NAME); await bobSearch.joinServerFromSearch(SERVER_NAME);
const serverCard = bob.page.locator('button', { hasText: SERVER_NAME }).first();
await expect(serverCard).toBeVisible({ timeout: 10_000 });
await serverCard.click();
await expect(bob.page).toHaveURL(/\/room\//, { timeout: 15_000 }); await expect(bob.page).toHaveURL(/\/room\//, { timeout: 15_000 });
} }

View File

@@ -88,7 +88,7 @@ test.describe('Connectivity warning', () => {
await register.goto(); await register.goto();
await register.register(`alice_${suffix}`, 'Alice', 'TestPass123!'); await register.register(`alice_${suffix}`, 'Alice', 'TestPass123!');
await expect(alice.page.getByPlaceholder('Search servers...')).toBeVisible({ timeout: 30_000 }); await expect(alice.page.getByPlaceholder('Search servers and users...')).toBeVisible({ timeout: 30_000 });
}); });
await test.step('Register Bob', async () => { await test.step('Register Bob', async () => {
@@ -96,7 +96,7 @@ test.describe('Connectivity warning', () => {
await register.goto(); await register.goto();
await register.register(`bob_${suffix}`, 'Bob', 'TestPass123!'); await register.register(`bob_${suffix}`, 'Bob', 'TestPass123!');
await expect(bob.page.getByPlaceholder('Search servers...')).toBeVisible({ timeout: 30_000 }); await expect(bob.page.getByPlaceholder('Search servers and users...')).toBeVisible({ timeout: 30_000 });
}); });
await test.step('Register Charlie', async () => { await test.step('Register Charlie', async () => {
@@ -104,7 +104,7 @@ test.describe('Connectivity warning', () => {
await register.goto(); await register.goto();
await register.register(`charlie_${suffix}`, 'Charlie', 'TestPass123!'); await register.register(`charlie_${suffix}`, 'Charlie', 'TestPass123!');
await expect(charlie.page.getByPlaceholder('Search servers...')).toBeVisible({ timeout: 30_000 }); await expect(charlie.page.getByPlaceholder('Search servers and users...')).toBeVisible({ timeout: 30_000 });
}); });
// ── Create server and have everyone join ── // ── Create server and have everyone join ──
@@ -117,22 +117,14 @@ test.describe('Connectivity warning', () => {
await test.step('Bob joins the server', async () => { await test.step('Bob joins the server', async () => {
const search = new ServerSearchPage(bob.page); const search = new ServerSearchPage(bob.page);
await search.searchInput.fill(serverName); await search.joinServerFromSearch(serverName);
const card = bob.page.locator('button', { hasText: serverName }).first();
await expect(card).toBeVisible({ timeout: 15_000 });
await card.click();
await expect(bob.page).toHaveURL(/\/room\//, { timeout: 15_000 }); await expect(bob.page).toHaveURL(/\/room\//, { timeout: 15_000 });
}); });
await test.step('Charlie joins the server', async () => { await test.step('Charlie joins the server', async () => {
const search = new ServerSearchPage(charlie.page); const search = new ServerSearchPage(charlie.page);
await search.searchInput.fill(serverName); await search.joinServerFromSearch(serverName);
const card = charlie.page.locator('button', { hasText: serverName }).first();
await expect(card).toBeVisible({ timeout: 15_000 });
await card.click();
await expect(charlie.page).toHaveURL(/\/room\//, { timeout: 15_000 }); await expect(charlie.page).toHaveURL(/\/room\//, { timeout: 15_000 });
}); });

View File

@@ -9,10 +9,11 @@ test.describe('ICE server settings', () => {
await register.goto(); await register.goto();
await register.register(`user_${suffix}`, 'IceTestUser', 'TestPass123!'); await register.register(`user_${suffix}`, 'IceTestUser', 'TestPass123!');
await expect(page.getByPlaceholder('Search servers...')).toBeVisible({ timeout: 30_000 }); await expect(page.getByPlaceholder('Search servers and users...')).toBeVisible({ timeout: 30_000 });
await page.getByTitle('Settings').click(); await page.getByTitle('Settings').click();
await expect(page.getByRole('dialog')).toBeVisible({ timeout: 10_000 }); await expect(page.getByRole('button', { name: 'Network' })).toBeVisible({ timeout: 10_000 });
await page.getByRole('button', { name: 'Network' }).click(); await page.getByRole('button', { name: 'Network' }).click();
await expect(page.getByTestId('ice-server-settings')).toBeVisible({ timeout: 10_000 });
} }
test('allows adding, removing, and reordering ICE servers', async ({ createClient }) => { test('allows adding, removing, and reordering ICE servers', async ({ createClient }) => {
@@ -101,7 +102,7 @@ test.describe('ICE server settings', () => {
await page.reload({ waitUntil: 'domcontentloaded' }); await page.reload({ waitUntil: 'domcontentloaded' });
await page.getByTitle('Settings').click(); await page.getByTitle('Settings').click();
await expect(page.getByRole('dialog')).toBeVisible({ timeout: 10_000 }); await expect(page.getByRole('button', { name: 'Network' })).toBeVisible({ timeout: 10_000 });
await page.getByRole('button', { name: 'Network' }).click(); await page.getByRole('button', { name: 'Network' }).click();
await expect(page.getByText('stun:persist-test.example.com:3478')).toBeVisible({ timeout: 10_000 }); await expect(page.getByText('stun:persist-test.example.com:3478')).toBeVisible({ timeout: 10_000 });
}); });

View File

@@ -89,7 +89,7 @@ test.describe('STUN/TURN fallback behaviour', () => {
await register.goto(); await register.goto();
await register.register(`alice_${suffix}`, 'Alice', 'TestPass123!'); await register.register(`alice_${suffix}`, 'Alice', 'TestPass123!');
await expect(alice.page.getByPlaceholder('Search servers...')).toBeVisible({ timeout: 30_000 }); await expect(alice.page.getByPlaceholder('Search servers and users...')).toBeVisible({ timeout: 30_000 });
}); });
await test.step('Register Bob', async () => { await test.step('Register Bob', async () => {
@@ -97,7 +97,7 @@ test.describe('STUN/TURN fallback behaviour', () => {
await register.goto(); await register.goto();
await register.register(`bob_${suffix}`, 'Bob', 'TestPass123!'); await register.register(`bob_${suffix}`, 'Bob', 'TestPass123!');
await expect(bob.page.getByPlaceholder('Search servers...')).toBeVisible({ timeout: 30_000 }); await expect(bob.page.getByPlaceholder('Search servers and users...')).toBeVisible({ timeout: 30_000 });
}); });
await test.step('Alice creates a server', async () => { await test.step('Alice creates a server', async () => {
@@ -109,11 +109,7 @@ test.describe('STUN/TURN fallback behaviour', () => {
await test.step('Bob joins Alice server', async () => { await test.step('Bob joins Alice server', async () => {
const search = new ServerSearchPage(bob.page); const search = new ServerSearchPage(bob.page);
await search.searchInput.fill(serverName); await search.joinServerFromSearch(serverName);
const serverCard = bob.page.locator('button', { hasText: serverName }).first();
await expect(serverCard).toBeVisible({ timeout: 15_000 });
await serverCard.click();
await expect(bob.page).toHaveURL(/\/room\//, { timeout: 15_000 }); await expect(bob.page).toHaveURL(/\/room\//, { timeout: 15_000 });
}); });

View File

@@ -556,7 +556,7 @@ async function installDeterministicVoiceSettings(page: Page): Promise<void> {
} }
async function openSearchView(page: Page): Promise<void> { async function openSearchView(page: Page): Promise<void> {
const searchInput = page.getByPlaceholder('Search servers...'); const searchInput = page.getByPlaceholder('Search servers and users...');
if (await searchInput.isVisible().catch(() => false)) { if (await searchInput.isVisible().catch(() => false)) {
return; return;
@@ -567,15 +567,15 @@ async function openSearchView(page: Page): Promise<void> {
} }
async function joinRoomFromSearch(page: Page, roomName: string): Promise<void> { async function joinRoomFromSearch(page: Page, roomName: string): Promise<void> {
const searchInput = page.getByPlaceholder('Search servers...'); const searchInput = page.getByPlaceholder('Search servers and users...');
await expect(searchInput).toBeVisible({ timeout: 20_000 }); await expect(searchInput).toBeVisible({ timeout: 20_000 });
await searchInput.fill(roomName); await searchInput.fill(roomName);
const roomCard = page.locator('button', { hasText: roomName }).first(); const roomCard = page.locator('div[title]', { hasText: roomName }).first();
await expect(roomCard).toBeVisible({ timeout: 20_000 }); await expect(roomCard).toBeVisible({ timeout: 20_000 });
await roomCard.click(); await roomCard.dblclick();
await expect(page).toHaveURL(/\/room\//, { timeout: 20_000 }); await expect(page).toHaveURL(/\/room\//, { timeout: 20_000 });
await expect(page.locator('app-rooms-side-panel').first()).toBeVisible({ timeout: 20_000 }); await expect(page.locator('app-rooms-side-panel').first()).toBeVisible({ timeout: 20_000 });
await waitForCurrentRoomName(page, roomName); await waitForCurrentRoomName(page, roomName);

View File

@@ -319,7 +319,7 @@ async function installDeterministicVoiceSettings(page: Page): Promise<void> {
} }
async function openSearchView(page: Page): Promise<void> { async function openSearchView(page: Page): Promise<void> {
const searchInput = page.getByPlaceholder('Search servers...'); const searchInput = page.getByPlaceholder('Search servers and users...');
if (await searchInput.isVisible().catch(() => false)) { if (await searchInput.isVisible().catch(() => false)) {
return; return;
@@ -330,15 +330,15 @@ async function openSearchView(page: Page): Promise<void> {
} }
async function joinRoomFromSearch(page: Page, roomName: string): Promise<void> { async function joinRoomFromSearch(page: Page, roomName: string): Promise<void> {
const searchInput = page.getByPlaceholder('Search servers...'); const searchInput = page.getByPlaceholder('Search servers and users...');
await expect(searchInput).toBeVisible({ timeout: 20_000 }); await expect(searchInput).toBeVisible({ timeout: 20_000 });
await searchInput.fill(roomName); await searchInput.fill(roomName);
const roomCard = page.locator('button', { hasText: roomName }).first(); const roomCard = page.locator('div[title]', { hasText: roomName }).first();
await expect(roomCard).toBeVisible({ timeout: 20_000 }); await expect(roomCard).toBeVisible({ timeout: 20_000 });
await roomCard.click(); await roomCard.dblclick();
await expect(page).toHaveURL(/\/room\//, { timeout: 20_000 }); await expect(page).toHaveURL(/\/room\//, { timeout: 20_000 });
await expect(page.locator('app-rooms-side-panel').first()).toBeVisible({ timeout: 20_000 }); await expect(page.locator('app-rooms-side-panel').first()).toBeVisible({ timeout: 20_000 });
await waitForCurrentRoomName(page, roomName); await waitForCurrentRoomName(page, roomName);

View File

@@ -96,14 +96,7 @@ test.describe('Full user journey: register -> server -> voice chat', () => {
await test.step('Bob finds and joins the server', async () => { await test.step('Bob finds and joins the server', async () => {
const searchPage = new ServerSearchPage(bob.page); const searchPage = new ServerSearchPage(bob.page);
// Search for the server await searchPage.joinServerFromSearch(SERVER_NAME);
await searchPage.searchInput.fill(SERVER_NAME);
// Wait for search results and click the server
const serverCard = bob.page.locator('button', { hasText: SERVER_NAME }).first();
await expect(serverCard).toBeVisible({ timeout: 10_000 });
await serverCard.click();
// Bob should be in the room now // Bob should be in the room now
await expect(bob.page).toHaveURL(/\/room\//, { timeout: 15_000 }); await expect(bob.page).toHaveURL(/\/room\//, { timeout: 15_000 });

View File

@@ -16,6 +16,7 @@ Electron main-process package for MetoYou / Toju. This directory owns desktop bo
| --- | --- | | --- | --- |
| `main.ts` | Electron app bootstrap and process entry point | | `main.ts` | Electron app bootstrap and process entry point |
| `preload.ts` | Typed renderer-facing preload bridge | | `preload.ts` | Typed renderer-facing preload bridge |
| `process-list.ts` | Linux/Windows process-name scan used by now-playing game detection |
| `app/` | App lifecycle and startup composition | | `app/` | App lifecycle and startup composition |
| `ipc/` | Renderer-invoked IPC handlers | | `ipc/` | Renderer-invoked IPC handlers |
| `cqrs/` | Local database command/query handlers and mappings | | `cqrs/` | Local database command/query handlers and mappings |
@@ -27,5 +28,6 @@ Electron main-process package for MetoYou / Toju. This directory owns desktop bo
## Notes ## Notes
- When adding a renderer-facing capability, update the Electron implementation, `preload.ts`, and the renderer bridge in `toju-app/` together. - When adding a renderer-facing capability, update the Electron implementation, `preload.ts`, and the renderer bridge in `toju-app/` together.
- Plugin client data is stored in the local Electron SQLite database in the dedicated user-scoped `plugin_data` table. Renderer plugins reach it through CQRS commands/queries exposed by the preload bridge; the signal server must not be used for arbitrary plugin data persistence.
- Treat `dist/electron/` and `dist-electron/` as generated output. - Treat `dist/electron/` and `dist-electron/` as generated output.
- See [AGENTS.md](AGENTS.md) for package-level editing rules. - See [AGENTS.md](AGENTS.md) for package-level editing rules.

View File

@@ -0,0 +1,69 @@
import { randomBytes } from 'crypto';
export interface IssuedToken {
token: string;
userId: string;
username: string;
displayName: string;
signalingServerUrl: string;
issuedAt: number;
expiresAt: number;
}
const TOKEN_TTL_MS = 24 * 60 * 60 * 1000;
const tokens = new Map<string, IssuedToken>();
export function issueToken(params: {
userId: string;
username: string;
displayName: string;
signalingServerUrl: string;
}): IssuedToken {
const token = randomBytes(32).toString('hex');
const issuedAt = Date.now();
const issued: IssuedToken = {
token,
issuedAt,
expiresAt: issuedAt + TOKEN_TTL_MS,
userId: params.userId,
username: params.username,
displayName: params.displayName,
signalingServerUrl: params.signalingServerUrl
};
tokens.set(token, issued);
return issued;
}
export function consumeToken(token: string): IssuedToken | null {
const issued = tokens.get(token);
if (!issued) {
return null;
}
if (issued.expiresAt < Date.now()) {
tokens.delete(token);
return null;
}
return issued;
}
export function revokeToken(token: string): void {
tokens.delete(token);
}
export function clearAllTokens(): void {
tokens.clear();
}
export function pruneExpiredTokens(): void {
const now = Date.now();
for (const [token, issued] of tokens) {
if (issued.expiresAt < now) {
tokens.delete(token);
}
}
}

133
electron/api/docs-html.ts Normal file
View File

@@ -0,0 +1,133 @@
import { promises as fs } from 'fs';
import * as path from 'path';
function getScalarBundleCandidates(): string[] {
const processWithResources = process as NodeJS.Process & { resourcesPath?: string };
const candidates: string[] = [];
if (processWithResources.resourcesPath) {
candidates.push(path.join(processWithResources.resourcesPath, 'scalar', 'api-reference.js'));
}
candidates.push(path.join(process.cwd(), 'node_modules', '@scalar', 'api-reference', 'dist', 'browser', 'standalone.js'));
try {
candidates.push(path.join(path.dirname(require.resolve('@scalar/api-reference')), 'browser', 'standalone.js'));
} catch {
// ignore; the packaged app path above is the production path
}
return candidates;
}
export async function getScalarApiReferenceBundlePath(): Promise<string | null> {
for (const candidate of getScalarBundleCandidates()) {
try {
await fs.access(candidate);
return candidate;
} catch {
// try the next candidate
}
}
return null;
}
export function getDocsHtml(specUrl: string): string {
const scalarConfig = {
url: specUrl,
theme: 'default',
layout: 'modern',
proxyUrl: '',
telemetry: false,
persistAuth: false,
showDeveloperTools: 'never',
hideDownloadButton: false,
hideTestRequestButton: false,
hideClientButton: false,
externalUrls: {
dashboardUrl: '',
registryUrl: '',
proxyUrl: '',
apiBaseUrl: ''
},
agent: {
disabled: true,
hideAddApi: true
},
mcp: {
disabled: true
}
};
const contentSecurityPolicy = [
"default-src 'none'",
"script-src 'self' 'nonce-metoyou-local-api-docs'",
"style-src 'self' 'unsafe-inline'",
"img-src 'self' data: blob:",
"font-src 'self' data:",
"connect-src 'self'",
"base-uri 'none'",
"form-action 'none'",
"frame-ancestors 'none'"
].join('; ');
return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta
http-equiv="Content-Security-Policy"
content="${contentSecurityPolicy}"
/>
<title>MetoYou Local API</title>
<style>
:root { color-scheme: light dark; }
body {
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
background: #0b0d11;
color: #e6e9ee;
}
.placeholder {
max-width: 720px;
margin: 8vh auto;
padding: 2rem;
background: #14181f;
border: 1px solid #232a35;
border-radius: 12px;
}
h1 { margin-top: 0; }
a { color: #7aa2f7; }
code { background: #1f262f; padding: 0.1rem 0.4rem; border-radius: 4px; }
#api-reference { min-height: 100vh; }
</style>
</head>
<body>
<div id="api-reference"></div>
<noscript>
<div class="placeholder">
<h1>API Documentation</h1>
<p>JavaScript is required to render Scalar. The OpenAPI specification is available directly:</p>
<p><a href="${specUrl}">${specUrl}</a></p>
</div>
</noscript>
<script nonce="metoyou-local-api-docs" src="/scalar/api-reference.js"></script>
<script nonce="metoyou-local-api-docs">
(function () {
var config = ${JSON.stringify(scalarConfig)};
if (!window.Scalar || typeof window.Scalar.createApiReference !== 'function') {
var root = document.getElementById('api-reference');
root.innerHTML = '<div class="placeholder"><h1>API Documentation</h1>'
+ '<p>The bundled Scalar UI could not be loaded.</p>'
+ '<p>Spec: <a href="' + config.url + '">' + config.url + '</a></p></div>';
return;
}
window.Scalar.createApiReference('#api-reference', config);
})();
</script>
</body>
</html>`;
}

View File

@@ -0,0 +1,108 @@
import { promises as fs } from 'fs';
import * as path from 'path';
import { HttpError } from './http-helpers';
const MIME_TYPES_BY_EXTENSION: Record<string, string> = {
'.css': 'text/css; charset=utf-8',
'.gif': 'image/gif',
'.html': 'text/html; charset=utf-8',
'.ico': 'image/x-icon',
'.jpeg': 'image/jpeg',
'.jpg': 'image/jpeg',
'.js': 'application/javascript; charset=utf-8',
'.json': 'application/json; charset=utf-8',
'.map': 'application/json; charset=utf-8',
'.png': 'image/png',
'.svg': 'image/svg+xml; charset=utf-8',
'.txt': 'text/plain; charset=utf-8',
'.webp': 'image/webp',
'.woff': 'font/woff',
'.woff2': 'font/woff2'
};
function getDocsRootCandidates(): string[] {
const processWithResources = process as NodeJS.Process & { resourcesPath?: string };
const candidates: string[] = [];
if (processWithResources.resourcesPath) {
candidates.push(path.join(processWithResources.resourcesPath, 'docusaurus'));
}
candidates.push(path.join(process.cwd(), 'docs-site', 'build'));
return candidates;
}
async function getDocusaurusBuildRoot(): Promise<string | null> {
for (const candidate of getDocsRootCandidates()) {
try {
const stat = await fs.stat(candidate);
if (stat.isDirectory()) {
return candidate;
}
} catch {
// try next candidate
}
}
return null;
}
function isPathInside(parent: string, child: string): boolean {
const relative = path.relative(parent, child);
return relative === '' || (!!relative && !relative.startsWith('..') && !path.isAbsolute(relative));
}
function resolveAssetPath(root: string, pathname: string): string {
const withoutPrefix = pathname.replace(/^\/docusaurus\/?/u, '');
const decoded = decodeURIComponent(withoutPrefix);
const normalized = decoded.endsWith('/') || decoded === '' ? path.join(decoded, 'index.html') : decoded;
const absolutePath = path.resolve(root, normalized);
if (!isPathInside(root, absolutePath)) {
throw new HttpError(400, 'Invalid Docusaurus asset path', 'INVALID_DOCS_PATH');
}
return absolutePath;
}
export async function resolveDocusaurusRoute(pathname: string): Promise<{ filePath: string; contentType: string }> {
const root = await getDocusaurusBuildRoot();
if (!root) {
throw new HttpError(
503,
'Docusaurus build is not available. Run npm run build:docs before opening the docs endpoint.',
'DOCUSAURUS_BUILD_MISSING'
);
}
let filePath = resolveAssetPath(root, pathname);
try {
const stat = await fs.stat(filePath);
if (stat.isDirectory()) {
filePath = path.join(filePath, 'index.html');
}
} catch {
const directoryIndexPath = path.join(filePath, 'index.html');
try {
await fs.access(directoryIndexPath);
filePath = directoryIndexPath;
} catch {
filePath = path.join(root, '404.html');
}
}
if (!isPathInside(root, filePath)) {
throw new HttpError(400, 'Invalid Docusaurus asset path', 'INVALID_DOCS_PATH');
}
const contentType = MIME_TYPES_BY_EXTENSION[path.extname(filePath).toLowerCase()] ?? 'application/octet-stream';
return { filePath, contentType };
}

View File

@@ -0,0 +1,108 @@
import { IncomingMessage, ServerResponse } from 'http';
export interface RequestContext {
method: string;
url: URL;
pathname: string;
headers: IncomingMessage['headers'];
remoteAddress: string;
bearerToken: string | null;
}
const MAX_BODY_BYTES = 1 * 1024 * 1024; // 1 MiB
export function getBearerToken(headers: IncomingMessage['headers']): string | null {
const raw = headers.authorization;
if (typeof raw !== 'string') {
return null;
}
const trimmed = raw.trim();
if (!/^bearer\s+/iu.test(trimmed)) {
return null;
}
const token = trimmed.replace(/^bearer\s+/iu, '').trim();
return token.length > 0 ? token : null;
}
export async function readJsonBody<T>(req: IncomingMessage): Promise<T> {
const length = Number(req.headers['content-length'] ?? 0);
if (length > MAX_BODY_BYTES) {
throw new HttpError(413, 'Request body too large', 'BODY_TOO_LARGE');
}
const chunks: Buffer[] = [];
let received = 0;
for await (const chunk of req) {
const buffer = chunk instanceof Buffer ? chunk : Buffer.from(chunk as string);
received += buffer.length;
if (received > MAX_BODY_BYTES) {
throw new HttpError(413, 'Request body too large', 'BODY_TOO_LARGE');
}
chunks.push(buffer);
}
if (chunks.length === 0) {
return {} as T;
}
const raw = Buffer.concat(chunks).toString('utf8');
try {
return JSON.parse(raw) as T;
} catch {
throw new HttpError(400, 'Invalid JSON body', 'INVALID_JSON');
}
}
export function sendJson(res: ServerResponse, status: number, payload: unknown): void {
if (!res.headersSent) {
res.statusCode = status;
res.setHeader('Content-Type', 'application/json; charset=utf-8');
res.setHeader('Cache-Control', 'no-store');
}
res.end(JSON.stringify(payload));
}
export function sendText(res: ServerResponse, status: number, text: string, contentType = 'text/plain; charset=utf-8'): void {
if (!res.headersSent) {
res.statusCode = status;
res.setHeader('Content-Type', contentType);
res.setHeader('Cache-Control', 'no-store');
}
res.end(text);
}
export class HttpError extends Error {
readonly status: number;
readonly code: string;
constructor(status: number, message: string, code: string) {
super(message);
this.status = status;
this.code = code;
}
}
export function sendError(res: ServerResponse, error: unknown): void {
if (error instanceof HttpError) {
sendJson(res, error.status, { error: error.message, errorCode: error.code });
return;
}
const message = error instanceof Error ? error.message : 'Internal server error';
sendJson(res, 500, { error: message, errorCode: 'INTERNAL_ERROR' });
}

8
electron/api/index.ts Normal file
View File

@@ -0,0 +1,8 @@
export {
applyLocalApiSettings,
getLocalApiSnapshot,
startLocalApiServer,
stopLocalApiServer,
type LocalApiSnapshot,
type LocalApiStatus
} from './local-api-server';

View File

@@ -0,0 +1,286 @@
import {
createServer,
IncomingMessage,
Server,
ServerResponse
} from 'http';
import { createReadStream } from 'fs';
import { AddressInfo } from 'net';
import { pipeline } from 'stream/promises';
import { getDataSource } from '../db/database';
import { LocalApiSettings, readDesktopSettings } from '../desktop-settings';
import { authenticate, matchRoute } from './router';
import { clearAllTokens } from './auth-store';
import {
HttpError,
RequestContext,
getBearerToken,
readJsonBody,
sendError,
sendJson,
sendText
} from './http-helpers';
export type LocalApiStatus = 'stopped' | 'starting' | 'running' | 'error';
export interface LocalApiSnapshot {
status: LocalApiStatus;
host: string | null;
port: number | null;
baseUrl: string | null;
error: string | null;
exposeOnLan: boolean;
scalarEnabled: boolean;
docusaurusEnabled: boolean;
}
let server: Server | null = null;
let currentStatus: LocalApiStatus = 'stopped';
let currentBindHost: string | null = null;
let currentBindPort: number | null = null;
let currentError: string | null = null;
let activeSettings: LocalApiSettings | null = null;
function pickBindHost(settings: LocalApiSettings): string {
return settings.exposeOnLan ? '0.0.0.0' : '127.0.0.1';
}
function buildBaseUrl(host: string, port: number): string {
const safeHost = host === '0.0.0.0' ? '127.0.0.1' : host;
return `http://${safeHost}:${port}`;
}
async function sendFile(res: ServerResponse, status: number, filePath: string, contentType: string): Promise<void> {
if (!res.headersSent) {
res.statusCode = status;
res.setHeader('Content-Type', contentType);
res.setHeader('Cache-Control', 'no-store');
}
await pipeline(createReadStream(filePath), res);
}
export function getLocalApiSnapshot(): LocalApiSnapshot {
const settings = activeSettings ?? readDesktopSettings().localApi;
return {
status: currentStatus,
host: currentBindHost,
port: currentBindPort,
baseUrl: currentBindHost && currentBindPort ? buildBaseUrl(currentBindHost, currentBindPort) : null,
error: currentError,
exposeOnLan: settings.exposeOnLan,
scalarEnabled: settings.scalarEnabled,
docusaurusEnabled: settings.docusaurusEnabled
};
}
async function handleRequest(req: IncomingMessage, res: ServerResponse, settings: LocalApiSettings): Promise<void> {
// CORS for loopback origin only. Local-first; not a public API.
const origin = req.headers.origin;
const allowOrigin = origin && /^https?:\/\/(localhost|127\.0\.0\.1)(:\d+)?$/iu.test(origin) ? origin : 'null';
res.setHeader('Access-Control-Allow-Origin', allowOrigin);
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.setHeader('Access-Control-Max-Age', '600');
if (req.method === 'OPTIONS') {
res.statusCode = 204;
res.end();
return;
}
let urlObj: URL;
try {
urlObj = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
} catch {
sendJson(res, 400, { error: 'Invalid URL', errorCode: 'INVALID_URL' });
return;
}
const requestContext: RequestContext = {
method: (req.method ?? 'GET').toUpperCase(),
url: urlObj,
pathname: urlObj.pathname,
headers: req.headers,
remoteAddress: req.socket.remoteAddress ?? '',
bearerToken: getBearerToken(req.headers)
};
const { match, methodNotAllowed } = matchRoute(requestContext.method, requestContext.pathname);
if (!match) {
if (methodNotAllowed) {
sendJson(res, 405, { error: 'Method not allowed', errorCode: 'METHOD_NOT_ALLOWED' });
} else {
sendJson(res, 404, { error: 'Not found', errorCode: 'NOT_FOUND' });
}
return;
}
if (match.requiresAuth) {
const issued = authenticate(requestContext.bearerToken);
if (!issued) {
sendJson(res, 401, { error: 'Authentication required', errorCode: 'UNAUTHORIZED' });
return;
}
}
const dataSource = getDataSource() ?? null;
if (match.requiresDatabase && (!dataSource || !dataSource.isInitialized)) {
sendJson(res, 503, { error: 'Database not initialised', errorCode: 'DB_UNAVAILABLE' });
return;
}
let bodyCache: unknown | undefined;
try {
const baseUrl = buildBaseUrl(currentBindHost ?? '127.0.0.1', currentBindPort ?? settings.port);
const result = await match.handler({
request: requestContext,
settings,
baseUrl,
dataSource,
bodyBuffer: async () => {
if (bodyCache === undefined) {
bodyCache = await readJsonBody<unknown>(req);
}
return bodyCache;
}
});
if (result.status === 204) {
res.statusCode = 204;
res.end();
return;
}
if (result.filePath) {
await sendFile(res, result.status, result.filePath, result.contentType ?? 'application/octet-stream');
return;
}
if (result.rawBody !== undefined) {
sendText(res, result.status, result.rawBody, result.contentType ?? 'text/plain; charset=utf-8');
return;
}
sendJson(res, result.status, result.body);
} catch (error) {
if (!(error instanceof HttpError)) {
console.error('[LocalApi] Request handler error:', error);
}
sendError(res, error);
}
}
export interface StartResult {
ok: boolean;
snapshot: LocalApiSnapshot;
}
export async function startLocalApiServer(settings: LocalApiSettings): Promise<StartResult> {
if (server) {
await stopLocalApiServer();
}
activeSettings = { ...settings, allowedSignalingServers: [...settings.allowedSignalingServers] };
currentStatus = 'starting';
currentError = null;
currentBindHost = pickBindHost(settings);
currentBindPort = settings.port;
const httpServer = createServer((req, res) => {
void handleRequest(req, res, activeSettings ?? settings).catch((error) => {
console.error('[LocalApi] Unhandled request error:', error);
try {
sendError(res, error);
} catch {
// ignore
}
});
});
return await new Promise<StartResult>((resolve) => {
httpServer.once('error', (error) => {
currentStatus = 'error';
currentError = (error as Error).message;
currentBindPort = null;
server = null;
activeSettings = null;
console.error('[LocalApi] Failed to start:', error);
resolve({ ok: false, snapshot: getLocalApiSnapshot() });
});
httpServer.listen(settings.port, pickBindHost(settings), () => {
const address = httpServer.address() as AddressInfo | null;
server = httpServer;
currentStatus = 'running';
currentBindPort = address?.port ?? settings.port;
currentError = null;
console.log(`[LocalApi] Listening on http://${currentBindHost}:${currentBindPort}`);
resolve({ ok: true, snapshot: getLocalApiSnapshot() });
});
});
}
export async function stopLocalApiServer(): Promise<LocalApiSnapshot> {
const httpServer = server;
if (!httpServer) {
currentStatus = 'stopped';
currentBindHost = null;
currentBindPort = null;
activeSettings = null;
return getLocalApiSnapshot();
}
await new Promise<void>((resolve) => {
httpServer.close(() => resolve());
// close() waits for connections; force-close keep-alives so it returns promptly.
httpServer.closeAllConnections?.();
});
server = null;
currentStatus = 'stopped';
currentBindHost = null;
currentBindPort = null;
currentError = null;
activeSettings = null;
clearAllTokens();
console.log('[LocalApi] Stopped');
return getLocalApiSnapshot();
}
export async function applyLocalApiSettings(): Promise<LocalApiSnapshot> {
const settings = readDesktopSettings().localApi;
if (!settings.enabled) {
return await stopLocalApiServer();
}
// If already running with the same bind config, no-op (settings like
// scalarEnabled / allowedSignalingServers are read on every request).
if (
server
&& activeSettings
&& currentStatus === 'running'
&& activeSettings.port === settings.port
&& activeSettings.exposeOnLan === settings.exposeOnLan
) {
activeSettings = { ...settings, allowedSignalingServers: [...settings.allowedSignalingServers] };
return getLocalApiSnapshot();
}
const result = await startLocalApiServer(settings);
return result.snapshot;
}

540
electron/api/openapi.ts Normal file
View File

@@ -0,0 +1,540 @@
export interface OpenApiBuildOptions {
baseUrl: string;
appVersion: string;
}
export function buildOpenApiDocument(options: OpenApiBuildOptions): unknown {
const { baseUrl, appVersion } = options;
const roomIdPathParameter = { name: 'roomId', in: 'path', required: true, schema: { type: 'string' } };
const userIdPathParameter = { name: 'userId', in: 'path', required: true, schema: { type: 'string' } };
const messageIdPathParameter = { name: 'messageId', in: 'path', required: true, schema: { type: 'string' } };
const sinceTimestampQueryParameter = {
name: 'sinceTimestamp',
in: 'query',
required: true,
schema: { type: 'integer', minimum: 0, format: 'int64' }
};
return {
openapi: '3.1.0',
info: {
title: 'MetoYou Local Desktop API',
version: appVersion,
description:
'Authenticated local HTTP API exposed by the MetoYou desktop app. '
+ 'Authentication is performed against a configured signaling server. '
+ 'Bearer tokens issued here are scoped to this device only.'
},
servers: [{ url: baseUrl }],
components: {
securitySchemes: {
bearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'opaque'
}
},
schemas: {
Error: {
type: 'object',
required: ['error'],
properties: {
error: { type: 'string' },
errorCode: { type: 'string' }
}
},
LoginRequest: {
type: 'object',
required: [
'username',
'password',
'serverUrl'
],
properties: {
username: { type: 'string' },
password: { type: 'string' },
serverUrl: {
type: 'string',
format: 'uri',
description: 'Base URL of the signaling server to authenticate against. Must be in the allowed list configured in the desktop app.'
}
}
},
LoginResponse: {
type: 'object',
required: [
'token',
'expiresAt',
'user'
],
properties: {
token: { type: 'string' },
expiresAt: { type: 'integer', format: 'int64' },
user: { $ref: '#/components/schemas/AuthUser' }
}
},
AuthUser: {
type: 'object',
required: [
'id',
'username',
'displayName'
],
properties: {
id: { type: 'string' },
username: { type: 'string' },
displayName: { type: 'string' }
}
},
Profile: {
type: 'object',
properties: {
id: { type: 'string' },
username: { type: 'string' },
displayName: { type: 'string' },
description: { type: 'string' },
avatarUrl: { type: 'string' },
status: { type: 'string' }
}
},
Room: {
type: 'object',
properties: {
id: { type: 'string' },
name: { type: 'string' }
},
additionalProperties: true
},
User: {
type: 'object',
properties: {
id: { type: 'string' },
oderId: { type: 'string' },
username: { type: 'string' },
displayName: { type: 'string' },
status: { type: 'string' },
role: { type: 'string' },
isOnline: { type: 'boolean' }
},
additionalProperties: true
},
Message: {
type: 'object',
properties: {
id: { type: 'string' },
roomId: { type: 'string' },
channelId: { type: 'string' },
senderId: { type: 'string' },
senderName: { type: 'string' },
content: { type: 'string' },
timestamp: { type: 'integer', format: 'int64' },
editedAt: { type: 'integer', format: 'int64' },
isDeleted: { type: 'boolean' }
},
additionalProperties: true
},
Reaction: {
type: 'object',
properties: {
id: { type: 'string' },
messageId: { type: 'string' },
userId: { type: 'string' },
oderId: { type: 'string' },
emoji: { type: 'string' },
timestamp: { type: 'integer', format: 'int64' }
},
additionalProperties: true
},
Attachment: {
type: 'object',
properties: {
id: { type: 'string' },
messageId: { type: 'string' },
filename: { type: 'string' },
size: { type: 'integer' },
mime: { type: 'string' },
isImage: { type: 'boolean' },
filePath: { type: 'string' },
savedPath: { type: 'string' }
},
additionalProperties: true
},
Ban: {
type: 'object',
properties: {
oderId: { type: 'string' },
roomId: { type: 'string' },
userId: { type: 'string' },
bannedBy: { type: 'string' },
displayName: { type: 'string' },
reason: { type: 'string' },
expiresAt: { type: 'integer', format: 'int64' },
timestamp: { type: 'integer', format: 'int64' }
},
additionalProperties: true
},
PluginDataValue: {
type: 'object',
properties: {
value: {}
}
},
MetaValue: {
type: 'object',
properties: {
key: { type: 'string' },
value: { type: ['string', 'null'] }
}
}
}
},
security: [{ bearerAuth: [] }],
paths: {
'/api/health': {
get: {
security: [],
summary: 'Liveness probe',
responses: {
'200': {
description: 'Service is alive',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
status: { type: 'string' },
version: { type: 'string' }
}
}
}
}
}
}
}
},
'/api/openapi.json': {
get: {
security: [],
summary: 'OpenAPI specification',
responses: { '200': { description: 'This document' } }
}
},
'/api/auth/login': {
post: {
security: [],
summary: 'Exchange username/password (validated by a signaling server) for a bearer token',
requestBody: {
required: true,
content: {
'application/json': {
schema: { $ref: '#/components/schemas/LoginRequest' }
}
}
},
responses: {
'200': {
description: 'Token issued',
content: {
'application/json': {
schema: { $ref: '#/components/schemas/LoginResponse' }
}
}
},
'401': {
description: 'Invalid credentials',
content: {
'application/json': { schema: { $ref: '#/components/schemas/Error' } }
}
},
'403': {
description: 'Signaling server URL not allowed',
content: {
'application/json': { schema: { $ref: '#/components/schemas/Error' } }
}
}
}
}
},
'/api/auth/logout': {
post: {
summary: 'Revoke the current bearer token',
responses: { '204': { description: 'Token revoked' } }
}
},
'/api/profile': {
get: {
summary: 'Get the current user profile',
responses: {
'200': {
description: 'Current user profile',
content: {
'application/json': {
schema: { $ref: '#/components/schemas/Profile' }
}
}
},
'404': {
description: 'No current user is set on this device',
content: {
'application/json': { schema: { $ref: '#/components/schemas/Error' } }
}
}
}
}
},
'/api/rooms': {
get: {
summary: 'List rooms (servers) known to this device',
responses: {
'200': {
description: 'Rooms array',
content: {
'application/json': {
schema: {
type: 'array',
items: { $ref: '#/components/schemas/Room' }
}
}
}
}
}
}
},
'/api/rooms/{roomId}': {
get: {
summary: 'Get a room by id',
parameters: [roomIdPathParameter],
responses: {
'200': {
description: 'Room details',
content: {
'application/json': {
schema: { $ref: '#/components/schemas/Room' }
}
}
},
'404': {
description: 'Room not found',
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } }
}
}
}
},
'/api/rooms/{roomId}/users': {
get: {
summary: 'List users known for a room',
parameters: [roomIdPathParameter],
responses: {
'200': {
description: 'Users array',
content: {
'application/json': {
schema: { type: 'array', items: { $ref: '#/components/schemas/User' } }
}
}
}
}
}
},
'/api/rooms/{roomId}/messages': {
get: {
summary: 'List messages for a room',
parameters: [
roomIdPathParameter,
{ name: 'limit', in: 'query', required: false, schema: { type: 'integer', minimum: 1, maximum: 500 } },
{ name: 'offset', in: 'query', required: false, schema: { type: 'integer', minimum: 0 } }
],
responses: {
'200': {
description: 'Messages array',
content: {
'application/json': {
schema: {
type: 'array',
items: { $ref: '#/components/schemas/Message' }
}
}
}
}
}
}
},
'/api/rooms/{roomId}/messages/since': {
get: {
summary: 'List room messages after a timestamp',
parameters: [roomIdPathParameter, sinceTimestampQueryParameter],
responses: {
'200': {
description: 'Messages array',
content: {
'application/json': {
schema: { type: 'array', items: { $ref: '#/components/schemas/Message' } }
}
}
}
}
}
},
'/api/rooms/{roomId}/bans': {
get: {
summary: 'List active bans for a room',
parameters: [roomIdPathParameter],
responses: {
'200': {
description: 'Bans array',
content: {
'application/json': {
schema: { type: 'array', items: { $ref: '#/components/schemas/Ban' } }
}
}
}
}
}
},
'/api/rooms/{roomId}/bans/{userId}': {
get: {
summary: 'Check whether a user is banned in a room',
parameters: [roomIdPathParameter, userIdPathParameter],
responses: {
'200': {
description: 'Ban status',
content: {
'application/json': {
schema: {
type: 'object',
required: ['isBanned'],
properties: { isBanned: { type: 'boolean' } }
}
}
}
}
}
}
},
'/api/messages/{messageId}': {
get: {
summary: 'Get a message by id',
parameters: [messageIdPathParameter],
responses: {
'200': {
description: 'Message details',
content: {
'application/json': {
schema: { $ref: '#/components/schemas/Message' }
}
}
},
'404': {
description: 'Message not found',
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } }
}
}
}
},
'/api/messages/{messageId}/reactions': {
get: {
summary: 'List reactions for a message',
parameters: [messageIdPathParameter],
responses: {
'200': {
description: 'Reactions array',
content: {
'application/json': {
schema: { type: 'array', items: { $ref: '#/components/schemas/Reaction' } }
}
}
}
}
}
},
'/api/messages/{messageId}/attachments': {
get: {
summary: 'List attachments for a message',
parameters: [messageIdPathParameter],
responses: {
'200': {
description: 'Attachments array',
content: {
'application/json': {
schema: { type: 'array', items: { $ref: '#/components/schemas/Attachment' } }
}
}
}
}
}
},
'/api/users/{userId}': {
get: {
summary: 'Get a user by id',
parameters: [userIdPathParameter],
responses: {
'200': {
description: 'User details',
content: {
'application/json': {
schema: { $ref: '#/components/schemas/User' }
}
}
},
'404': {
description: 'User not found',
content: { 'application/json': { schema: { $ref: '#/components/schemas/Error' } } }
}
}
}
},
'/api/attachments': {
get: {
summary: 'List all attachments stored on this device',
responses: {
'200': {
description: 'Attachments array',
content: {
'application/json': {
schema: { type: 'array', items: { $ref: '#/components/schemas/Attachment' } }
}
}
}
}
}
},
'/api/plugin-data': {
get: {
summary: 'Read a plugin data value',
parameters: [
{ name: 'pluginId', in: 'query', required: true, schema: { type: 'string' } },
{ name: 'key', in: 'query', required: true, schema: { type: 'string' } },
{ name: 'scope', in: 'query', required: true, schema: { type: 'string', enum: ['local', 'server'] } },
{ name: 'serverId', in: 'query', required: false, schema: { type: 'string' } }
],
responses: {
'200': {
description: 'Plugin data value',
content: {
'application/json': {
schema: { $ref: '#/components/schemas/PluginDataValue' }
}
}
}
}
}
},
'/api/meta/{key}': {
get: {
summary: 'Read a desktop metadata value',
parameters: [{ name: 'key', in: 'path', required: true, schema: { type: 'string' } }],
responses: {
'200': {
description: 'Metadata value',
content: {
'application/json': {
schema: { $ref: '#/components/schemas/MetaValue' }
}
}
}
}
}
}
}
};
}

511
electron/api/router.ts Normal file
View File

@@ -0,0 +1,511 @@
import { app, net } from 'electron';
import { DataSource } from 'typeorm';
import { buildQueryHandlers } from '../cqrs/queries';
import {
QueryType,
QueryTypeKey,
Query
} from '../cqrs/types';
import {
issueToken,
consumeToken,
revokeToken,
IssuedToken
} from './auth-store';
import { buildOpenApiDocument } from './openapi';
import { HttpError, RequestContext } from './http-helpers';
import { getDocsHtml, getScalarApiReferenceBundlePath } from './docs-html';
import { resolveDocusaurusRoute } from './docusaurus-static';
import { LocalApiSettings } from '../desktop-settings';
export interface RouteResponse {
status: number;
body: unknown;
contentType?: string;
filePath?: string;
rawBody?: string;
}
export interface RouteContext {
request: RequestContext;
settings: LocalApiSettings;
baseUrl: string;
dataSource: DataSource | null;
bodyBuffer: () => Promise<unknown>;
}
type RouteHandler = (context: RouteContext) => Promise<RouteResponse>;
interface RouteMatch {
handler: RouteHandler;
params: Record<string, string>;
requiresAuth: boolean;
requiresDatabase: boolean;
}
interface RouteDefinition {
method: string;
pattern: RegExp;
paramKeys: string[];
handler: RouteHandler;
requiresAuth: boolean;
requiresDatabase: boolean;
}
function compilePattern(template: string): { pattern: RegExp; paramKeys: string[] } {
const paramKeys: string[] = [];
const escaped = template.replace(/[.*+?^${}()|[\]\\]/g, (match) => {
if (match === '*' || match === '+' || match === '?')
return `\\${match}`;
return `\\${match}`;
});
const source = template.replace(/\{([^}]+)\}/g, (_full, key: string) => {
paramKeys.push(key);
return '([^/]+)';
});
void escaped;
return { pattern: new RegExp(`^${source}$`), paramKeys };
}
function defineRoute(method: string, template: string, handler: RouteHandler, requiresAuth: boolean, requiresDatabase = true): RouteDefinition {
const compiled = compilePattern(template);
return { method: method.toUpperCase(), pattern: compiled.pattern, paramKeys: compiled.paramKeys, handler, requiresAuth, requiresDatabase };
}
function runQuery<T>(dataSource: DataSource, query: Query): Promise<T> {
const handlers = buildQueryHandlers(dataSource) as Record<QueryTypeKey, (q: Query) => Promise<unknown>>;
const handler = handlers[query.type as QueryTypeKey];
if (!handler) {
throw new HttpError(500, `No handler registered for query: ${query.type}`, 'UNKNOWN_QUERY');
}
return handler(query) as Promise<T>;
}
function requireDataSource(dataSource: DataSource | null): DataSource {
if (!dataSource) {
throw new HttpError(503, 'Database not initialised', 'DB_UNAVAILABLE');
}
return dataSource;
}
function clampInt(value: unknown, min: number, max: number, fallback: number): number {
const parsed = typeof value === 'string' ? Number(value) : NaN;
if (!Number.isFinite(parsed))
return fallback;
return Math.max(min, Math.min(max, Math.floor(parsed)));
}
function getTrailingPathParam(pathname: string, pattern: RegExp, name: string): string {
const value = pattern.exec(pathname)?.[1];
if (!value) {
throw new HttpError(400, `${name} is required`, 'INVALID_REQUEST');
}
return decodeURIComponent(value);
}
function getRequiredQueryParam(ctx: RouteContext, name: string): string {
const value = ctx.request.url.searchParams.get(name)?.trim() ?? '';
if (!value) {
throw new HttpError(400, `${name} is required`, 'INVALID_REQUEST');
}
return value;
}
function getRequiredTimestamp(ctx: RouteContext, name: string): number {
const raw = getRequiredQueryParam(ctx, name);
const value = Number(raw);
if (!Number.isFinite(value) || value < 0) {
throw new HttpError(400, `${name} must be a non-negative timestamp`, 'INVALID_REQUEST');
}
return Math.floor(value);
}
const ROUTES: RouteDefinition[] = [
defineRoute('GET', '/api/health', async (ctx): Promise<RouteResponse> => ({
status: 200,
body: { status: 'ok', version: app.getVersion(), timestamp: Date.now(), exposeOnLan: ctx.settings.exposeOnLan }
}), false, false),
defineRoute('GET', '/api/openapi.json', async (ctx): Promise<RouteResponse> => ({
status: 200,
body: buildOpenApiDocument({ baseUrl: ctx.baseUrl, appVersion: app.getVersion() })
}), false, false),
defineRoute('GET', '/docs', async (ctx): Promise<RouteResponse> => {
if (!ctx.settings.scalarEnabled) {
return {
status: 404,
body: null,
contentType: 'text/plain; charset=utf-8',
rawBody: 'API documentation is disabled. Enable Scalar in desktop settings to view it.'
};
}
return {
status: 200,
body: null,
contentType: 'text/html; charset=utf-8',
rawBody: getDocsHtml(`${ctx.baseUrl}/api/openapi.json`)
};
}, false, false),
defineRoute('GET', '/docusaurus(?:/.*)?', async (ctx): Promise<RouteResponse> => {
if (!ctx.settings.docusaurusEnabled) {
return {
status: 404,
body: null,
contentType: 'text/plain; charset=utf-8',
rawBody: 'Docusaurus documentation is disabled. Open documentation from the desktop app to activate it.'
};
}
const docsRoute = await resolveDocusaurusRoute(ctx.request.pathname);
return {
status: 200,
body: null,
contentType: docsRoute.contentType,
filePath: docsRoute.filePath
};
}, false, false),
defineRoute('GET', '/scalar/api-reference.js', async (ctx): Promise<RouteResponse> => {
if (!ctx.settings.scalarEnabled) {
return {
status: 404,
body: null,
contentType: 'text/plain; charset=utf-8',
rawBody: 'API documentation is disabled. Enable Scalar in desktop settings to view it.'
};
}
const bundlePath = await getScalarApiReferenceBundlePath();
if (!bundlePath) {
throw new HttpError(503, 'Scalar API reference bundle is not available in this build', 'SCALAR_BUNDLE_MISSING');
}
return {
status: 200,
body: null,
contentType: 'application/javascript; charset=utf-8',
filePath: bundlePath
};
}, false, false),
defineRoute('POST', '/api/auth/login', async (ctx): Promise<RouteResponse> => {
const body = await ctx.bodyBuffer() as { username?: unknown; password?: unknown; serverUrl?: unknown };
const username = typeof body.username === 'string' ? body.username.trim() : '';
const password = typeof body.password === 'string' ? body.password : '';
const serverUrl = typeof body.serverUrl === 'string' ? body.serverUrl.trim().replace(/\/+$/u, '') : '';
if (!username || !password || !serverUrl) {
throw new HttpError(400, 'username, password, and serverUrl are required', 'INVALID_REQUEST');
}
if (!/^https?:\/\//iu.test(serverUrl)) {
throw new HttpError(400, 'serverUrl must be an http or https URL', 'INVALID_REQUEST');
}
if (ctx.settings.allowedSignalingServers.length === 0) {
throw new HttpError(403, 'No signaling servers are allowed for local API authentication. Add one in desktop settings.', 'NO_ALLOWED_SERVERS');
}
if (!ctx.settings.allowedSignalingServers.includes(serverUrl)) {
throw new HttpError(403, 'Signaling server URL is not in the allowed list', 'SERVER_NOT_ALLOWED');
}
let response: Response;
try {
response = await net.fetch(`${serverUrl}/api/users/login`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username, password })
});
} catch (error) {
throw new HttpError(502, `Failed to reach signaling server: ${(error as Error).message}`, 'UPSTREAM_UNREACHABLE');
}
if (response.status === 401 || response.status === 403) {
throw new HttpError(401, 'Invalid credentials', 'INVALID_CREDENTIALS');
}
if (!response.ok) {
throw new HttpError(502, `Signaling server rejected login (${response.status})`, 'UPSTREAM_ERROR');
}
const remote = await response.json() as { id?: string; username?: string; displayName?: string };
if (!remote.id || !remote.username) {
throw new HttpError(502, 'Signaling server returned an unexpected response', 'UPSTREAM_BAD_RESPONSE');
}
const issued = issueToken({
userId: remote.id,
username: remote.username,
displayName: remote.displayName ?? remote.username,
signalingServerUrl: serverUrl
});
return {
status: 200,
body: {
token: issued.token,
expiresAt: issued.expiresAt,
user: {
id: issued.userId,
username: issued.username,
displayName: issued.displayName
}
}
};
}, false),
defineRoute('POST', '/api/auth/logout', async (ctx): Promise<RouteResponse> => {
if (ctx.request.bearerToken) {
revokeToken(ctx.request.bearerToken);
}
return { status: 204, body: null };
}, true),
defineRoute('GET', '/api/profile', async (ctx): Promise<RouteResponse> => {
const user = await runQuery<unknown>(requireDataSource(ctx.dataSource), {
type: QueryType.GetCurrentUser,
payload: {}
});
if (!user) {
throw new HttpError(404, 'No current user is set on this device', 'NO_CURRENT_USER');
}
return { status: 200, body: user };
}, true),
defineRoute('GET', '/api/rooms', async (ctx): Promise<RouteResponse> => {
const rooms = await runQuery<unknown[]>(requireDataSource(ctx.dataSource), {
type: QueryType.GetAllRooms,
payload: {}
});
return { status: 200, body: rooms ?? [] };
}, true),
defineRoute('GET', '/api/rooms/{roomId}', async (ctx): Promise<RouteResponse> => {
const roomId = getTrailingPathParam(ctx.request.pathname, /\/api\/rooms\/([^/]+)$/u, 'roomId');
const room = await runQuery<unknown>(requireDataSource(ctx.dataSource), {
type: QueryType.GetRoom,
payload: { roomId }
});
if (!room) {
throw new HttpError(404, 'Room not found on this device', 'ROOM_NOT_FOUND');
}
return { status: 200, body: room };
}, true),
defineRoute('GET', '/api/rooms/{roomId}/users', async (ctx): Promise<RouteResponse> => {
const roomId = getTrailingPathParam(ctx.request.pathname, /\/api\/rooms\/([^/]+)\/users$/u, 'roomId');
const users = await runQuery<unknown[]>(requireDataSource(ctx.dataSource), {
type: QueryType.GetUsersByRoom,
payload: { roomId }
});
return { status: 200, body: users ?? [] };
}, true),
defineRoute('GET', '/api/rooms/{roomId}/messages', async (ctx): Promise<RouteResponse> => {
const roomId = getTrailingPathParam(ctx.request.pathname, /\/api\/rooms\/([^/]+)\/messages$/u, 'roomId');
const limit = clampInt(ctx.request.url.searchParams.get('limit'), 1, 500, 100);
const offset = clampInt(ctx.request.url.searchParams.get('offset'), 0, Number.MAX_SAFE_INTEGER, 0);
const messages = await runQuery<unknown[]>(requireDataSource(ctx.dataSource), {
type: QueryType.GetMessages,
payload: { roomId, limit, offset }
});
return { status: 200, body: messages ?? [] };
}, true),
defineRoute('GET', '/api/rooms/{roomId}/messages/since', async (ctx): Promise<RouteResponse> => {
const roomId = getTrailingPathParam(ctx.request.pathname, /\/api\/rooms\/([^/]+)\/messages\/since$/u, 'roomId');
const sinceTimestamp = getRequiredTimestamp(ctx, 'sinceTimestamp');
const messages = await runQuery<unknown[]>(requireDataSource(ctx.dataSource), {
type: QueryType.GetMessagesSince,
payload: { roomId, sinceTimestamp }
});
return { status: 200, body: messages ?? [] };
}, true),
defineRoute('GET', '/api/rooms/{roomId}/bans', async (ctx): Promise<RouteResponse> => {
const roomId = getTrailingPathParam(ctx.request.pathname, /\/api\/rooms\/([^/]+)\/bans$/u, 'roomId');
const bans = await runQuery<unknown[]>(requireDataSource(ctx.dataSource), {
type: QueryType.GetBansForRoom,
payload: { roomId }
});
return { status: 200, body: bans ?? [] };
}, true),
defineRoute('GET', '/api/rooms/{roomId}/bans/{userId}', async (ctx): Promise<RouteResponse> => {
const match = /\/api\/rooms\/([^/]+)\/bans\/([^/]+)$/u.exec(ctx.request.pathname);
if (!match) {
throw new HttpError(400, 'roomId and userId are required', 'INVALID_REQUEST');
}
const isBanned = await runQuery<boolean>(requireDataSource(ctx.dataSource), {
type: QueryType.IsUserBanned,
payload: { roomId: decodeURIComponent(match[1]), userId: decodeURIComponent(match[2]) }
});
return { status: 200, body: { isBanned } };
}, true),
defineRoute('GET', '/api/messages/{messageId}', async (ctx): Promise<RouteResponse> => {
const messageId = getTrailingPathParam(ctx.request.pathname, /\/api\/messages\/([^/]+)$/u, 'messageId');
const message = await runQuery<unknown>(requireDataSource(ctx.dataSource), {
type: QueryType.GetMessageById,
payload: { messageId }
});
if (!message) {
throw new HttpError(404, 'Message not found on this device', 'MESSAGE_NOT_FOUND');
}
return { status: 200, body: message };
}, true),
defineRoute('GET', '/api/messages/{messageId}/reactions', async (ctx): Promise<RouteResponse> => {
const messageId = getTrailingPathParam(ctx.request.pathname, /\/api\/messages\/([^/]+)\/reactions$/u, 'messageId');
const reactions = await runQuery<unknown[]>(requireDataSource(ctx.dataSource), {
type: QueryType.GetReactionsForMessage,
payload: { messageId }
});
return { status: 200, body: reactions ?? [] };
}, true),
defineRoute('GET', '/api/messages/{messageId}/attachments', async (ctx): Promise<RouteResponse> => {
const messageId = getTrailingPathParam(ctx.request.pathname, /\/api\/messages\/([^/]+)\/attachments$/u, 'messageId');
const attachments = await runQuery<unknown[]>(requireDataSource(ctx.dataSource), {
type: QueryType.GetAttachmentsForMessage,
payload: { messageId }
});
return { status: 200, body: attachments ?? [] };
}, true),
defineRoute('GET', '/api/users/{userId}', async (ctx): Promise<RouteResponse> => {
const userId = getTrailingPathParam(ctx.request.pathname, /\/api\/users\/([^/]+)$/u, 'userId');
const user = await runQuery<unknown>(requireDataSource(ctx.dataSource), {
type: QueryType.GetUser,
payload: { userId }
});
if (!user) {
throw new HttpError(404, 'User not found on this device', 'USER_NOT_FOUND');
}
return { status: 200, body: user };
}, true),
defineRoute('GET', '/api/attachments', async (ctx): Promise<RouteResponse> => {
const attachments = await runQuery<unknown[]>(requireDataSource(ctx.dataSource), {
type: QueryType.GetAllAttachments,
payload: {}
});
return { status: 200, body: attachments ?? [] };
}, true),
defineRoute('GET', '/api/plugin-data', async (ctx): Promise<RouteResponse> => {
const pluginId = getRequiredQueryParam(ctx, 'pluginId');
const key = getRequiredQueryParam(ctx, 'key');
const scope = getRequiredQueryParam(ctx, 'scope');
if (scope !== 'local' && scope !== 'server') {
throw new HttpError(400, 'scope must be local or server', 'INVALID_REQUEST');
}
const value = await runQuery<unknown>(requireDataSource(ctx.dataSource), {
type: QueryType.GetPluginData,
payload: {
key,
pluginId,
scope,
serverId: ctx.request.url.searchParams.get('serverId') ?? undefined
}
});
return { status: 200, body: { value } };
}, true),
defineRoute('GET', '/api/meta/{key}', async (ctx): Promise<RouteResponse> => {
const key = getTrailingPathParam(ctx.request.pathname, /\/api\/meta\/([^/]+)$/u, 'key');
const value = await runQuery<string | null>(requireDataSource(ctx.dataSource), {
type: QueryType.GetMeta,
payload: { key }
});
return { status: 200, body: { key, value } };
}, true)
];
export interface RoutingResult {
match: RouteMatch | null;
methodNotAllowed: boolean;
}
export function matchRoute(method: string, pathname: string): RoutingResult {
let methodNotAllowed = false;
for (const route of ROUTES) {
const result = route.pattern.exec(pathname);
if (!result)
continue;
if (route.method !== method) {
methodNotAllowed = true;
continue;
}
const params: Record<string, string> = {};
for (let index = 0; index < route.paramKeys.length; index++) {
params[route.paramKeys[index]] = result[index + 1];
}
return {
match: { handler: route.handler, params, requiresAuth: route.requiresAuth, requiresDatabase: route.requiresDatabase },
methodNotAllowed: false
};
}
return { match: null, methodNotAllowed };
}
export function authenticate(token: string | null): IssuedToken | null {
if (!token)
return null;
return consumeToken(token);
}

View File

@@ -5,6 +5,7 @@ import { createWindow, getMainWindow } from '../window/create-window';
const CUSTOM_PROTOCOL = 'toju'; const CUSTOM_PROTOCOL = 'toju';
const DEEP_LINK_PREFIX = `${CUSTOM_PROTOCOL}://`; const DEEP_LINK_PREFIX = `${CUSTOM_PROTOCOL}://`;
const DEV_SINGLE_INSTANCE_EXIT_CODE_ENV = 'METOYOU_SINGLE_INSTANCE_EXIT_CODE'; const DEV_SINGLE_INSTANCE_EXIT_CODE_ENV = 'METOYOU_SINGLE_INSTANCE_EXIT_CODE';
const DEV_RELOAD_EXISTING_ARG = '--metoyou-dev-reload-existing';
let pendingDeepLink: string | null = null; let pendingDeepLink: string | null = null;
@@ -95,6 +96,12 @@ export function initializeDeepLinkHandling(): boolean {
} }
app.on('second-instance', (_event, argv) => { app.on('second-instance', (_event, argv) => {
if (resolveDevSingleInstanceExitCode() != null && argv.includes(DEV_RELOAD_EXISTING_ARG)) {
app.relaunch();
app.exit(0);
return;
}
focusMainWindow(); focusMainWindow();
const deepLink = extractDeepLink(argv); const deepLink = extractDeepLink(argv);

View File

@@ -2,6 +2,7 @@ import { app, BrowserWindow } from 'electron';
import { cleanupLinuxScreenShareAudioRouting } from '../audio/linux-screen-share-routing'; import { cleanupLinuxScreenShareAudioRouting } from '../audio/linux-screen-share-routing';
import { initializeDesktopUpdater, shutdownDesktopUpdater } from '../update/desktop-updater'; import { initializeDesktopUpdater, shutdownDesktopUpdater } from '../update/desktop-updater';
import { synchronizeAutoStartSetting } from './auto-start'; import { synchronizeAutoStartSetting } from './auto-start';
import { applyLocalApiSettings, stopLocalApiServer } from '../api';
import { import {
initializeDatabase, initializeDatabase,
destroyDatabase, destroyDatabase,
@@ -21,6 +22,14 @@ import {
} from '../ipc'; } from '../ipc';
import { startIdleMonitor, stopIdleMonitor } from '../idle/idle-monitor'; import { startIdleMonitor, stopIdleMonitor } from '../idle/idle-monitor';
function startLocalApiAfterWindowReady(): void {
setImmediate(() => {
void applyLocalApiSettings().catch((error: unknown) => {
console.error('[LocalApi] Failed to apply settings after window startup:', error);
});
});
}
export function registerAppLifecycle(): void { export function registerAppLifecycle(): void {
app.whenReady().then(async () => { app.whenReady().then(async () => {
const dockIconPath = getDockIconPath(); const dockIconPath = getDockIconPath();
@@ -35,6 +44,7 @@ export function registerAppLifecycle(): void {
await synchronizeAutoStartSetting(); await synchronizeAutoStartSetting();
initializeDesktopUpdater(); initializeDesktopUpdater();
await createWindow(); await createWindow();
startLocalApiAfterWindowReady();
startIdleMonitor(); startIdleMonitor();
app.on('activate', () => { app.on('activate', () => {
@@ -60,6 +70,7 @@ export function registerAppLifecycle(): void {
event.preventDefault(); event.preventDefault();
shutdownDesktopUpdater(); shutdownDesktopUpdater();
stopIdleMonitor(); stopIdleMonitor();
await stopLocalApiServer();
await cleanupLinuxScreenShareAudioRouting(); await cleanupLinuxScreenShareAudioRouting();
await destroyDatabase(); await destroyDatabase();
app.quit(); app.quit();

View File

@@ -11,7 +11,8 @@ import {
ReactionEntity, ReactionEntity,
BanEntity, BanEntity,
AttachmentEntity, AttachmentEntity,
MetaEntity MetaEntity,
PluginDataEntity
} from '../../../entities'; } from '../../../entities';
export async function handleClearAllData(dataSource: DataSource): Promise<void> { export async function handleClearAllData(dataSource: DataSource): Promise<void> {
@@ -27,4 +28,5 @@ export async function handleClearAllData(dataSource: DataSource): Promise<void>
await dataSource.getRepository(BanEntity).clear(); await dataSource.getRepository(BanEntity).clear();
await dataSource.getRepository(AttachmentEntity).clear(); await dataSource.getRepository(AttachmentEntity).clear();
await dataSource.getRepository(MetaEntity).clear(); await dataSource.getRepository(MetaEntity).clear();
await dataSource.getRepository(PluginDataEntity).clear();
} }

View File

@@ -1,9 +1,15 @@
import { DataSource } from 'typeorm'; import { DataSource } from 'typeorm';
import { MessageEntity } from '../../../entities'; import { MessageEntity } from '../../../entities';
import { ClearRoomMessagesCommand } from '../../types'; import { ClearRoomMessagesCommand } from '../../types';
import { getCurrentUserScope } from '../../current-user-scope';
export async function handleClearRoomMessages(command: ClearRoomMessagesCommand, dataSource: DataSource): Promise<void> { export async function handleClearRoomMessages(command: ClearRoomMessagesCommand, dataSource: DataSource): Promise<void> {
const repo = dataSource.getRepository(MessageEntity); const repo = dataSource.getRepository(MessageEntity);
const currentUserId = await getCurrentUserScope(dataSource);
await repo.delete({ roomId: command.payload.roomId }); if (!currentUserId) {
return;
}
await repo.delete({ roomId: command.payload.roomId, ownerUserId: currentUserId });
} }

View File

@@ -1,9 +1,15 @@
import { DataSource } from 'typeorm'; import { DataSource } from 'typeorm';
import { MessageEntity } from '../../../entities'; import { MessageEntity } from '../../../entities';
import { DeleteMessageCommand } from '../../types'; import { DeleteMessageCommand } from '../../types';
import { getCurrentUserScope } from '../../current-user-scope';
export async function handleDeleteMessage(command: DeleteMessageCommand, dataSource: DataSource): Promise<void> { export async function handleDeleteMessage(command: DeleteMessageCommand, dataSource: DataSource): Promise<void> {
const repo = dataSource.getRepository(MessageEntity); const repo = dataSource.getRepository(MessageEntity);
const currentUserId = await getCurrentUserScope(dataSource);
await repo.delete({ id: command.payload.messageId }); if (!currentUserId) {
return;
}
await repo.delete({ id: command.payload.messageId, ownerUserId: currentUserId });
} }

View File

@@ -0,0 +1,21 @@
import { DataSource } from 'typeorm';
import { getCurrentUserScope } from '../../current-user-scope';
import { PluginDataEntity } from '../../../entities';
import { DeletePluginDataCommand } from '../../types';
export async function handleDeletePluginData(command: DeletePluginDataCommand, dataSource: DataSource): Promise<void> {
const { payload } = command;
const ownerUserId = await getCurrentUserScope(dataSource);
if (!ownerUserId) {
return;
}
await dataSource.getRepository(PluginDataEntity).delete({
key: payload.key,
ownerUserId,
pluginId: payload.pluginId,
scope: payload.scope,
serverId: payload.serverId ?? ''
});
}

View File

@@ -3,23 +3,39 @@ import {
RoomChannelPermissionEntity, RoomChannelPermissionEntity,
RoomChannelEntity, RoomChannelEntity,
RoomEntity, RoomEntity,
RoomOwnerEntity,
RoomMemberEntity, RoomMemberEntity,
RoomRoleEntity, RoomRoleEntity,
RoomUserRoleEntity, RoomUserRoleEntity,
MessageEntity MessageEntity
} from '../../../entities'; } from '../../../entities';
import { DeleteRoomCommand } from '../../types'; import { DeleteRoomCommand } from '../../types';
import { getCurrentUserScope } from '../../current-user-scope';
export async function handleDeleteRoom(command: DeleteRoomCommand, dataSource: DataSource): Promise<void> { export async function handleDeleteRoom(command: DeleteRoomCommand, dataSource: DataSource): Promise<void> {
const { roomId } = command.payload; const { roomId } = command.payload;
await dataSource.transaction(async (manager) => { await dataSource.transaction(async (manager) => {
const currentUserId = await getCurrentUserScope(manager);
if (!currentUserId) {
return;
}
await manager.getRepository(RoomOwnerEntity).delete({ roomId, userId: currentUserId });
await manager.getRepository(MessageEntity).delete({ roomId, ownerUserId: currentUserId });
const remainingOwners = await manager.getRepository(RoomOwnerEntity).count({ where: { roomId } });
if (remainingOwners > 0) {
return;
}
await manager.getRepository(RoomChannelPermissionEntity).delete({ roomId }); await manager.getRepository(RoomChannelPermissionEntity).delete({ roomId });
await manager.getRepository(RoomChannelEntity).delete({ roomId }); await manager.getRepository(RoomChannelEntity).delete({ roomId });
await manager.getRepository(RoomMemberEntity).delete({ roomId }); await manager.getRepository(RoomMemberEntity).delete({ roomId });
await manager.getRepository(RoomRoleEntity).delete({ roomId }); await manager.getRepository(RoomRoleEntity).delete({ roomId });
await manager.getRepository(RoomUserRoleEntity).delete({ roomId }); await manager.getRepository(RoomUserRoleEntity).delete({ roomId });
await manager.getRepository(RoomEntity).delete({ id: roomId }); await manager.getRepository(RoomEntity).delete({ id: roomId });
await manager.getRepository(MessageEntity).delete({ roomId });
}); });
} }

View File

@@ -2,15 +2,18 @@ import { DataSource } from 'typeorm';
import { MessageEntity } from '../../../entities'; import { MessageEntity } from '../../../entities';
import { replaceMessageReactions } from '../../relations'; import { replaceMessageReactions } from '../../relations';
import { SaveMessageCommand } from '../../types'; import { SaveMessageCommand } from '../../types';
import { getCurrentUserScope } from '../../current-user-scope';
export async function handleSaveMessage(command: SaveMessageCommand, dataSource: DataSource): Promise<void> { export async function handleSaveMessage(command: SaveMessageCommand, dataSource: DataSource): Promise<void> {
const { message } = command.payload; const { message } = command.payload;
await dataSource.transaction(async (manager) => { await dataSource.transaction(async (manager) => {
const currentUserId = await getCurrentUserScope(manager);
const repo = manager.getRepository(MessageEntity); const repo = manager.getRepository(MessageEntity);
const entity = repo.create({ const entity = repo.create({
id: message.id, id: message.id,
roomId: message.roomId, roomId: message.roomId,
ownerUserId: currentUserId,
channelId: message.channelId ?? null, channelId: message.channelId ?? null,
senderId: message.senderId, senderId: message.senderId,
senderName: message.senderName, senderName: message.senderName,

View File

@@ -0,0 +1,10 @@
import { DataSource } from 'typeorm';
import { MetaEntity } from '../../../entities';
import { SaveMetaCommand } from '../../types';
export async function handleSaveMeta(command: SaveMetaCommand, dataSource: DataSource): Promise<void> {
await dataSource.getRepository(MetaEntity).save({
key: command.payload.key,
value: command.payload.value
});
}

View File

@@ -0,0 +1,23 @@
import { DataSource } from 'typeorm';
import { getCurrentUserScope } from '../../current-user-scope';
import { PluginDataEntity } from '../../../entities';
import { SavePluginDataCommand } from '../../types';
export async function handleSavePluginData(command: SavePluginDataCommand, dataSource: DataSource): Promise<void> {
const { payload } = command;
const ownerUserId = await getCurrentUserScope(dataSource);
if (!ownerUserId) {
return;
}
await dataSource.getRepository(PluginDataEntity).save({
key: payload.key,
ownerUserId,
pluginId: payload.pluginId,
scope: payload.scope,
serverId: payload.serverId ?? '',
updatedAt: Date.now(),
valueJson: JSON.stringify(payload.value ?? null)
});
}

View File

@@ -1,7 +1,8 @@
import { DataSource } from 'typeorm'; import { DataSource } from 'typeorm';
import { RoomEntity } from '../../../entities'; import { RoomEntity, RoomOwnerEntity } from '../../../entities';
import { replaceRoomRelations } from '../../relations'; import { replaceRoomRelations } from '../../relations';
import { SaveRoomCommand } from '../../types'; import { SaveRoomCommand } from '../../types';
import { getCurrentUserScope } from '../../current-user-scope';
function extractSlowModeInterval(room: SaveRoomCommand['payload']['room']): number { function extractSlowModeInterval(room: SaveRoomCommand['payload']['room']): number {
if (typeof room.slowModeInterval === 'number' && Number.isFinite(room.slowModeInterval)) { if (typeof room.slowModeInterval === 'number' && Number.isFinite(room.slowModeInterval)) {
@@ -21,6 +22,7 @@ export async function handleSaveRoom(command: SaveRoomCommand, dataSource: DataS
const { room } = command.payload; const { room } = command.payload;
await dataSource.transaction(async (manager) => { await dataSource.transaction(async (manager) => {
const currentUserId = await getCurrentUserScope(manager);
const repo = manager.getRepository(RoomEntity); const repo = manager.getRepository(RoomEntity);
const entity = repo.create({ const entity = repo.create({
id: room.id, id: room.id,
@@ -43,6 +45,15 @@ export async function handleSaveRoom(command: SaveRoomCommand, dataSource: DataS
}); });
await repo.save(entity); await repo.save(entity);
if (currentUserId) {
await manager.getRepository(RoomOwnerEntity).save({
roomId: room.id,
userId: currentUserId,
savedAt: Date.now()
});
}
await replaceRoomRelations(manager, room.id, { await replaceRoomRelations(manager, room.id, {
channels: room.channels ?? [], channels: room.channels ?? [],
members: room.members ?? [], members: room.members ?? [],

View File

@@ -2,13 +2,20 @@ import { DataSource } from 'typeorm';
import { MessageEntity } from '../../../entities'; import { MessageEntity } from '../../../entities';
import { replaceMessageReactions } from '../../relations'; import { replaceMessageReactions } from '../../relations';
import { UpdateMessageCommand } from '../../types'; import { UpdateMessageCommand } from '../../types';
import { getCurrentUserScope } from '../../current-user-scope';
export async function handleUpdateMessage(command: UpdateMessageCommand, dataSource: DataSource): Promise<void> { export async function handleUpdateMessage(command: UpdateMessageCommand, dataSource: DataSource): Promise<void> {
const { messageId, updates } = command.payload; const { messageId, updates } = command.payload;
await dataSource.transaction(async (manager) => { await dataSource.transaction(async (manager) => {
const currentUserId = await getCurrentUserScope(manager);
if (!currentUserId) {
return;
}
const repo = manager.getRepository(MessageEntity); const repo = manager.getRepository(MessageEntity);
const existing = await repo.findOne({ where: { id: messageId } }); const existing = await repo.findOne({ where: { id: messageId, ownerUserId: currentUserId } });
if (!existing) if (!existing)
return; return;

View File

@@ -7,6 +7,7 @@ import {
boolToInt, boolToInt,
TransformMap TransformMap
} from './utils/applyUpdates'; } from './utils/applyUpdates';
import { getCurrentUserScope, userOwnsRoom } from '../../current-user-scope';
const ROOM_TRANSFORMS: TransformMap = { const ROOM_TRANSFORMS: TransformMap = {
hasPassword: boolToInt, hasPassword: boolToInt,
@@ -32,6 +33,12 @@ export async function handleUpdateRoom(command: UpdateRoomCommand, dataSource: D
const { roomId, updates } = command.payload; const { roomId, updates } = command.payload;
await dataSource.transaction(async (manager) => { await dataSource.transaction(async (manager) => {
const currentUserId = await getCurrentUserScope(manager);
if (!await userOwnsRoom(manager, roomId, currentUserId)) {
return;
}
const repo = manager.getRepository(RoomEntity); const repo = manager.getRepository(RoomEntity);
const existing = await repo.findOne({ where: { id: roomId } }); const existing = await repo.findOne({ where: { id: roomId } });

View File

@@ -18,7 +18,10 @@ import {
SaveBanCommand, SaveBanCommand,
RemoveBanCommand, RemoveBanCommand,
SaveAttachmentCommand, SaveAttachmentCommand,
DeleteAttachmentsForMessageCommand DeleteAttachmentsForMessageCommand,
SavePluginDataCommand,
DeletePluginDataCommand,
SaveMetaCommand
} from '../types'; } from '../types';
import { handleSaveMessage } from './handlers/saveMessage'; import { handleSaveMessage } from './handlers/saveMessage';
import { handleDeleteMessage } from './handlers/deleteMessage'; import { handleDeleteMessage } from './handlers/deleteMessage';
@@ -36,6 +39,9 @@ import { handleSaveBan } from './handlers/saveBan';
import { handleRemoveBan } from './handlers/removeBan'; import { handleRemoveBan } from './handlers/removeBan';
import { handleSaveAttachment } from './handlers/saveAttachment'; import { handleSaveAttachment } from './handlers/saveAttachment';
import { handleDeleteAttachmentsForMessage } from './handlers/deleteAttachmentsForMessage'; import { handleDeleteAttachmentsForMessage } from './handlers/deleteAttachmentsForMessage';
import { handleSavePluginData } from './handlers/savePluginData';
import { handleDeletePluginData } from './handlers/deletePluginData';
import { handleSaveMeta } from './handlers/saveMeta';
import { handleClearAllData } from './handlers/clearAllData'; import { handleClearAllData } from './handlers/clearAllData';
export const buildCommandHandlers = (dataSource: DataSource): Record<CommandTypeKey, (command: Command) => Promise<unknown>> => ({ export const buildCommandHandlers = (dataSource: DataSource): Record<CommandTypeKey, (command: Command) => Promise<unknown>> => ({
@@ -55,5 +61,8 @@ export const buildCommandHandlers = (dataSource: DataSource): Record<CommandType
[CommandType.RemoveBan]: (cmd) => handleRemoveBan(cmd as RemoveBanCommand, dataSource), [CommandType.RemoveBan]: (cmd) => handleRemoveBan(cmd as RemoveBanCommand, dataSource),
[CommandType.SaveAttachment]: (cmd) => handleSaveAttachment(cmd as SaveAttachmentCommand, dataSource), [CommandType.SaveAttachment]: (cmd) => handleSaveAttachment(cmd as SaveAttachmentCommand, dataSource),
[CommandType.DeleteAttachmentsForMessage]: (cmd) => handleDeleteAttachmentsForMessage(cmd as DeleteAttachmentsForMessageCommand, dataSource), [CommandType.DeleteAttachmentsForMessage]: (cmd) => handleDeleteAttachmentsForMessage(cmd as DeleteAttachmentsForMessageCommand, dataSource),
[CommandType.SavePluginData]: (cmd) => handleSavePluginData(cmd as SavePluginDataCommand, dataSource),
[CommandType.DeletePluginData]: (cmd) => handleDeletePluginData(cmd as DeletePluginDataCommand, dataSource),
[CommandType.SaveMeta]: (cmd) => handleSaveMeta(cmd as SaveMetaCommand, dataSource),
[CommandType.ClearAllData]: () => handleClearAllData(dataSource) [CommandType.ClearAllData]: () => handleClearAllData(dataSource)
}); });

View File

@@ -0,0 +1,24 @@
import { DataSource, EntityManager } from 'typeorm';
import { MetaEntity, RoomOwnerEntity } from '../entities';
export async function getCurrentUserScope(dataSourceOrManager: DataSource | EntityManager): Promise<string | null> {
const repo = dataSourceOrManager.getRepository(MetaEntity);
const meta = await repo.findOne({ where: { key: 'currentUserId' } });
return meta?.value?.trim() || null;
}
export async function userOwnsRoom(
dataSourceOrManager: DataSource | EntityManager,
roomId: string,
userId: string | null
): Promise<boolean> {
if (!userId) {
return false;
}
const repo = dataSourceOrManager.getRepository(RoomOwnerEntity);
const owner = await repo.findOne({ where: { roomId, userId } });
return !!owner;
}

View File

@@ -1,11 +1,28 @@
import { DataSource } from 'typeorm'; import { DataSource } from 'typeorm';
import { RoomEntity } from '../../../entities'; import { RoomEntity, RoomOwnerEntity } from '../../../entities';
import { rowToRoom } from '../../mappers'; import { rowToRoom } from '../../mappers';
import { loadRoomRelationsMap } from '../../relations'; import { loadRoomRelationsMap } from '../../relations';
import { getCurrentUserScope } from '../../current-user-scope';
export async function handleGetAllRooms(dataSource: DataSource) { export async function handleGetAllRooms(dataSource: DataSource) {
const currentUserId = await getCurrentUserScope(dataSource);
if (!currentUserId) {
return [];
}
const repo = dataSource.getRepository(RoomEntity); const repo = dataSource.getRepository(RoomEntity);
const rows = await repo.find(); const ownershipRows = await dataSource.getRepository(RoomOwnerEntity).find({ where: { userId: currentUserId } });
const roomIds = ownershipRows.map((owner) => owner.roomId);
if (roomIds.length === 0) {
return [];
}
const rows = await repo
.createQueryBuilder('room')
.where('room.id IN (:...roomIds)', { roomIds })
.getMany();
const relationsByRoomId = await loadRoomRelationsMap(dataSource, rows.map((row) => row.id)); const relationsByRoomId = await loadRoomRelationsMap(dataSource, rows.map((row) => row.id));
return rows.map((row) => rowToRoom(row, relationsByRoomId.get(row.id))); return rows.map((row) => rowToRoom(row, relationsByRoomId.get(row.id)));

View File

@@ -0,0 +1,9 @@
import { DataSource } from 'typeorm';
import { MetaEntity } from '../../../entities';
export async function handleGetCurrentUserId(dataSource: DataSource): Promise<string | null> {
const metaRepo = dataSource.getRepository(MetaEntity);
const metaRow = await metaRepo.findOne({ where: { key: 'currentUserId' } });
return metaRow?.value?.trim() || null;
}

View File

@@ -3,10 +3,17 @@ import { MessageEntity } from '../../../entities';
import { GetMessageByIdQuery } from '../../types'; import { GetMessageByIdQuery } from '../../types';
import { rowToMessage } from '../../mappers'; import { rowToMessage } from '../../mappers';
import { loadMessageReactionsMap } from '../../relations'; import { loadMessageReactionsMap } from '../../relations';
import { getCurrentUserScope } from '../../current-user-scope';
export async function handleGetMessageById(query: GetMessageByIdQuery, dataSource: DataSource) { export async function handleGetMessageById(query: GetMessageByIdQuery, dataSource: DataSource) {
const repo = dataSource.getRepository(MessageEntity); const repo = dataSource.getRepository(MessageEntity);
const row = await repo.findOne({ where: { id: query.payload.messageId } }); const currentUserId = await getCurrentUserScope(dataSource);
if (!currentUserId) {
return null;
}
const row = await repo.findOne({ where: { id: query.payload.messageId, ownerUserId: currentUserId } });
if (!row) { if (!row) {
return null; return null;

View File

@@ -3,12 +3,19 @@ import { MessageEntity } from '../../../entities';
import { GetMessagesQuery } from '../../types'; import { GetMessagesQuery } from '../../types';
import { rowToMessage } from '../../mappers'; import { rowToMessage } from '../../mappers';
import { loadMessageReactionsMap } from '../../relations'; import { loadMessageReactionsMap } from '../../relations';
import { getCurrentUserScope } from '../../current-user-scope';
export async function handleGetMessages(query: GetMessagesQuery, dataSource: DataSource) { export async function handleGetMessages(query: GetMessagesQuery, dataSource: DataSource) {
const repo = dataSource.getRepository(MessageEntity); const repo = dataSource.getRepository(MessageEntity);
const { roomId, limit = 100, offset = 0 } = query.payload; const { roomId, limit = 100, offset = 0 } = query.payload;
const currentUserId = await getCurrentUserScope(dataSource);
if (!currentUserId) {
return [];
}
const rows = await repo.find({ const rows = await repo.find({
where: { roomId }, where: { roomId, ownerUserId: currentUserId },
order: { timestamp: 'ASC' }, order: { timestamp: 'ASC' },
take: limit, take: limit,
skip: offset skip: offset

View File

@@ -3,13 +3,21 @@ import { MessageEntity } from '../../../entities';
import { GetMessagesSinceQuery } from '../../types'; import { GetMessagesSinceQuery } from '../../types';
import { rowToMessage } from '../../mappers'; import { rowToMessage } from '../../mappers';
import { loadMessageReactionsMap } from '../../relations'; import { loadMessageReactionsMap } from '../../relations';
import { getCurrentUserScope } from '../../current-user-scope';
export async function handleGetMessagesSince(query: GetMessagesSinceQuery, dataSource: DataSource) { export async function handleGetMessagesSince(query: GetMessagesSinceQuery, dataSource: DataSource) {
const repo = dataSource.getRepository(MessageEntity); const repo = dataSource.getRepository(MessageEntity);
const { roomId, sinceTimestamp } = query.payload; const { roomId, sinceTimestamp } = query.payload;
const currentUserId = await getCurrentUserScope(dataSource);
if (!currentUserId) {
return [];
}
const rows = await repo.find({ const rows = await repo.find({
where: { where: {
roomId, roomId,
ownerUserId: currentUserId,
timestamp: MoreThan(sinceTimestamp) timestamp: MoreThan(sinceTimestamp)
}, },
order: { timestamp: 'ASC' } order: { timestamp: 'ASC' }

View File

@@ -0,0 +1,11 @@
import { DataSource } from 'typeorm';
import { MetaEntity } from '../../../entities';
import { GetMetaQuery } from '../../types';
export async function handleGetMeta(query: GetMetaQuery, dataSource: DataSource): Promise<string | null> {
const meta = await dataSource.getRepository(MetaEntity).findOne({
where: { key: query.payload.key }
});
return meta?.value ?? null;
}

View File

@@ -0,0 +1,33 @@
import { DataSource } from 'typeorm';
import { getCurrentUserScope } from '../../current-user-scope';
import { PluginDataEntity } from '../../../entities';
import { GetPluginDataQuery } from '../../types';
export async function handleGetPluginData(query: GetPluginDataQuery, dataSource: DataSource): Promise<unknown> {
const { payload } = query;
const ownerUserId = await getCurrentUserScope(dataSource);
if (!ownerUserId) {
return null;
}
const record = await dataSource.getRepository(PluginDataEntity).findOne({
where: {
key: payload.key,
ownerUserId,
pluginId: payload.pluginId,
scope: payload.scope,
serverId: payload.serverId ?? ''
}
});
if (!record) {
return null;
}
try {
return JSON.parse(record.valueJson) as unknown;
} catch {
return null;
}
}

View File

@@ -3,8 +3,15 @@ import { RoomEntity } from '../../../entities';
import { GetRoomQuery } from '../../types'; import { GetRoomQuery } from '../../types';
import { rowToRoom } from '../../mappers'; import { rowToRoom } from '../../mappers';
import { loadRoomRelationsMap } from '../../relations'; import { loadRoomRelationsMap } from '../../relations';
import { getCurrentUserScope, userOwnsRoom } from '../../current-user-scope';
export async function handleGetRoom(query: GetRoomQuery, dataSource: DataSource) { export async function handleGetRoom(query: GetRoomQuery, dataSource: DataSource) {
const currentUserId = await getCurrentUserScope(dataSource);
if (!await userOwnsRoom(dataSource, query.payload.roomId, currentUserId)) {
return null;
}
const repo = dataSource.getRepository(RoomEntity); const repo = dataSource.getRepository(RoomEntity);
const row = await repo.findOne({ where: { id: query.payload.roomId } }); const row = await repo.findOne({ where: { id: query.payload.roomId } });

View File

@@ -11,7 +11,9 @@ import {
GetRoomQuery, GetRoomQuery,
GetBansForRoomQuery, GetBansForRoomQuery,
IsUserBannedQuery, IsUserBannedQuery,
GetAttachmentsForMessageQuery GetAttachmentsForMessageQuery,
GetPluginDataQuery,
GetMetaQuery
} from '../types'; } from '../types';
import { handleGetMessages } from './handlers/getMessages'; import { handleGetMessages } from './handlers/getMessages';
import { handleGetMessagesSince } from './handlers/getMessagesSince'; import { handleGetMessagesSince } from './handlers/getMessagesSince';
@@ -19,6 +21,7 @@ import { handleGetMessageById } from './handlers/getMessageById';
import { handleGetReactionsForMessage } from './handlers/getReactionsForMessage'; import { handleGetReactionsForMessage } from './handlers/getReactionsForMessage';
import { handleGetUser } from './handlers/getUser'; import { handleGetUser } from './handlers/getUser';
import { handleGetCurrentUser } from './handlers/getCurrentUser'; import { handleGetCurrentUser } from './handlers/getCurrentUser';
import { handleGetCurrentUserId } from './handlers/getCurrentUserId';
import { handleGetUsersByRoom } from './handlers/getUsersByRoom'; import { handleGetUsersByRoom } from './handlers/getUsersByRoom';
import { handleGetRoom } from './handlers/getRoom'; import { handleGetRoom } from './handlers/getRoom';
import { handleGetAllRooms } from './handlers/getAllRooms'; import { handleGetAllRooms } from './handlers/getAllRooms';
@@ -26,6 +29,8 @@ import { handleGetBansForRoom } from './handlers/getBansForRoom';
import { handleIsUserBanned } from './handlers/isUserBanned'; import { handleIsUserBanned } from './handlers/isUserBanned';
import { handleGetAttachmentsForMessage } from './handlers/getAttachmentsForMessage'; import { handleGetAttachmentsForMessage } from './handlers/getAttachmentsForMessage';
import { handleGetAllAttachments } from './handlers/getAllAttachments'; import { handleGetAllAttachments } from './handlers/getAllAttachments';
import { handleGetPluginData } from './handlers/getPluginData';
import { handleGetMeta } from './handlers/getMeta';
export const buildQueryHandlers = (dataSource: DataSource): Record<QueryTypeKey, (query: Query) => Promise<unknown>> => ({ export const buildQueryHandlers = (dataSource: DataSource): Record<QueryTypeKey, (query: Query) => Promise<unknown>> => ({
[QueryType.GetMessages]: (query) => handleGetMessages(query as GetMessagesQuery, dataSource), [QueryType.GetMessages]: (query) => handleGetMessages(query as GetMessagesQuery, dataSource),
@@ -34,11 +39,14 @@ export const buildQueryHandlers = (dataSource: DataSource): Record<QueryTypeKey,
[QueryType.GetReactionsForMessage]: (query) => handleGetReactionsForMessage(query as GetReactionsForMessageQuery, dataSource), [QueryType.GetReactionsForMessage]: (query) => handleGetReactionsForMessage(query as GetReactionsForMessageQuery, dataSource),
[QueryType.GetUser]: (query) => handleGetUser(query as GetUserQuery, dataSource), [QueryType.GetUser]: (query) => handleGetUser(query as GetUserQuery, dataSource),
[QueryType.GetCurrentUser]: () => handleGetCurrentUser(dataSource), [QueryType.GetCurrentUser]: () => handleGetCurrentUser(dataSource),
[QueryType.GetCurrentUserId]: () => handleGetCurrentUserId(dataSource),
[QueryType.GetUsersByRoom]: () => handleGetUsersByRoom(dataSource), [QueryType.GetUsersByRoom]: () => handleGetUsersByRoom(dataSource),
[QueryType.GetRoom]: (query) => handleGetRoom(query as GetRoomQuery, dataSource), [QueryType.GetRoom]: (query) => handleGetRoom(query as GetRoomQuery, dataSource),
[QueryType.GetAllRooms]: () => handleGetAllRooms(dataSource), [QueryType.GetAllRooms]: () => handleGetAllRooms(dataSource),
[QueryType.GetBansForRoom]: (query) => handleGetBansForRoom(query as GetBansForRoomQuery, dataSource), [QueryType.GetBansForRoom]: (query) => handleGetBansForRoom(query as GetBansForRoomQuery, dataSource),
[QueryType.IsUserBanned]: (query) => handleIsUserBanned(query as IsUserBannedQuery, dataSource), [QueryType.IsUserBanned]: (query) => handleIsUserBanned(query as IsUserBannedQuery, dataSource),
[QueryType.GetAttachmentsForMessage]: (query) => handleGetAttachmentsForMessage(query as GetAttachmentsForMessageQuery, dataSource), [QueryType.GetAttachmentsForMessage]: (query) => handleGetAttachmentsForMessage(query as GetAttachmentsForMessageQuery, dataSource),
[QueryType.GetAllAttachments]: () => handleGetAllAttachments(dataSource) [QueryType.GetAllAttachments]: () => handleGetAllAttachments(dataSource),
[QueryType.GetPluginData]: (query) => handleGetPluginData(query as GetPluginDataQuery, dataSource),
[QueryType.GetMeta]: (query) => handleGetMeta(query as GetMetaQuery, dataSource)
}); });

View File

@@ -15,6 +15,9 @@ export const CommandType = {
RemoveBan: 'remove-ban', RemoveBan: 'remove-ban',
SaveAttachment: 'save-attachment', SaveAttachment: 'save-attachment',
DeleteAttachmentsForMessage: 'delete-attachments-for-message', DeleteAttachmentsForMessage: 'delete-attachments-for-message',
SavePluginData: 'save-plugin-data',
DeletePluginData: 'delete-plugin-data',
SaveMeta: 'save-meta',
ClearAllData: 'clear-all-data' ClearAllData: 'clear-all-data'
} as const; } as const;
@@ -27,13 +30,16 @@ export const QueryType = {
GetReactionsForMessage: 'get-reactions-for-message', GetReactionsForMessage: 'get-reactions-for-message',
GetUser: 'get-user', GetUser: 'get-user',
GetCurrentUser: 'get-current-user', GetCurrentUser: 'get-current-user',
GetCurrentUserId: 'get-current-user-id',
GetUsersByRoom: 'get-users-by-room', GetUsersByRoom: 'get-users-by-room',
GetRoom: 'get-room', GetRoom: 'get-room',
GetAllRooms: 'get-all-rooms', GetAllRooms: 'get-all-rooms',
GetBansForRoom: 'get-bans-for-room', GetBansForRoom: 'get-bans-for-room',
IsUserBanned: 'is-user-banned', IsUserBanned: 'is-user-banned',
GetAttachmentsForMessage: 'get-attachments-for-message', GetAttachmentsForMessage: 'get-attachments-for-message',
GetAllAttachments: 'get-all-attachments' GetAllAttachments: 'get-all-attachments',
GetPluginData: 'get-plugin-data',
GetMeta: 'get-meta'
} as const; } as const;
export type QueryTypeKey = typeof QueryType[keyof typeof QueryType]; export type QueryTypeKey = typeof QueryType[keyof typeof QueryType];
@@ -171,6 +177,16 @@ export interface AttachmentPayload {
savedPath?: string; savedPath?: string;
} }
export type PluginDataScopePayload = 'local' | 'server';
export interface PluginDataPayload {
key: string;
pluginId: string;
scope: PluginDataScopePayload;
serverId?: string;
value: unknown;
}
export interface SaveMessageCommand { type: typeof CommandType.SaveMessage; payload: { message: MessagePayload } } export interface SaveMessageCommand { type: typeof CommandType.SaveMessage; payload: { message: MessagePayload } }
export interface DeleteMessageCommand { type: typeof CommandType.DeleteMessage; payload: { messageId: string } } export interface DeleteMessageCommand { type: typeof CommandType.DeleteMessage; payload: { messageId: string } }
export interface UpdateMessageCommand { type: typeof CommandType.UpdateMessage; payload: { messageId: string; updates: Partial<MessagePayload> } } export interface UpdateMessageCommand { type: typeof CommandType.UpdateMessage; payload: { messageId: string; updates: Partial<MessagePayload> } }
@@ -187,6 +203,9 @@ export interface SaveBanCommand { type: typeof CommandType.SaveBan; payload: { b
export interface RemoveBanCommand { type: typeof CommandType.RemoveBan; payload: { oderId: string } } export interface RemoveBanCommand { type: typeof CommandType.RemoveBan; payload: { oderId: string } }
export interface SaveAttachmentCommand { type: typeof CommandType.SaveAttachment; payload: { attachment: AttachmentPayload } } export interface SaveAttachmentCommand { type: typeof CommandType.SaveAttachment; payload: { attachment: AttachmentPayload } }
export interface DeleteAttachmentsForMessageCommand { type: typeof CommandType.DeleteAttachmentsForMessage; payload: { messageId: string } } export interface DeleteAttachmentsForMessageCommand { type: typeof CommandType.DeleteAttachmentsForMessage; payload: { messageId: string } }
export interface SavePluginDataCommand { type: typeof CommandType.SavePluginData; payload: PluginDataPayload }
export interface DeletePluginDataCommand { type: typeof CommandType.DeletePluginData; payload: Omit<PluginDataPayload, 'value'> }
export interface SaveMetaCommand { type: typeof CommandType.SaveMeta; payload: { key: string; value: string | null } }
export interface ClearAllDataCommand { type: typeof CommandType.ClearAllData; payload: Record<string, never> } export interface ClearAllDataCommand { type: typeof CommandType.ClearAllData; payload: Record<string, never> }
export type Command = export type Command =
@@ -206,6 +225,9 @@ export type Command =
| RemoveBanCommand | RemoveBanCommand
| SaveAttachmentCommand | SaveAttachmentCommand
| DeleteAttachmentsForMessageCommand | DeleteAttachmentsForMessageCommand
| SavePluginDataCommand
| DeletePluginDataCommand
| SaveMetaCommand
| ClearAllDataCommand; | ClearAllDataCommand;
export interface GetMessagesQuery { type: typeof QueryType.GetMessages; payload: { roomId: string; limit?: number; offset?: number } } export interface GetMessagesQuery { type: typeof QueryType.GetMessages; payload: { roomId: string; limit?: number; offset?: number } }
@@ -214,6 +236,7 @@ export interface GetMessageByIdQuery { type: typeof QueryType.GetMessageById; pa
export interface GetReactionsForMessageQuery { type: typeof QueryType.GetReactionsForMessage; payload: { messageId: string } } export interface GetReactionsForMessageQuery { type: typeof QueryType.GetReactionsForMessage; payload: { messageId: string } }
export interface GetUserQuery { type: typeof QueryType.GetUser; payload: { userId: string } } export interface GetUserQuery { type: typeof QueryType.GetUser; payload: { userId: string } }
export interface GetCurrentUserQuery { type: typeof QueryType.GetCurrentUser; payload: Record<string, never> } export interface GetCurrentUserQuery { type: typeof QueryType.GetCurrentUser; payload: Record<string, never> }
export interface GetCurrentUserIdQuery { type: typeof QueryType.GetCurrentUserId; payload: Record<string, never> }
export interface GetUsersByRoomQuery { type: typeof QueryType.GetUsersByRoom; payload: { roomId: string } } export interface GetUsersByRoomQuery { type: typeof QueryType.GetUsersByRoom; payload: { roomId: string } }
export interface GetRoomQuery { type: typeof QueryType.GetRoom; payload: { roomId: string } } export interface GetRoomQuery { type: typeof QueryType.GetRoom; payload: { roomId: string } }
export interface GetAllRoomsQuery { type: typeof QueryType.GetAllRooms; payload: Record<string, never> } export interface GetAllRoomsQuery { type: typeof QueryType.GetAllRooms; payload: Record<string, never> }
@@ -221,6 +244,8 @@ export interface GetBansForRoomQuery { type: typeof QueryType.GetBansForRoom; pa
export interface IsUserBannedQuery { type: typeof QueryType.IsUserBanned; payload: { userId: string; roomId: string } } export interface IsUserBannedQuery { type: typeof QueryType.IsUserBanned; payload: { userId: string; roomId: string } }
export interface GetAttachmentsForMessageQuery { type: typeof QueryType.GetAttachmentsForMessage; payload: { messageId: string } } export interface GetAttachmentsForMessageQuery { type: typeof QueryType.GetAttachmentsForMessage; payload: { messageId: string } }
export interface GetAllAttachmentsQuery { type: typeof QueryType.GetAllAttachments; payload: Record<string, never> } export interface GetAllAttachmentsQuery { type: typeof QueryType.GetAllAttachments; payload: Record<string, never> }
export interface GetPluginDataQuery { type: typeof QueryType.GetPluginData; payload: Omit<PluginDataPayload, 'value'> }
export interface GetMetaQuery { type: typeof QueryType.GetMeta; payload: { key: string } }
export type Query = export type Query =
| GetMessagesQuery | GetMessagesQuery
@@ -229,10 +254,13 @@ export type Query =
| GetReactionsForMessageQuery | GetReactionsForMessageQuery
| GetUserQuery | GetUserQuery
| GetCurrentUserQuery | GetCurrentUserQuery
| GetCurrentUserIdQuery
| GetUsersByRoomQuery | GetUsersByRoomQuery
| GetRoomQuery | GetRoomQuery
| GetAllRoomsQuery | GetAllRoomsQuery
| GetBansForRoomQuery | GetBansForRoomQuery
| IsUserBannedQuery | IsUserBannedQuery
| GetAttachmentsForMessageQuery | GetAttachmentsForMessageQuery
| GetAllAttachmentsQuery; | GetAllAttachmentsQuery
| GetPluginDataQuery
| GetMetaQuery;

233
electron/data-archive.ts Normal file
View File

@@ -0,0 +1,233 @@
import * as fsp from 'fs/promises';
import * as path from 'path';
export interface ZipArchiveEntry {
data: Buffer;
path: string;
}
interface CentralDirectoryEntry {
compressedSize: number;
crc: number;
data: Buffer;
localHeaderOffset: number;
name: Buffer;
uncompressedSize: number;
}
const ZIP_LOCAL_FILE_HEADER_SIGNATURE = 0x04034b50;
const ZIP_CENTRAL_DIRECTORY_SIGNATURE = 0x02014b50;
const ZIP_END_OF_CENTRAL_DIRECTORY_SIGNATURE = 0x06054b50;
const ZIP_UTF8_FLAG = 0x0800;
const ZIP_STORE_METHOD = 0;
const ZIP_VERSION = 20;
const MAX_UINT32 = 0xffffffff;
const crcTable = buildCrcTable();
export function createZipArchive(entries: ZipArchiveEntry[]): Buffer {
const localParts: Buffer[] = [];
const centralEntries: CentralDirectoryEntry[] = [];
let offset = 0;
for (const entry of entries) {
const normalizedPath = normalizeZipPath(entry.path);
const name = Buffer.from(normalizedPath, 'utf8');
const data = entry.data;
if (name.length > 0xffff || data.length > MAX_UINT32 || offset > MAX_UINT32) {
throw new Error('Data archive is too large for the portable ZIP format.');
}
const crc = crc32(data);
const localHeader = Buffer.alloc(30);
localHeader.writeUInt32LE(ZIP_LOCAL_FILE_HEADER_SIGNATURE, 0);
localHeader.writeUInt16LE(ZIP_VERSION, 4);
localHeader.writeUInt16LE(ZIP_UTF8_FLAG, 6);
localHeader.writeUInt16LE(ZIP_STORE_METHOD, 8);
localHeader.writeUInt16LE(0, 10);
localHeader.writeUInt16LE(0, 12);
localHeader.writeUInt32LE(crc, 14);
localHeader.writeUInt32LE(data.length, 18);
localHeader.writeUInt32LE(data.length, 22);
localHeader.writeUInt16LE(name.length, 26);
localHeader.writeUInt16LE(0, 28);
localParts.push(localHeader, name, data);
centralEntries.push({
compressedSize: data.length,
crc,
data,
localHeaderOffset: offset,
name,
uncompressedSize: data.length
});
offset += localHeader.length + name.length + data.length;
}
const centralDirectoryOffset = offset;
const centralParts = centralEntries.map((entry) => {
const header = Buffer.alloc(46);
header.writeUInt32LE(ZIP_CENTRAL_DIRECTORY_SIGNATURE, 0);
header.writeUInt16LE(ZIP_VERSION, 4);
header.writeUInt16LE(ZIP_VERSION, 6);
header.writeUInt16LE(ZIP_UTF8_FLAG, 8);
header.writeUInt16LE(ZIP_STORE_METHOD, 10);
header.writeUInt16LE(0, 12);
header.writeUInt16LE(0, 14);
header.writeUInt32LE(entry.crc, 16);
header.writeUInt32LE(entry.compressedSize, 20);
header.writeUInt32LE(entry.uncompressedSize, 24);
header.writeUInt16LE(entry.name.length, 28);
header.writeUInt16LE(0, 30);
header.writeUInt16LE(0, 32);
header.writeUInt16LE(0, 34);
header.writeUInt16LE(0, 36);
header.writeUInt32LE(0, 38);
header.writeUInt32LE(entry.localHeaderOffset, 42);
offset += header.length + entry.name.length;
return Buffer.concat([header, entry.name]);
});
const centralDirectorySize = offset - centralDirectoryOffset;
if (centralEntries.length > 0xffff || centralDirectoryOffset > MAX_UINT32 || centralDirectorySize > MAX_UINT32) {
throw new Error('Data archive is too large for the portable ZIP format.');
}
const end = Buffer.alloc(22);
end.writeUInt32LE(ZIP_END_OF_CENTRAL_DIRECTORY_SIGNATURE, 0);
end.writeUInt16LE(0, 4);
end.writeUInt16LE(0, 6);
end.writeUInt16LE(centralEntries.length, 8);
end.writeUInt16LE(centralEntries.length, 10);
end.writeUInt32LE(centralDirectorySize, 12);
end.writeUInt32LE(centralDirectoryOffset, 16);
end.writeUInt16LE(0, 20);
return Buffer.concat([
...localParts,
...centralParts,
end
]);
}
export function readZipArchive(data: Buffer): ZipArchiveEntry[] {
const endOffset = findEndOfCentralDirectory(data);
if (endOffset < 0) {
throw new Error('The selected file is not a supported data archive.');
}
const entryCount = data.readUInt16LE(endOffset + 10);
const centralDirectoryOffset = data.readUInt32LE(endOffset + 16);
const entries: ZipArchiveEntry[] = [];
let offset = centralDirectoryOffset;
for (let index = 0; index < entryCount; index += 1) {
if (data.readUInt32LE(offset) !== ZIP_CENTRAL_DIRECTORY_SIGNATURE) {
throw new Error('The data archive directory is invalid.');
}
const method = data.readUInt16LE(offset + 10);
const compressedSize = data.readUInt32LE(offset + 20);
const uncompressedSize = data.readUInt32LE(offset + 24);
const nameLength = data.readUInt16LE(offset + 28);
const extraLength = data.readUInt16LE(offset + 30);
const commentLength = data.readUInt16LE(offset + 32);
const localHeaderOffset = data.readUInt32LE(offset + 42);
const entryPath = normalizeZipPath(data.subarray(offset + 46, offset + 46 + nameLength).toString('utf8'));
if (method !== ZIP_STORE_METHOD || compressedSize !== uncompressedSize) {
throw new Error('Compressed data archives are not supported by this build.');
}
if (data.readUInt32LE(localHeaderOffset) !== ZIP_LOCAL_FILE_HEADER_SIGNATURE) {
throw new Error('The data archive contains an invalid file entry.');
}
const localNameLength = data.readUInt16LE(localHeaderOffset + 26);
const localExtraLength = data.readUInt16LE(localHeaderOffset + 28);
const dataOffset = localHeaderOffset + 30 + localNameLength + localExtraLength;
entries.push({
data: Buffer.from(data.subarray(dataOffset, dataOffset + compressedSize)),
path: entryPath
});
offset += 46 + nameLength + extraLength + commentLength;
}
return entries;
}
export async function extractZipEntries(entries: ZipArchiveEntry[], destinationPath: string): Promise<void> {
const destinationRoot = path.resolve(destinationPath);
for (const entry of entries) {
const targetPath = path.resolve(destinationRoot, entry.path);
if (!targetPath.startsWith(destinationRoot + path.sep) && targetPath !== destinationRoot) {
throw new Error('The data archive contains an unsafe path.');
}
await fsp.mkdir(path.dirname(targetPath), { recursive: true });
await fsp.writeFile(targetPath, entry.data);
}
}
function findEndOfCentralDirectory(data: Buffer): number {
const minimumOffset = Math.max(0, data.length - 0xffff - 22);
for (let offset = data.length - 22; offset >= minimumOffset; offset -= 1) {
if (data.readUInt32LE(offset) === ZIP_END_OF_CENTRAL_DIRECTORY_SIGNATURE) {
return offset;
}
}
return -1;
}
function normalizeZipPath(value: string): string {
const normalized = value.replace(/\\/g, '/').replace(/^\/+/, '');
if (!normalized || normalized.split('/').some((part) => part === '..' || part === '')) {
throw new Error('The data archive contains an unsafe path.');
}
return normalized;
}
function buildCrcTable(): number[] {
const table: number[] = [];
for (let index = 0; index < 256; index += 1) {
let value = index;
for (let bit = 0; bit < 8; bit += 1) {
value = (value & 1) !== 0
? 0xedb88320 ^ (value >>> 1)
: value >>> 1;
}
table[index] = value >>> 0;
}
return table;
}
function crc32(data: Buffer): number {
let crc = 0xffffffff;
for (const byte of data) {
crc = crcTable[(crc ^ byte) & 0xff] ^ (crc >>> 8);
}
return (crc ^ 0xffffffff) >>> 0;
}

256
electron/data-management.ts Normal file
View File

@@ -0,0 +1,256 @@
import {
app,
dialog,
shell
} from 'electron';
import * as fsp from 'fs/promises';
import * as path from 'path';
import { destroyDatabase, initializeDatabase } from './db/database';
import {
createZipArchive,
extractZipEntries,
readZipArchive,
type ZipArchiveEntry
} from './data-archive';
export interface ExportUserDataResult {
cancelled: boolean;
exported: boolean;
filePath?: string;
}
export interface ImportUserDataResult {
backupPath?: string;
cancelled: boolean;
imported: boolean;
restartRequired: boolean;
}
export interface EraseUserDataResult {
erased: boolean;
restartRequired: boolean;
}
const ARCHIVE_MANIFEST_PATH = 'metoyou-data-manifest.json';
const ARCHIVE_DATA_PREFIX = 'data/';
const BACKUP_DIRECTORY_NAME = 'metoyou-data-backups';
export async function openCurrentDataFolder(): Promise<boolean> {
const error = await shell.openPath(app.getPath('userData'));
return error.length === 0;
}
export async function exportUserData(): Promise<ExportUserDataResult> {
const dataPath = app.getPath('userData');
const defaultFileName = `metoyou-data-${new Date().toISOString()
.slice(0, 10)}.dat`;
const { canceled, filePath } = await dialog.showSaveDialog({
defaultPath: path.join(app.getPath('documents'), defaultFileName),
filters: [{ extensions: ['dat'], name: 'MetoYou data archive' }],
title: 'Export MetoYou data'
});
if (canceled || !filePath) {
return { cancelled: true, exported: false };
}
const entries: ZipArchiveEntry[] = [
{
data: Buffer.from(JSON.stringify({
appVersion: app.getVersion(),
exportedAt: new Date().toISOString(),
format: 'metoyou-user-data',
version: 1
}, null, 2)),
path: ARCHIVE_MANIFEST_PATH
}
];
for (const file of await collectDataFiles(dataPath)) {
const relativePath = toArchivePath(path.relative(dataPath, file));
entries.push({
data: await fsp.readFile(file),
path: `${ARCHIVE_DATA_PREFIX}${relativePath}`
});
}
await fsp.writeFile(ensureDatExtension(filePath), createZipArchive(entries));
return {
cancelled: false,
exported: true,
filePath: ensureDatExtension(filePath)
};
}
export async function importUserData(): Promise<ImportUserDataResult> {
const { canceled, filePaths } = await dialog.showOpenDialog({
filters: [{ extensions: ['dat', 'zip'], name: 'MetoYou data archive' }],
properties: ['openFile'],
title: 'Import MetoYou data'
});
if (canceled || filePaths.length === 0) {
return {
cancelled: true,
imported: false,
restartRequired: false
};
}
const archiveEntries = readZipArchive(await fsp.readFile(filePaths[0]));
validateArchiveManifest(archiveEntries);
const importRoot = path.join(app.getPath('temp'), `metoyou-import-${Date.now()}`);
const importDataPath = path.join(importRoot, 'data');
try {
await extractZipEntries(
archiveEntries
.filter((entry) => entry.path.startsWith(ARCHIVE_DATA_PREFIX))
.map((entry) => ({
data: entry.data,
path: entry.path.slice(ARCHIVE_DATA_PREFIX.length)
})),
importDataPath
);
await destroyDatabase();
const backupPath = await moveCurrentDataAside();
await copyDirectory(importDataPath, app.getPath('userData'));
await initializeDatabase();
return {
backupPath,
cancelled: false,
imported: true,
restartRequired: true
};
} catch (error) {
await initializeDatabase().catch(() => {});
throw error;
} finally {
await fsp.rm(importRoot, { force: true, recursive: true }).catch(() => {});
}
}
export async function eraseUserData(): Promise<EraseUserDataResult> {
const dataPath = app.getPath('userData');
await destroyDatabase();
for (const entry of await fsp.readdir(dataPath, { withFileTypes: true }).catch(() => [])) {
await fsp.rm(path.join(dataPath, entry.name), { force: true, recursive: true });
}
await fsp.mkdir(dataPath, { recursive: true });
await initializeDatabase();
return {
erased: true,
restartRequired: true
};
}
async function collectDataFiles(directoryPath: string): Promise<string[]> {
const files: string[] = [];
const entries = await fsp.readdir(directoryPath, { withFileTypes: true }).catch(() => []);
for (const entry of entries) {
if (entry.name === BACKUP_DIRECTORY_NAME) {
continue;
}
const entryPath = path.join(directoryPath, entry.name);
if (entry.isDirectory()) {
files.push(...await collectDataFiles(entryPath));
} else if (entry.isFile()) {
files.push(entryPath);
}
}
return files;
}
async function moveCurrentDataAside(): Promise<string | undefined> {
const dataPath = app.getPath('userData');
const backupRoot = path.join(dataPath, BACKUP_DIRECTORY_NAME);
const backupPath = path.join(backupRoot, `before-import-${new Date().toISOString()
.replace(/[:.]/g, '-')}`);
const entries = await fsp.readdir(dataPath, { withFileTypes: true }).catch(() => []);
await fsp.mkdir(backupPath, { recursive: true });
let movedAny = false;
for (const entry of entries) {
if (entry.name === BACKUP_DIRECTORY_NAME) {
continue;
}
const sourcePath = path.join(dataPath, entry.name);
const targetPath = path.join(backupPath, entry.name);
await fsp.mkdir(path.dirname(targetPath), { recursive: true });
await fsp.rename(sourcePath, targetPath).catch(async () => {
await copyPath(sourcePath, targetPath);
await fsp.rm(sourcePath, { force: true, recursive: true });
});
movedAny = true;
}
return movedAny ? backupPath : undefined;
}
async function copyDirectory(sourcePath: string, targetPath: string): Promise<void> {
await fsp.mkdir(targetPath, { recursive: true });
for (const entry of await fsp.readdir(sourcePath, { withFileTypes: true }).catch(() => [])) {
await copyPath(path.join(sourcePath, entry.name), path.join(targetPath, entry.name));
}
}
async function copyPath(sourcePath: string, targetPath: string): Promise<void> {
const stats = await fsp.stat(sourcePath);
if (stats.isDirectory()) {
await copyDirectory(sourcePath, targetPath);
return;
}
if (stats.isFile()) {
await fsp.mkdir(path.dirname(targetPath), { recursive: true });
await fsp.copyFile(sourcePath, targetPath);
}
}
function validateArchiveManifest(entries: ZipArchiveEntry[]): void {
const manifest = entries.find((entry) => entry.path === ARCHIVE_MANIFEST_PATH);
if (!manifest) {
throw new Error('The selected file is missing a MetoYou data manifest.');
}
const parsed = JSON.parse(manifest.data.toString('utf8')) as { format?: string; version?: number };
if (parsed.format !== 'metoyou-user-data' || parsed.version !== 1) {
throw new Error('The selected file uses an unsupported data archive format.');
}
}
function ensureDatExtension(filePath: string): string {
return path.extname(filePath).toLowerCase() === '.dat'
? filePath
: `${filePath}.dat`;
}
function toArchivePath(filePath: string): string {
return filePath.split(path.sep).join('/');
}

View File

@@ -25,7 +25,8 @@ import {
ReactionEntity, ReactionEntity,
BanEntity, BanEntity,
AttachmentEntity, AttachmentEntity,
MetaEntity MetaEntity,
PluginDataEntity
} from './entities'; } from './entities';
const projectRootDatabaseFilePath = path.join(__dirname, '..', '..', settings.databaseName); const projectRootDatabaseFilePath = path.join(__dirname, '..', '..', settings.databaseName);
@@ -51,7 +52,8 @@ export const AppDataSource = new DataSource({
ReactionEntity, ReactionEntity,
BanEntity, BanEntity,
AttachmentEntity, AttachmentEntity,
MetaEntity MetaEntity,
PluginDataEntity
], ],
migrations: [path.join(__dirname, 'migrations', '*.{ts,js}')], migrations: [path.join(__dirname, 'migrations', '*.{ts,js}')],
synchronize: false, synchronize: false,

View File

@@ -8,6 +8,7 @@ import {
MessageEntity, MessageEntity,
UserEntity, UserEntity,
RoomEntity, RoomEntity,
RoomOwnerEntity,
RoomChannelEntity, RoomChannelEntity,
RoomMemberEntity, RoomMemberEntity,
RoomRoleEntity, RoomRoleEntity,
@@ -16,7 +17,8 @@ import {
ReactionEntity, ReactionEntity,
BanEntity, BanEntity,
AttachmentEntity, AttachmentEntity,
MetaEntity MetaEntity,
PluginDataEntity
} from '../entities'; } from '../entities';
import { settings } from '../settings'; import { settings } from '../settings';
@@ -26,6 +28,34 @@ let dbBackupPath = '';
// SQLite files start with this 16-byte header string. // SQLite files start with this 16-byte header string.
const SQLITE_MAGIC = 'SQLite format 3\0'; const SQLITE_MAGIC = 'SQLite format 3\0';
const SAVE_RETRY_DELAYS_MS = [
25,
75,
150,
300,
600
];
const RETRYABLE_SAVE_ERROR_CODES = new Set([
'EPERM',
'EACCES',
'EBUSY'
]);
let saveQueue: Promise<void> = Promise.resolve();
function wait(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
function isRetryableSaveError(error: unknown): boolean {
if (!error || typeof error !== 'object') {
return false;
}
const code = (error as NodeJS.ErrnoException).code;
return typeof code === 'string' && RETRYABLE_SAVE_ERROR_CODES.has(code);
}
export function getDataSource(): DataSource | undefined { export function getDataSource(): DataSource | undefined {
return applicationDataSource; return applicationDataSource;
@@ -87,18 +117,47 @@ function safeguardDbFile(): Uint8Array | undefined {
* then rename it over the real file. rename() is atomic on the same * then rename it over the real file. rename() is atomic on the same
* filesystem, so a crash mid-write can never leave a half-written DB. * filesystem, so a crash mid-write can never leave a half-written DB.
*/ */
async function atomicSave(data: Uint8Array): Promise<void> { async function replaceDatabaseFile(tmpPath: string): Promise<void> {
for (let attempt = 0; ; attempt++) {
try {
await fsp.rename(tmpPath, dbFilePath);
return;
} catch (error) {
const delay = SAVE_RETRY_DELAYS_MS[attempt];
if (!isRetryableSaveError(error) || delay === undefined) {
throw error;
}
await wait(delay);
}
}
}
async function writeDatabaseSnapshot(snapshot: Buffer): Promise<void> {
const tmpPath = dbFilePath + '.tmp-' + randomBytes(6).toString('hex'); const tmpPath = dbFilePath + '.tmp-' + randomBytes(6).toString('hex');
try { try {
await fsp.writeFile(tmpPath, Buffer.from(data)); await fsp.writeFile(tmpPath, snapshot);
await fsp.rename(tmpPath, dbFilePath); await replaceDatabaseFile(tmpPath);
} catch (err) { } catch (err) {
await fsp.unlink(tmpPath).catch(() => {}); await fsp.unlink(tmpPath).catch(() => {});
throw err; throw err;
} }
} }
async function atomicSave(data: Uint8Array): Promise<void> {
const snapshot = Buffer.from(data);
const saveTask = saveQueue.then(
() => writeDatabaseSnapshot(snapshot),
() => writeDatabaseSnapshot(snapshot)
);
saveQueue = saveTask.catch(() => {});
return saveTask;
}
export async function initializeDatabase(): Promise<void> { export async function initializeDatabase(): Promise<void> {
const userDataPath = app.getPath('userData'); const userDataPath = app.getPath('userData');
const dbDir = path.join(userDataPath, 'metoyou'); const dbDir = path.join(userDataPath, 'metoyou');
@@ -116,6 +175,7 @@ export async function initializeDatabase(): Promise<void> {
MessageEntity, MessageEntity,
UserEntity, UserEntity,
RoomEntity, RoomEntity,
RoomOwnerEntity,
RoomChannelEntity, RoomChannelEntity,
RoomMemberEntity, RoomMemberEntity,
RoomRoleEntity, RoomRoleEntity,
@@ -124,7 +184,8 @@ export async function initializeDatabase(): Promise<void> {
ReactionEntity, ReactionEntity,
BanEntity, BanEntity,
AttachmentEntity, AttachmentEntity,
MetaEntity MetaEntity,
PluginDataEntity
], ],
migrations: [path.join(__dirname, '..', 'migrations', '*.js'), path.join(__dirname, '..', 'migrations', '*.ts')], migrations: [path.join(__dirname, '..', 'migrations', '*.js'), path.join(__dirname, '..', 'migrations', '*.ts')],
synchronize: false, synchronize: false,

Some files were not shown because too many files have changed in this diff Show More