11 Commits

Author SHA1 Message Date
Myx
d0aff6319d fix: should now sync with other devices
All checks were successful
Queue Release Build / prepare (push) Successful in 25s
Deploy Web Apps / deploy (push) Successful in 7m8s
Queue Release Build / build-windows (push) Successful in 28m10s
Queue Release Build / build-linux (push) Successful in 44m38s
Queue Release Build / build-android (push) Successful in 18m36s
Queue Release Build / finalize (push) Successful in 1m40s
2026-06-09 22:00:39 +02:00
Myx
1274ad9b46 fix: search 2026-06-09 22:00:06 +02:00
Myx
eb51f043ac fix: Major bug cleanup pass 1
All checks were successful
Queue Release Build / prepare (push) Successful in 19s
Deploy Web Apps / deploy (push) Successful in 8m12s
Queue Release Build / build-windows (push) Successful in 27m44s
Queue Release Build / build-linux (push) Successful in 48m1s
Queue Release Build / build-android (push) Successful in 22m7s
Queue Release Build / finalize (push) Successful in 2m42s
2026-06-09 17:59:54 +02:00
Myx
80d7728e66 fix: No longer displays edited on all messages and fix Disconnected from signaling server on multiple clients
All checks were successful
Queue Release Build / prepare (push) Successful in 19s
Deploy Web Apps / deploy (push) Successful in 8m19s
Queue Release Build / build-windows (push) Successful in 27m48s
Queue Release Build / build-linux (push) Successful in 47m35s
Queue Release Build / build-android (push) Successful in 21m15s
Queue Release Build / finalize (push) Successful in 2m30s
2026-06-07 15:05:12 +02:00
Myx
83456c018c fix: Fix multiple bugs with new authentication flow 2026-06-07 15:04:21 +02:00
Myx
9fc26b1ccf ci: fix apk build
All checks were successful
Queue Release Build / prepare (push) Successful in 23s
Deploy Web Apps / deploy (push) Successful in 6m35s
Queue Release Build / build-windows (push) Successful in 27m49s
Queue Release Build / build-linux (push) Successful in 44m3s
Queue Release Build / build-android (push) Successful in 20m59s
Queue Release Build / finalize (push) Successful in 2m40s
2026-06-05 18:37:17 +02:00
Myx
45675192a5 feat: Security 2026-06-05 18:34:01 +02:00
Myx
ee293d7daf feat: Rename to Toju and add translation
Some checks failed
Deploy Web Apps / deploy (push) Successful in 5m52s
Build Android APK / build-android-apk (push) Failing after 23m15s
Queue Release Build / prepare (push) Successful in 1m42s
Queue Release Build / build-linux (push) Failing after 9m33s
Queue Release Build / build-windows (push) Successful in 26m5s
Queue Release Build / finalize (push) Has been skipped
2026-06-05 17:17:29 +02:00
Myx
8ecfc9a1fe feat: Add slashcommand api 2026-06-05 17:12:26 +02:00
Myx
4070ef6caf perf: Add ram metric 2026-06-05 15:27:33 +02:00
Myx
a675f12e61 feat: Add deafen to pc, fix mobiel view, fix freeze on startup 2026-06-05 15:27:06 +02:00
635 changed files with 26959 additions and 3788 deletions

View File

@@ -195,7 +195,7 @@ export class LoginPage {
| ------------------- | ------------------ | ----------------------- |
| `/login` | `LoginPage` | `LoginComponent` |
| `/register` | `RegisterPage` | `RegisterComponent` |
| `/search` | `ServerSearchPage` | `ServerSearchComponent` |
| `/servers` | `FindServersPage` | `FindServersComponent` |
| `/room/:roomId` | `ChatRoomPage` | `ChatRoomComponent` |
| `/settings` | `SettingsPage` | `SettingsComponent` |
| `/invite/:inviteId` | `InvitePage` | `InviteComponent` |

View File

@@ -1,14 +1,6 @@
name: Build Android APK
on:
push:
branches: [main, master]
paths:
- 'toju-app/**'
- 'package.json'
- 'package-lock.json'
- 'tools/build-android-apk.sh'
- '.gitea/workflows/build-android-apk.yml'
workflow_dispatch:
jobs:
@@ -39,7 +31,14 @@ jobs:
- name: Install Android build toolchain
run: |
apt-get update
apt-get install -y --no-install-recommends openjdk-21-jdk wget unzip
apt-get install -y --no-install-recommends wget unzip ca-certificates gnupg
# node:22 is Debian Bookworm — openjdk-21-jdk is not in default repos.
install -d /etc/apt/keyrings
wget -qO - https://packages.adoptium.net/artifactory/api/gpg/key/public | gpg --dearmor -o /etc/apt/keyrings/adoptium.gpg
echo "deb [signed-by=/etc/apt/keyrings/adoptium.gpg] https://packages.adoptium.net/artifactory/deb bookworm main" > /etc/apt/sources.list.d/adoptium.list
apt-get update
apt-get install -y --no-install-recommends temurin-21-jdk
export ANDROID_SDK_ROOT=/opt/android-sdk
mkdir -p "$ANDROID_SDK_ROOT/cmdline-tools"
@@ -54,7 +53,7 @@ jobs:
echo "ANDROID_SDK_ROOT=$ANDROID_SDK_ROOT" >> "$GITHUB_ENV"
echo "ANDROID_HOME=$ANDROID_SDK_ROOT" >> "$GITHUB_ENV"
echo "JAVA_HOME=/usr/lib/jvm/java-21-openjdk-amd64" >> "$GITHUB_ENV"
echo "JAVA_HOME=/usr/lib/jvm/temurin-21-jdk-amd64" >> "$GITHUB_ENV"
echo "PATH=$PATH:$ANDROID_SDK_ROOT/cmdline-tools/latest/bin:$ANDROID_SDK_ROOT/platform-tools" >> "$GITHUB_ENV"
- name: Install dependencies
@@ -62,12 +61,39 @@ jobs:
NODE_ENV: development
run: npm ci
- name: Resolve release version
id: version
run: node tools/resolve-release-version.js --write-output
- name: Ensure draft release exists
id: release
env:
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
run: >
node tools/gitea-release.js ensure-draft
--server-url "${{ github.server_url }}"
--repository "${{ github.repository }}"
--tag "${{ steps.version.outputs.release_tag }}"
--target "${{ github.sha }}"
--name "${{ steps.version.outputs.release_name }}"
--body "Automated draft release from ${{ github.ref_name }} @ ${{ github.sha }}"
--write-output
- name: Build debug APK
run: bash tools/build-android-apk.sh
- name: Upload APK artifact
uses: https://github.com/actions/upload-artifact@v4
with:
name: metoyou-android-debug-apk
path: toju-app/android/app/build/outputs/apk/debug/app-debug.apk
if-no-files-found: error
- name: Stage Android APK
run: |
mkdir -p dist-android
cp toju-app/android/app/build/outputs/apk/debug/app-debug.apk \
"dist-android/Toju-${{ steps.version.outputs.release_version }}-android-debug.apk"
- name: Upload Android APK to draft release
env:
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
run: >
node tools/gitea-release.js upload-built-assets
--server-url "${{ github.server_url }}"
--repository "${{ github.repository }}"
--release-id "${{ steps.release.outputs.release_id }}"
--dist-android dist-android

View File

@@ -110,6 +110,87 @@ jobs:
--dist-electron dist-electron
--dist-server dist-server
build-android:
needs: prepare
runs-on: ubuntu-latest
container: node:22
steps:
- name: Checkout
uses: https://github.com/actions/checkout@v4
- name: Restore npm cache
uses: https://github.com/actions/cache@v4
with:
path: /root/.npm
key: npm-android-${{ hashFiles('package-lock.json') }}
restore-keys: npm-android-
- name: Restore Gradle cache
uses: https://github.com/actions/cache@v4
with:
path: |
/root/.gradle/caches
/root/.gradle/wrapper
key: gradle-android-${{ hashFiles('toju-app/android/**/*.gradle*', 'toju-app/android/gradle/wrapper/gradle-wrapper.properties') }}
restore-keys: gradle-android-
- name: Install Android build toolchain
run: |
apt-get update
apt-get install -y --no-install-recommends wget unzip ca-certificates gnupg
install -d /etc/apt/keyrings
wget -qO - https://packages.adoptium.net/artifactory/api/gpg/key/public | gpg --dearmor -o /etc/apt/keyrings/adoptium.gpg
echo "deb [signed-by=/etc/apt/keyrings/adoptium.gpg] https://packages.adoptium.net/artifactory/deb bookworm main" > /etc/apt/sources.list.d/adoptium.list
apt-get update
apt-get install -y --no-install-recommends temurin-21-jdk
export ANDROID_SDK_ROOT=/opt/android-sdk
mkdir -p "$ANDROID_SDK_ROOT/cmdline-tools"
cd /tmp
wget -q https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip
unzip -q commandlinetools-linux-11076708_latest.zip
mv cmdline-tools "$ANDROID_SDK_ROOT/cmdline-tools/latest"
export PATH="$PATH:$ANDROID_SDK_ROOT/cmdline-tools/latest/bin:$ANDROID_SDK_ROOT/platform-tools"
yes | sdkmanager --licenses >/dev/null
sdkmanager "platform-tools" "platforms;android-36" "build-tools;35.0.0"
echo "ANDROID_SDK_ROOT=$ANDROID_SDK_ROOT" >> "$GITHUB_ENV"
echo "ANDROID_HOME=$ANDROID_SDK_ROOT" >> "$GITHUB_ENV"
echo "JAVA_HOME=/usr/lib/jvm/temurin-21-jdk-amd64" >> "$GITHUB_ENV"
echo "PATH=$PATH:$ANDROID_SDK_ROOT/cmdline-tools/latest/bin:$ANDROID_SDK_ROOT/platform-tools" >> "$GITHUB_ENV"
- name: Install dependencies
env:
NODE_ENV: development
run: npm ci
- name: Set CI release version
run: >
node tools/set-release-version.js
--version "${{ needs.prepare.outputs.release_version }}"
- name: Build debug APK
run: bash tools/build-android-apk.sh
- name: Stage Android APK
run: |
mkdir -p dist-android
cp toju-app/android/app/build/outputs/apk/debug/app-debug.apk \
"dist-android/Toju-${{ needs.prepare.outputs.release_version }}-android-debug.apk"
- name: Upload Android APK
env:
GITEA_RELEASE_TOKEN: ${{ secrets.RELEASE_TOKEN }}
run: >
node tools/gitea-release.js upload-built-assets
--server-url "${{ github.server_url }}"
--repository "${{ github.repository }}"
--release-id "${{ needs.prepare.outputs.release_id }}"
--dist-android dist-android
build-windows:
needs: prepare
runs-on: windows

1
.gitignore vendored
View File

@@ -59,6 +59,7 @@ Thumbs.db
.env
.certs/
/server/data/variables.json
/server/data/metoyou.sqlite
dist-server/*
doc/**

View File

@@ -124,7 +124,8 @@ Behavioral changes to any of these qualify as a feature-doc update under the rul
- `release-draft.yml` — queues release builds on push to `main` / `master`
- `publish-draft-release.yml` — publishes draft releases
- `deploy-web-apps.yml` — deploys the marketing site and Docusaurus docs
- `build-android-apk.yml`builds a debug Capacitor Android APK on push (mobile-related paths) or manual dispatch; uploads `app-debug.apk` as a workflow artifact
- `build-android-apk.yml`manual **workflow_dispatch** debug Capacitor Android APK build; uploads `Toju-<version>-android-debug.apk` to the draft release (same path as desktop assets)
- `release-draft.yml` job `build-android` — builds and uploads the debug APK to each queued draft release alongside desktop/server archives
- All checks must pass before merging a PR
- Workflow status is visible in the Gitea PR view; use the web UI or `tea` CLI to inspect runs

View File

@@ -8,7 +8,10 @@ It must stay accurate as new features are introduced, renamed, merged, or remove
## Feature list (alphabetical)
- [App i18n](features/app-i18n.md) — `@ngx-translate/core` localization for the product client; English-only catalog today, same stack as the marketing website.
- [Authentication](features/authentication.md) — signaling-server session tokens, protected REST/WebSocket identity, and client bearer storage.
- [Custom Emoji](features/custom-emoji.md) — peer-synced user-created emoji assets, chat reaction shortcuts, and composer emoji insertion.
- [Message Integrity](features/message-integrity.md) — signed P2P message revision chains, inventory `headHash` convergence, and Ed25519 signing-key registration on the signaling server.
- [Mobile Capacitor](features/mobile-capacitor.md) — Capacitor native shell, mobile infrastructure facades, and phone-specific call/chat/media integrations.
- [Server Discovery](features/server-discovery.md) — featured/trending public-server REST endpoints (server) consumed by the `/dashboard` and `/servers` client pages.
- [Signal Server Tag](features/signal-server-tag.md) — configurable signal-server display tag shown on profile cards for a user's registration server.

View File

@@ -25,6 +25,104 @@ Durable rules for AI agents working on this project. Read this file at session s
## Lessons
### When renaming an Angular route, sweep every navigate/url-match/doc reference [routing]
- **Trigger:** the find-servers route was renamed `/search``/servers` in `app.routes.ts`, but `servers-rail.component.ts` still called `router.navigate(['/search'])` (leave-server) and matched `startsWith('/search')` for the user-bar visibility signal, throwing `NG04002: 'search'` on leave and never showing the user-bar on the discovery page.
- **Rule:** after changing a `path:` in `app.routes.ts`, grep the whole repo for the old literal (`/search`) across `*.ts`/`*.html` (router calls, `startsWith`/url-match signals) and docs (`docs-site`, `.agents/skills/playwright-e2e/SKILL.md` route tables, domain READMEs) and update them all in the same change.
- **Why:** `router.navigate` to a non-existent path raises `NG04002` and aborts navigation, and stale `startsWith` matches silently break route-derived UI state — neither is caught by the build (string literals) and there was no `servers-rail` spec to catch it.
- **Example:** fixed `isOnServers`/`router.navigate(['/servers'])` in `servers-rail.component.{ts,html}`; canonical post-leave/discovery route is `/servers` (`FindServersComponent`), matching `DashboardComponent`'s `router.navigate(['/servers'])`.
### Server discovery (featured/trending) must fan out across all online endpoints like search [server-directory]
- **Trigger:** the `/servers` (find-servers) page showed no servers by default but found them as soon as the user typed in the search box. Discovery (`getDiscoveryServers`) queried only the *active* endpoint via `getApiBaseUrl()`, and when that endpoint is a discovery-unsupported production host (`signal.toju.app` / `signal-sweden.toju.app` in `DISCOVERY_UNSUPPORTED_HOSTS`) it short-circuited to `[]`; search meanwhile fans out across every online endpoint, so typing surfaced the servers that lived on other endpoints (e.g. localhost).
- **Rule:** make `getFeaturedServers`/`getTrendingServers` fan out across `getSearchableEndpoints()` with `forkJoin` + `deduplicateById` (mirroring all-endpoint search), and apply the `endpointSupportsServerDiscovery` gate *per endpoint* (skip → `[]`) instead of short-circuiting the whole request on the active endpoint.
- **Why:** the empty-query find-servers view renders discovery sections, not search results, so any divergence between discovery's endpoint set and search's endpoint set makes the default view look broken while search works.
- **Example:** `getDiscoveryServers` + `fetchDiscoveryFromEndpoint` in `server-directory-api.service.ts`; verified the live server returns 12 featured/12 trending while the active production host is gated out client-side.
### Server registration needs `ownerPublicKey: oderId || id`, and must not be fire-and-forget [server-directory] [rooms]
- **Trigger:** creating a server appeared to work (the creator landed in the room view) but the server didn't exist on the backend — invite-link creation and search both 404'd. `createRoom$` sent `ownerPublicKey: currentUser.oderId` with no fallback; on restored sessions `oderId` can be falsy (identify still works because it falls back to `id`), so `POST /api/servers` returned `400 Missing required fields`, and the `.subscribe()` swallowed the error while `createRoomSuccess` fired regardless.
- **Rule:** resolve owner identity as `oderId || id` everywhere it's required (the server rejects an empty `ownerPublicKey`), and give `registerServer().subscribe()` an `error` handler so a failed registration is never silent.
- **Why:** verified against the live server — authed POST with a truthy `ownerPublicKey` → 201; authed POST with an empty one → 400; the swallowed 400 is exactly what produces a "ghost" room the creator can enter but no one can find.
- **Example:** `buildServerRegistrationPayload(room, currentUser, normalizedPassword)` in `toju-app/src/app/store/rooms/server-registration.rules.ts`, used by `RoomsEffects.createRoom$`.
### Identify must fall back to the legacy session token, not only the new credential store [realtime] [authentication]
- **Trigger:** the multi-signal-server auth refactor changed `resolveCredentialForSignalUrl` to read *only* `SignalServerCredentialStoreService`; sessions restored from disk (and logins where `user.homeSignalServerUrl` is unset) have an empty credential store, so `identify` was skipped on every signal server ("Skipping identify because no session token is available") and users appeared alone — no presence, no peers, sent messages visible only to themselves. E2E never caught it because every e2e flow does a *fresh* register/login that writes the credential store directly.
- **Rule:** when resolving the identify credential for a signal URL, prefer the per-signal credential but fall back to the legacy `AuthTokenStoreService` token reconstructed with the current home user's `id`/`displayName`; never gate `identify` solely on the new credential store.
- **Why:** `persistSessionToken` always writes the legacy `metoyou.authTokens` store on login, but the per-signal credential store is only populated on fresh login (with a `loginResponse`) or successful migration/provisioning — so on reload it can be empty while a valid session still exists.
- **Example:** `resolveSignalIdentity(credential, legacyTokenEntry, homeUser)` in `signal-server-credential-resolution.rules.ts`, wired through `SignalServerAuthService.resolveCredentialForSignalUrl` (which now passes `this.authTokenStore.getTokenEntry(httpUrl)` and a `homeUser` carrying `id`). Test cross-user behavior via a *session-restore* path, not just fresh login.
### Keep the per-signal-URL identify credential resolvable from the store [realtime] [authentication]
- **Trigger:** after the multi-signal-server auth refactor, `SignalingManager.getLastIdentify` was switched to `getIdentifyCredentialsForSignalUrl`, which only read an in-memory cache populated *after* `identify()` ran; a freshly (re)connected socket then emitted `join_server` before any identify and users silently never appeared in the presence roster (almost all multi-user e2e tests timed out waiting for the peer's `room-user-card`).
- **Rule:** `getIdentifyCredentialsForSignalUrl` must fall back to resolving the credential from the credential store so a new socket's `onopen` re-identifies before it re-joins; never restrict it to only the in-memory identify cache.
- **Why:** the server drops `join_server`/`view_server` on any unauthenticated connection, so an identify-less join is lost with no error and recovery only happens on a later reconnect (often beyond the 20s test timeout).
- **Example:** server log showed `join_server authed=false ... display=User` dropped, then `User identified: Alice` on a different connection but no `Alice joined server`; fixed in `signaling-transport-handler.ts` by resolving via `dependencies.resolveCredential(signalUrl)` when the cache is empty.
### Store clientInstanceId in sessionStorage not localStorage [realtime] [multi-device]
- **Trigger:** same user logged in on two tabs, browsers, or synced profiles sees alternating "Disconnected from signaling server" and no cross-device chat/voice sync.
- **Rule:** persist `metoyou.clientInstanceId` in `sessionStorage` (one id per tab/window) and clear any legacy `localStorage` copy on first read.
- **Why:** server identify evicts stale sockets with the same `(oderId, connectionScope, clientInstanceId)` tuple; a shared localStorage id makes each client kick the other in a reconnect loop.
- **Example:** `ClientInstanceService.getClientInstanceId()` writes to `sessionStorage`; two tabs get different ids and stay connected simultaneously.
### Revalidate IndexedDB scope without reinitializing on every read [persistence] [performance]
- **Trigger:** `DatabaseService.ensureReady()` called `initialize()` before every delegated read/write to fix user-scope races.
- **Rule:** cache the last validated `metoyou_currentUserId` and only re-run backend initialization when that scope changes or an in-flight initialize completes with a different scope.
- **Why:** per-operation revalidation fans out across ban lookups, room loads, and message reads, causing channel/chat UI to stay blank until repeated server clicks eventually win the race.
- **Example:** `ensureReady()` returns immediately when `isReady()` and `validatedUserScope` still match `getStoredCurrentUserId()`.
### Restore local user scope before protected writes [authentication] [persistence]
- **Trigger:** a logged-in in-memory user can create rooms or messages after `metoyou_currentUserId` was cleared by a late session-expired path.
- **Rule:** before protected local persistence or server-directory actions, restore `metoyou_currentUserId` from the current user and avoid treating a live current user as unauthenticated.
- **Why:** otherwise rooms/messages fall into the anonymous IndexedDB scope, and route checks redirect to login even though NgRx still has the authenticated user.
- **Example:** `MessagesEffects.sendMessage$`, `RoomsEffects.createRoom$`, and server-directory create/join components call `setStoredCurrentUserId(currentUser.id)` before writing or joining.
### Persisted local user state still requires a session token [authentication] [signaling]
- **Trigger:** Users appear logged in from local storage but cannot see peers online or send chat after session-token auth shipped.
- **Rule:** before connecting signaling or loading rooms for a persisted user, require a non-expired token in `metoyou.authTokens`; redirect to `/login` on `SESSION_EXPIRED`, `auth_required`, or `auth_error`.
- **Why:** WebSocket `identify` is skipped without a token, so `join_server`, RTC relay, and presence never establish even though the profile exists locally.
- **Example:** `hasValidPersistedSession()` in `auth-session.rules.ts` from `loadCurrentUser$`.
### Declare MODIFY_AUDIO_SETTINGS for Android WebRTC mic capture [mobile] [android]
- **Trigger:** Android users accept the microphone prompt but voice calls and channels still fail to join.
- **Rule:** include `android.permission.MODIFY_AUDIO_SETTINGS` in `toju-app/android/app/src/main/AndroidManifest.xml` and preflight Capacitor capture through `MobileMediaService.ensureVoiceCapturePermissions()` before `getUserMedia`.
- **Why:** Capacitor's `BridgeWebChromeClient.onPermissionRequest` requests `RECORD_AUDIO` and `MODIFY_AUDIO_SETTINGS` together; if the latter is undeclared, the combined grant is treated as denied even after the user taps Allow.
- **Example:** `ANDROID_REQUIRED_MANIFEST_PERMISSIONS` in `mobile-android-manifest-permissions.rules.ts`.
### Do not override Tailwind with box-sizing inherit [mobile] [css]
- **Trigger:** mobile pages still overflow horizontally until devtools disables `*, *::before, *::after { box-sizing: inherit }` in global styles.
- **Rule:** in `src/styles.scss` keep `box-sizing: border-box` on the universal selector (matching Tailwind preflight); never replace it with `inherit` from `html`.
- **Why:** `inherit` overrides preflight and some nested component hosts resolve to `content-box`, so `w-full` plus padding becomes wider than the parent — especially visible on the mobile dashboard beside the servers rail.
- **Example:** `src/styles.scss` `@layer base` universal rule uses `border-box`, not `inherit`.
### Use the app-shell servers rail for mobile discovery pages [mobile] [layout]
- **Trigger:** patching `min-w-0` / `overflow-x-hidden` on the dashboard (or find-people/find-servers) while the page still renders wider than the phone beside an embedded servers rail.
- **Rule:** on mobile discovery routes (`/dashboard`, `/people`, `/servers`, …) show the global `app.html` servers rail and render the page full-width in `appWorkspace`; keep embedded swiper+rail stacks only for chat/DM/call routes (`shouldShowMobileAppServersRail` in `mobile-shell-layout.rules.ts`).
- **Why:** nesting a second rail+Swiper stack inside `router-outlet` fights the shell flex width and content keeps sizing to intrinsic width, clipping cards and inputs on every viewport.
- **Example:** `hideAppServersRail()` in `app.html` + dashboard `pageContent` only (no local `<app-servers-rail>`).
### Defer attachment blob hydration on Electron startup [attachments] [electron]
- **Trigger:** fixing inline attachment display by eagerly calling `tryRestoreAttachmentFromLocal()` for every persisted attachment during `initFromDatabase()`.
- **Rule:** load attachment metadata at startup, but hydrate blob URLs only for the watched room on demand; read disk files through chunked IPC (`readFileChunk`) and yield between chunks/attachments so large images never block the renderer.
- **Why:** restoring every saved attachment as a single base64 round-trip plus synchronous `atob()` can freeze Electron for seconds even after the shell paints.
- **Example:** `runInitFromDatabase()` stops at `loadFromDatabase()`; `restoreLocalAttachmentsForRoom()` hydrates lazily via `restoreAttachmentBlobFromDiskPath()`.
### Lazy-load Capacitor modules on Electron/desktop [mobile] [electron]
- **Trigger:** adding mobile facades that statically import Capacitor adapters or `@capacitor/*` plugins into shared Angular services used by the desktop app.
- **Rule:** keep web/electron shells on web adapters synchronously and load Capacitor adapters/plugins only through dynamic `import()` after `runtime === 'capacitor'` — never top-level `import '@capacitor/...'` in code reachable from `app.ts` / `DirectCallService`.
- **Why:** bundlers evaluate static Capacitor imports during Electron startup, which can freeze the renderer before first paint even when runtime detection would have chosen the web adapter.
- **Example:** `resolveMobileAdapter()` in `mobile-capacitor-adapter.rules.ts` plus async `capacitor-plugin-loader.ts` / `loadMetoyouMobilePlugin()`.
### Use the upgrade transaction during IndexedDB schema migrations [persistence] [browser]
- **Trigger:** bumping `BROWSER_DATABASE_VERSION` and opening existing stores via `database.transaction(...)` inside `onupgradeneeded`.

View File

@@ -0,0 +1,13 @@
# ADR-0002: Session-Token Authentication on the Signaling Server
## Status
Accepted
## Context
The signaling server trusted client-supplied user IDs on REST mutations and WebSocket `identify`, allowing impersonation for kicks, bans, joins, plugin administration, and push dispatch. The product client already used bearer tokens for the Electron Local API, but the shared signaling server had no equivalent binding between HTTP/WebSocket actions and a logged-in user.
## Decision
Issue opaque session tokens on login/register, persist them in server SQLite, require `Authorization: Bearer` on all mutating REST routes, and require `identify.token` on WebSocket connections before any other client message is accepted. Actor fields (`currentOwnerId`, `actorUserId`, `requesterUserId`) are derived from the token instead of request bodies.
## Rationale
This closes identity spoofing without changing the P2P product model: discovery stays public, chat/media still relay over WebSocket, and DM WebRTC signaling remains available across servers. Bcrypt password hashing with transparent SHA-256 upgrade preserves existing accounts. A deprecation window for body-only auth was intentionally omitted so all clients must authenticate in one release, avoiding prolonged dual-trust behavior.

View File

@@ -0,0 +1,16 @@
# ADR-0003: Multi-Client Sessions with Connection-Scoped Routing
## Status
Accepted
## Context
Users expect to stay logged in on multiple devices simultaneously (Discord-style). The signaling server already issued multiple session tokens per user, but WebSocket broadcasts deduplicated by `oderId`, which prevented a user's second device from receiving chat, typing, or voice-state updates from their first device. Voice had no per-device identity, so two clients could both attempt to transmit audio.
## Decision
Introduce a stable per-install `clientInstanceId` on the product client. Route server broadcasts by **connection id** (exclude only the sender socket) while keeping presence `user_joined` / `user_left` identity-scoped. Track `voiceActive` per connection; relay RTC to the voice-active socket. Enforce single voice owner per user via `VoiceState.clientInstanceId` and `voice_client_takeover` handoff between connections.
## Consequences
- **Positive:** Chat and presence sync across a user's devices; voice behaves like Discord (one transmitting client, passive viewers, explicit takeover).
- **Positive:** Stale-tab hygiene uses `(oderId, connectionScope, clientInstanceId)` eviction without kicking other devices.
- **Negative:** `findUserByOderId` semantics change — RTC now prefers voice-active connections; callers must not assume one socket per user.
- **Negative:** Clients must include `clientInstanceId` on identify and voice payloads; older builds without it still work but cannot participate in multi-device voice exclusivity reliably.

View File

@@ -0,0 +1,23 @@
# ADR-0003: Signed Message Revision Chains for P2P Chat Integrity
## Status
Accepted
## Context
P2P chat sync compared timestamps, reaction counts, and attachment counts only. A peer could rewrite history or apply edits out of order with no cryptographic check. The product has no central message store, so integrity must travel with sync traffic and local audit logs.
## Decision
Adopt an append-only **revision chain** per message:
- Each mutation emits a `MessageRevision` (create, edit, delete, moderation, plugin) with `revision`, `prevRevisionHash`, and `headHash` (SHA-256 over canonical head state).
- Inventories advertise `{ revision, headHash }` so peers detect gaps and hash mismatches.
- Human-authored revisions are signed with per-user Ed25519 keys; public keys are registered on the signaling server for verification.
- Legacy `chat-message` / `message-edited` / `message-deleted` events continue to broadcast alongside `message-revision` for one-release backward compatibility.
## Rationale
Revision chains give deterministic merge (higher valid revision wins) without requiring a trusted relay. Signing binds edits to registered users while keeping chat payloads off the server. Dual emit avoids breaking peers that have not upgraded inventory or revision handlers yet.
## Consequences
- New persistence columns and revision audit stores on browser IDB, Electron SQLite, and Capacitor schemas.
- Plugin synthetic users may emit unsigned revisions until a plugin signing model exists.
- Attachment byte integrity (SHA-256 on `file-announce`) remains a separate follow-up.

View File

@@ -0,0 +1,62 @@
# App i18n
Client-side UI string localization for the product client (`toju-app`), using the same `@ngx-translate/core` stack as the marketing website.
## Responsibilities
- Bundle locale JSON under `toju-app/public/i18n/`.
- Bootstrap translations at app startup via `AppI18nService` (root `App` constructor).
- Expose `APP_TRANSLATE_IMPORTS` for standalone components that use the `translate` pipe in templates.
- Resolve the active locale through `resolveAppLocale()` in `app-i18n.rules.ts`.
## Boundaries
- **In scope:** user-visible UI copy in the Angular product client.
- **Out of scope:** server error messages, plugin-authored strings, Electron IPC payloads, and marketing-site copy (`website/public/i18n/`).
## Key files
| Path | Role |
|------|------|
| `toju-app/public/i18n/en.json` | English translation catalog (only locale shipped today). |
| `toju-app/src/app/core/i18n/app-i18n.rules.ts` | Supported locales and locale resolution. |
| `toju-app/src/app/core/i18n/app-i18n.service.ts` | Loads bundled JSON into `TranslateService`. |
| `toju-app/src/app/core/i18n/app-translate.imports.ts` | `TranslateModule` import bundle for standalone components. |
| `toju-app/src/app/app.config.ts` | `provideTranslateService()` registration. |
## Usage
**Templates** — import `APP_TRANSLATE_IMPORTS` in the standalone component and use the pipe:
```html
{{ 'common.brand' | translate }}
```
**TypeScript** — inject `AppI18nService` (or `TranslateService`) and call `instant()`:
```ts
this.appI18n.instant('common.brand');
```
## Catalog workflow
User-visible strings live in fragment files under `toju-app/public/i18n/catalog/*.json`, merged into `toju-app/public/i18n/en.json` by:
```bash
npm run i18n:sync
```
The sync script also extracts `theme.registry.*` labels/descriptions from `theme-registry.logic.ts` and `permissions.*` from `access-control.constants.ts` so those large registries stay DRY. Extracted prefixes use dotted paths and are merged as nested JSON (e.g. `theme.registry.appShell.label`, not a flat `"theme.registry"` root key).
## Adding a locale later
1. Add `toju-app/public/i18n/catalog/*.json` fragments for the new locale (or mirror `en.json` structure).
2. Register the locale in `SUPPORTED_APP_LOCALES`.
3. Import and `setTranslation()` in `AppI18nService`.
4. Wire user preference (e.g. general settings) to `AppI18nService.initialize(preferredLocale)`.
## Tests
- `toju-app/src/app/core/i18n/app-i18n.rules.spec.ts`
- `toju-app/src/app/core/i18n/app-i18n.service.spec.ts`
- `toju-app/src/app/core/i18n/app-i18n.testing.ts``provideAppI18nForTests()` / `initializeAppI18nForTests()` for Vitest injectors

View File

@@ -0,0 +1,124 @@
# Authentication
Session-token authentication for the signaling server and product client.
## Trust boundaries
| Surface | Identity proof | Notes |
|---|---|---|
| Signaling server REST (mutations) | `Authorization: Bearer <token>` | Actor user IDs in request bodies are ignored; server derives `authUserId` from the token |
| Signaling server REST (discovery) | None | `GET /api/servers`, featured/trending/search remain public |
| Signaling server WebSocket | `identify.token` | Connections must identify before any other message type |
| Electron Local API | Separate in-memory bearer tokens | Proxies login to allowed signaling servers only |
| Product client local DB | OS user account | SQLite and attachments are plaintext at rest |
## Login / register response
```json
{
"id": "<uuid>",
"username": "alice",
"displayName": "Alice",
"token": "<opaque-hex>",
"expiresAt": 1710000000000
}
```
- Tokens are opaque 64-character hex strings stored in server SQLite (`session_tokens`).
- Default TTL: 10 years (`SESSION_TOKEN_TTL_MS` env override supported on the signaling server).
- Passwords are stored with bcrypt; legacy SHA-256 hashes are upgraded transparently on successful login.
## Protected REST routes
Require `Authorization: Bearer`:
- `PUT/POST/DELETE` under `/api/servers/*` (except public `GET`)
- `PUT /api/requests/:id`
- Plugin-support mutations under `/api/servers/:serverId/plugins/*`
- `/api/users/device-tokens/*`
- `POST /api/users/logout`
## WebSocket identify contract
```json
{
"type": "identify",
"token": "<session-token>",
"oderId": "<user-id>",
"displayName": "Alice",
"connectionScope": "ws://host:3001",
"clientInstanceId": "<per-install-uuid>"
}
```
- `oderId` must match the token's user id when provided.
- `clientInstanceId` is a stable per-tab UUID generated by the product client (`metoyou.clientInstanceId` in `sessionStorage`). The signaling server uses it to distinguish multiple WebSocket connections for the same user and to route voice ownership.
- Server responds with `auth_error` or `auth_required` when authentication fails.
## Multi-device sessions
- Each login/register issues a **new** session token; prior tokens remain valid until they expire or the client calls `POST /api/users/logout` with that token.
- The same user may keep multiple WebSocket connections open (different devices or browser profiles). Server broadcasts (chat, typing, voice state, status) exclude only the **sending connection**, so other connections for that identity still receive updates.
- Voice/WebRTC is exclusive per user: only one `clientInstanceId` may own active voice at a time. Other connections show passive UI and can send `voice_client_takeover` to move voice to the local device.
- Stale reconnect hygiene: when a client re-identifies with the same `(oderId, connectionScope, clientInstanceId)` tuple, the server closes the older socket for that tuple.
### Account-owned state sync (`account_sync`)
When the same account is logged in on multiple devices, account-owned data is kept in sync through the signaling server:
| Data | Mechanism |
|---|---|
| Server chat messages | Existing `chat_message` relay (connection-scoped broadcast) |
| Voice / typing | Existing `voice_state` / `user_typing` relays |
| Saved servers (join/leave) | `account_sync` payload `saved-room-sync` / `saved-room-remove` |
| Profile avatar + card text | `account_sync` `user-avatar-full` + `user-avatar-chunk` |
| Custom emoji library | `account_sync` `custom-emoji-full` + `custom-emoji-chunk` |
| Friends list | `account_sync` `friend-added` / `friend-removed` |
| Server icons, edits, reactions | `account_sync` relay of existing P2P broadcast event types |
Client rules:
- `broadcastMessage()` still fans out over peer data channels; relayable events are **also** wrapped in `account_sync` and sent on the WebSocket.
- The server forwards `account_sync` to every other open connection for the same `oderId` via `notifyOtherConnectionsForOderId`.
- Receivers ignore payloads whose `clientInstanceId` matches the local tab id.
- When a new device identifies, the server notifies existing connections with `account_sync_peer_online`; those devices push a full snapshot (saved rooms, friends, profile, emoji library).
WebSocket envelope:
```json
{
"type": "account_sync",
"clientInstanceId": "<per-tab-uuid>",
"payload": { "type": "saved-room-sync", "room": { "...": "..." } }
}
```
Server response to other connections includes `fromUserId` set to the sender's `oderId`.
## Client storage
The product client stores tokens per signaling-server base URL in `localStorage` (`metoyou.authTokens`). An HTTP interceptor attaches the bearer token to `/api/*` requests targeting that server.
Per-server credentials (`metoyou.signalServerCredentials`) map each normalized signal-server URL to the authenticated user id, username, display name, session token, expiry, and whether the account was auto-provisioned. The home user profile in SQLite/NgRx remains the device-local identity (`homeSignalServerUrl`); foreign-server credentials are a side map used for REST and WebSocket identify on that URL.
A per-install **provision secret** enables silent account creation on newly added or encountered signal servers. It is generated on home register/login, stored in Electron `safeStorage` when available (sessionStorage fallback on web), and never persisted as the user's visible login password.
### Multi-signal-server auth flows
| Flow | Action | Effect |
|---|---|---|
| Home login/register | `authenticateUser` | Resets local state, stores home credential + provision secret |
| Foreign login/register | `authorizeSignalServer` | Upserts credential for that URL only; home session unchanged |
| Auto-provision | `SignalServerProvisionerService` | Registers or logs in on foreign server using provision secret; on username collision tries suffixed username (`alice-<homeUserIdPrefix>`) |
| Foreign auth failure | `signalServerAuthFailed` | Clears that URL's credential and re-provisions when home token is still valid; global logout only when home server rejects auth |
Authorize UI: `/login?mode=authorize&serverId=…&returnUrl=…` (also supported on `/register`). Settings → Network shows per-endpoint `Authorized` / `Needs sign-in` badges.
Persisted local user state (`metoyou_currentUserId` + IndexedDB/SQLite profile) is **not** sufficient to use chat or presence. On startup, `loadCurrentUser$` requires a non-expired session token for the user's home signaling server (or any stored token as a fallback). Missing or rejected **home** tokens dispatch `SESSION_EXPIRED` and redirect to `/login`. Foreign-server `auth_required` / `auth_error` responses clear only that server's credential and attempt re-provision.
## Security considerations
- Rate limits: login/register (100 / 15 min), server join (30 / min).
- CORS allowlist: optional `corsAllowlist` in `server/data/variables.json` or `CORS_ALLOWLIST` env (comma-separated). Empty allowlist keeps permissive CORS for local development.
- Push-token routes require bearer auth and user-id match.
- RTC relay: direct-message/direct-call types always relay; server-icon types require shared server membership; WebRTC offer/answer/ice remain open for cross-server DM WebRTC.

View File

@@ -0,0 +1,60 @@
# Message Integrity
Signed, append-only **message revisions** give P2P chat a verifiable history without central message storage. The materialized `Message` row in local SQLite/IDB is a cache; peers converge via inventory snapshots and revision events.
## Responsibilities
- **Revision chain** — Every create, edit, delete, moderation, or plugin mutation appends a `MessageRevision` with monotonically increasing `revision`, `prevRevisionHash`, and `headHash`.
- **Dual emit** — Outgoing mutations broadcast the legacy event (`chat-message`, `message-edited`, `message-deleted`) **and** `message-revision` so older peers keep working while integrity-aware peers prefer revisions.
- **Inventory** — Sync inventories include `{ id, ts, rc, ac, revision, headHash }`. Peers re-fetch when remote revision is newer or the same revision has a different hash (tamper detection).
- **Signing** — Human authors sign revisions with per-user Ed25519 keys. Public keys are registered on the signaling server; private keys stay in browser `localStorage`.
## Boundaries
| Layer | Owns |
| --- | --- |
| Product client (`toju-app`) | Revision construction, merge, verification, P2P broadcast, local persistence |
| Signaling server (`server`) | `PUT /api/users/me/signing-key`, `GET /api/users/:id/signing-public-key` — key directory only, no message storage |
| Electron / mobile persistence | `revision` + `headHash` on message rows; revision audit log (IDB store / SQLite meta) |
Plugin API messages may emit unsigned revisions (`plugin-edit` / `plugin-delete`) when the actor is a synthetic plugin user.
## Key types
- `Message.revision`, `Message.headHash` — materialized cache fields on the shared `Message` model.
- `MessageRevision` — wire + persistence audit record (`message-revision.models.ts`).
- `MessageRevisionType``create`, `author-edit`, `author-delete`, `moderate-edit`, `moderate-delete`, `plugin-edit`, `plugin-delete`.
- `ChatEvent.type: 'message-revision'` — P2P envelope carrying a full `MessageRevision`.
## Merge rules
1. Valid signed revision with higher `revision` wins over legacy timestamp edits.
2. Same `revision`, different `headHash` → treat as stale/tampered and re-fetch.
3. Unsigned revisions (no `signature`) are accepted for backward compatibility when verification is skipped.
4. Legacy peers without `revision`/`headHash` in inventory fall back to `ts` / `rc` / `ac` comparison.
## Client touchpoints
- Domain rules: `message-integrity.rules.ts`, `message-revision.builder.rules.ts`, `message-sync.rules.ts`
- Services: `MessageRevisionService`, `MessageSigningService`
- Store: `messages.effects.ts` (outgoing dual-emit), `messages-incoming.handlers.ts` (`handleMessageRevision`), `messages.helpers.ts` (inventory + merge)
- Plugins: `plugin-client-api.service.ts` emits revisions for send/edit/delete
## Server API
| Method | Path | Auth | Body / response |
| --- | --- | --- | --- |
| `PUT` | `/api/users/me/signing-key` | Bearer | `{ publicKeyJwk }` — stores Ed25519 public JWK on the user row |
| `GET` | `/api/users/:id/signing-public-key` | Public | `{ publicKeyJwk }` — used by peers to verify signatures |
Registration runs automatically after login/register via `AuthenticationService`.
## Degraded-mode behavior
- Outgoing revision signing is **best-effort**: if `Ed25519` signing fails, the client still broadcasts the legacy `chat-message` envelope (unsigned revision).
- Incoming signed revisions are accepted without cryptographic verification when the sender's public key is not yet registered on the server, so chat is not blocked during key-registration races.
## Testing
- Unit: `message-integrity.rules.spec.ts`, `message-revision.builder.rules.spec.ts`, `message-revision-signing.rules.spec.ts`, `message-sync.rules.spec.ts`, `messages-incoming.handlers.spec.ts`
- Outgoing revision wiring is covered indirectly through existing message effect tests; add focused specs when changing merge or signing behavior.

View File

@@ -4,7 +4,7 @@ Cross-context mobile shell for the Angular product client (`toju-app/`). Wraps t
## Responsibilities
- Detect runtime shell (`browser`, `capacitor`, `electron`) without importing native plugins in domain code.
- Detect runtime shell (`browser`, `capacitor`, `electron`) without importing native plugins in domain code. Capacitor packages and adapters load only on `capacitor` shells via dynamic `import()` so Electron/desktop startup never evaluates `@capacitor/*` modules.
- Expose facades for notifications, in-call controls, media/attachments, stream pop-out, background audio session, CallKit, and native persistence.
- Integrate with direct-call, voice-workspace, and chat composer flows.
@@ -48,13 +48,15 @@ Config: `toju-app/capacitor.config.ts` (`webDir: ../dist/client/browser`).
### CI (Gitea)
Workflow `.gitea/workflows/build-android-apk.yml` runs automatically on push to `main` / `master` when mobile client paths change (`toju-app/**`, root lockfile, or the workflow itself). Use **workflow_dispatch** to build on demand from any branch.
Release workflow `.gitea/workflows/release-draft.yml` builds a debug Android APK on every push to `main` / `master` (job `build-android`), stages it as `Toju-<version>-android-debug.apk`, and uploads it to the same draft Gitea release as the desktop `.exe` / `.deb` assets via `tools/gitea-release.js`.
The job installs JDK 21 and Android SDK platform 36 inside the `node:22` container, runs `tools/build-android-apk.sh`, and uploads `metoyou-android-debug-apk` (`app-debug.apk`) as a workflow artifact. No signing keystore is configured — output is a **debug** APK suitable for sideloading and QA.
Manual-only workflow `.gitea/workflows/build-android-apk.yml` (**workflow_dispatch**) repeats the same build and release upload on demand from any branch.
Both jobs install JDK 21 and Android SDK platform 36 inside the `node:22` container and run `tools/build-android-apk.sh`. No signing keystore is configured — output is a **debug** APK suitable for sideloading and QA.
Optional `google-services.json` is not injected in CI; push registration in artifact builds follows the same optional-Firebase behavior as local unsigned debug builds.
After dependency or plugin changes, run `npm run build:prod && npm run cap:sync` so native projects register `@capacitor/app`, `@capacitor-community/sqlite`, push plugins, and `MetoyouMobile`.
After dependency or plugin changes, run `npm run build:prod && npm run cap:sync` so native projects register `@capacitor/app`, `@capacitor-community/sqlite`, `@capawesome/capacitor-app-update`, push plugins, and `MetoyouMobile`.
## Feature status
@@ -71,6 +73,7 @@ After dependency or plugin changes, run `npm run build:prod && npm run cap:sync`
| Camera sharing | **Working** | Existing `getUserMedia` camera path in WebRTC stack |
| Speakerphone | **Working (partial)** | Android `AudioManager` via `MetoyouMobile`; iOS `@capgo/capacitor-audio-session`; direct-call speaker toggle on native mobile |
| Local DB (SQLite) | **Working** | `DatabaseService` routes Capacitor shells to `CapacitorDatabaseService` (native SQLite CRUD) |
| Store app updates | **Working (partial)** | `@capawesome/capacitor-app-update` via `MobileAppUpdateService`; Android in-app updates when Play allows, iOS opens App Store |
## Platform limitations
@@ -91,9 +94,26 @@ The app starts without Firebase. `MobilePushRegistrationService` probes `Metoyou
2. Copy `toju-app/android/app/google-services.json.example` to `google-services.json` (gitignored) and fill in your Firebase values.
3. Run `npm run cap:sync` so the Google Services Gradle plugin applies when the file is present (`build.gradle` applies it only when the JSON exists).
4. Rebuild with `npm run cap:build:android`.
5. Ensure `POST_NOTIFICATIONS`, `RECORD_AUDIO`, and foreground-service permissions are granted on Android 13+.
5. Ensure `POST_NOTIFICATIONS`, `RECORD_AUDIO`, `MODIFY_AUDIO_SETTINGS`, `CAMERA`, and foreground-service permissions are granted on Android 13+.
6. Verify `MobilePushRegistrationService` logs a registration token after login.
### Android runtime permissions (voice / camera)
Capacitor's WebView requests `RECORD_AUDIO` **and** `MODIFY_AUDIO_SETTINGS` together for microphone capture. If `MODIFY_AUDIO_SETTINGS` is missing from `AndroidManifest.xml`, users can accept the prompt and `getUserMedia` still fails.
Declared in `toju-app/android/app/src/main/AndroidManifest.xml`:
| Permission | Purpose |
|------------|---------|
| `RECORD_AUDIO` | Microphone capture for voice calls and channels |
| `MODIFY_AUDIO_SETTINGS` | Required by Capacitor WebChromeClient alongside `RECORD_AUDIO` |
| `CAMERA` | WebRTC camera sharing and WebView file capture |
| `BLUETOOTH_CONNECT` | Bluetooth headset routing during calls (Android 12+) |
| `POST_NOTIFICATIONS` | Incoming/active call notifications |
| `FOREGROUND_SERVICE` / `FOREGROUND_SERVICE_MICROPHONE` | Background voice session |
Before WebRTC capture, the client calls `MobileMediaService.ensureVoiceCapturePermissions()` / `ensureCameraCapturePermissions()`, which delegate to `MetoyouMobile.requestVoiceCapturePermissions()` / `requestCameraCapturePermissions()` on Capacitor shells.
### iOS (APNs)
1. Enable Push Notifications capability in Xcode for the `App` target.
@@ -135,6 +155,7 @@ POST /api/users/device-tokens/:userId/dispatch
- `FOREGROUND_SERVICE`
- `FOREGROUND_SERVICE_MICROPHONE`
- `RECORD_AUDIO`
- `MODIFY_AUDIO_SETTINGS`
- `POST_NOTIFICATIONS`
The service shows a low-importance ongoing notification while a call is active.
@@ -152,7 +173,7 @@ The service shows a low-importance ongoing notification while a call is active.
## Capacitor plugin loading
- `infrastructure/mobile/adapters/capacitor/capacitor-plugin-loader.ts` uses **static** `@capacitor/*` imports and `Capacitor.isPluginAvailable()` before returning a plugin. Do not `import()` plugin modules dynamically or `await` plugin objects (Capacitor proxies expose a throwing `.then()` stub).
- After adding or upgrading Capacitor plugins, run `npm run build:prod && npm run cap:sync` so Android/iOS native projects register `App`, `LocalNotifications`, push, and SQLite.
- After adding or upgrading Capacitor plugins, run `npm run build:prod && npm run cap:sync` so Android/iOS native projects register `App`, `AppUpdate`, `LocalNotifications`, push, and SQLite.
## Safe area (Android)
@@ -208,7 +229,8 @@ Network security configs:
- `ChatMessageComposerComponent` — `shouldShowAttachmentButton` + `pickAttachmentsFromDevice()`.
- `VoiceWorkspaceStreamTileComponent` — PiP when focused stream tile backgrounds.
- `MobileCallSessionService` — CallKit + foreground service + in-call notifications.
- `App` bootstrap — initializes mobile persistence, lifecycle, call-session, and push registration wiring.
- `App` bootstrap — initializes mobile persistence, lifecycle, app-update polling, call-session, and push registration wiring.
- `MobileAppUpdateService` — periodic Play Store / App Store checks (30 min) and settings UI actions; mirrors Electron `DesktopAppUpdateService` polling but uses native store APIs instead of release manifests.
## Phase 3 completion notes

View File

@@ -15,7 +15,7 @@ Owns the Docusaurus-based application and plugin-author documentation. The build
| Term | Definition | Aliases to avoid |
|------|------------|------------------|
| **App docs** | End-user-facing documentation for the MetoYou desktop client. | "manual" |
| **App docs** | End-user-facing documentation for the Toju desktop client. | "manual" |
| **Plugin docs** | Developer-facing reference for the plugin runtime — manifest format, lifecycle hooks, host APIs. Authoritative source for the plugin contract surface. | "API docs" |
| **Local API server** | The Electron in-process HTTP server that mounts `docs-site/build/` so the renderer can browse docs offline. Defined under `electron/api/`. | "embedded server" |

View File

@@ -48,7 +48,7 @@ This avoids:
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.
4. Toju validates credentials through the signaling server.
5. The desktop app issues an opaque local bearer token.
6. Use `Authorization: Bearer <token>` for protected routes.

View File

@@ -4,7 +4,7 @@ sidebar_position: 1
# Contributing
MetoYou is an npm-managed monorepo.
Toju is an npm-managed monorepo.
## Packages

View File

@@ -10,14 +10,20 @@ This page maps the app routes and important DOM areas. It is useful for plugin a
| Route | Component | Purpose |
| ---------------------------- | ------------------------- | --------------------------------------------------------------------- |
| `/` | Redirect | Redirects to `/search`. |
| `/` | Redirect | Redirects to `/dashboard`. |
| `/login` | `LoginComponent` | User login. |
| `/register` | `RegisterComponent` | User registration. |
| `/invite/:inviteId` | `InviteComponent` | Resolve and accept invite links. |
| `/search` | `ServerSearchComponent` | Search and join servers. |
| `/dashboard` | `DashboardComponent` | Landing dashboard after sign-in. |
| `/people` | `FindPeopleComponent` | Discover and start direct messages with people. |
| `/servers` | `FindServersComponent` | Search, discover, and join servers. |
| `/create-server` | `CreateServerComponent` | Create a new server. |
| `/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. |
| `/pm` | `DmWorkspaceComponent` | Private-message workspace (alias of the DM workspace). |
| `/pm/:conversationId` | `DmWorkspaceComponent` | A selected private-message conversation. |
| `/call/:callId` | `PrivateCallComponent` | Active private (1:1) call. |
| `/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()`. |

View File

@@ -4,11 +4,11 @@ sidebar_position: 5
# LLM Plugin Builder Guide
Copy this page into an LLM prompt when you want it to build a MetoYou plugin. It is intentionally explicit about the app, communication model, visual structure, manifest format, runtime rules, API types, and examples so the model has fewer gaps to invent around.
Copy this page into an LLM prompt when you want it to build a Toju plugin. It is intentionally explicit about the app, communication model, visual structure, manifest format, runtime rules, API types, and examples so the model has fewer gaps to invent around.
## Task For The LLM
Build a MetoYou client plugin: a browser-safe JavaScript ES module with a `toju-plugin.json` manifest, loaded by the Angular renderer, running inside the user's local MetoYou app, using only browser APIs and the provided `TojuClientPluginApi`.
Build a Toju client plugin: a browser-safe JavaScript ES module with a `toju-plugin.json` manifest, loaded by the Angular renderer, running inside the user's local Toju app, using only browser APIs and the provided `TojuClientPluginApi`.
Return a plugin folder like this:
@@ -22,7 +22,7 @@ my-plugin/
## Hard Rules
- Do not modify MetoYou core unless the user explicitly asks for a core code change.
- Do not modify Toju core unless the user explicitly asks for a core code change.
- Use plain browser ESM in `main.js`. Do not use Node APIs, `require`, `fs`, `path`, `child_process`, or build tooling unless explicitly requested.
- Use `toju-plugin.json` as the manifest name.
- Put every disposable returned by plugin APIs in `context.subscriptions`.
@@ -35,9 +35,9 @@ my-plugin/
- Server-installed plugins are requirement metadata plus local client downloads. The signaling server never executes plugin entrypoints.
- Every event used with `api.events.*` must be declared in the manifest `events` array.
## What MetoYou Is
## What Toju Is
MetoYou is a Discord-like chat and voice app:
Toju is a Discord-like chat and voice app:
- `toju-app/`: Angular renderer and plugin runtime.
- `electron/`: Electron desktop shell, preload bridge, local database, local REST API, local docs host.
@@ -124,7 +124,7 @@ Important routes:
| Route | Purpose |
| ------------------------------- | ------------------------------------------------------------------- |
| `/search` | Search and join servers. |
| `/servers` | Search, discover, and join servers. |
| `/room/:roomId` | Main server workspace with text, voice, members, and plugin panels. |
| `/dm` and `/dm/:conversationId` | Direct-message workspace. |
| `/settings` | App, voice, server, plugin, desktop, theme, and local API settings. |
@@ -178,7 +178,7 @@ Minimal manifest:
"schemaVersion": 1,
"id": "example.my-plugin",
"title": "My Plugin",
"description": "Adds a focused MetoYou feature.",
"description": "Adds a focused Toju feature.",
"version": "1.0.0",
"kind": "client",
"scope": "client",
@@ -621,7 +621,7 @@ interface PluginApiCustomStreamRequest {
label?: string;
}
type PluginApiActionSource = 'composerAction' | 'toolbarAction' | 'profileAction' | 'manual';
type PluginApiActionSource = 'composerAction' | 'toolbarAction' | 'profileAction' | 'slashCommand' | 'manual';
interface PluginApiActionContext {
source: PluginApiActionSource;
user: User | null;
@@ -821,6 +821,10 @@ interface TojuClientPluginApi {
registerEmbedRenderer: (id: string, contribution: PluginApiEmbedRendererContribution) => TojuPluginDisposable;
mountElement: (id: string, request: PluginApiDomMountRequest) => TojuPluginDisposable;
};
readonly commands: {
register: (id: string, contribution: PluginApiSlashCommandContribution) => TojuPluginDisposable;
list: () => PluginApiSlashCommandContribution[];
};
}
```
@@ -851,7 +855,7 @@ const currentUser = api.profile.getCurrent();
api.profile.update({
displayName: 'Ludde the Builder',
description: 'Building plugins for MetoYou.'
description: 'Building plugins for Toju.'
});
api.profile.updateAvatar({
@@ -1178,6 +1182,8 @@ Capabilities:
| `registerEmbedRenderer` | `ui.embeds` |
| `mountElement` | `ui.dom` |
For `/` slash commands, use `api.commands.register` (capability `ui.commands`). See the Slash Commands subsection below.
Register side panel:
```js
@@ -1310,6 +1316,36 @@ context.subscriptions.push(
`mountElement` tags the element with plugin ownership metadata, replaces duplicate mounts for the same plugin/id, and removes it on disposal/unload.
### Slash Commands
Capability: `commands.register` and `commands.list` both require `ui.commands`.
Register `/` slash commands that appear in the chat composer's autocomplete menu. Set `scope: 'global'` (default) for commands available in chat servers and direct messages, or `scope: 'server'` for commands only offered while a chat server is active. Declare `options` to parse arguments into `context.args` (use `type: 'rest'` to capture all trailing text). The `run` callback receives a context with `source: 'slashCommand'`, the parsed `args`, the invoked `command` name, the raw `rawArgs`, and the current user/server/channel.
```js
context.subscriptions.push(
api.commands.register('announce', {
name: 'announce',
description: 'Post an announcement to the current channel',
icon: 'megaphone',
scope: 'server',
options: [{ name: 'message', type: 'rest', required: true }],
run: (slash) => api.messages.send(`Announcement: ${slash.args.message}`, slash.textChannel?.id)
})
);
context.subscriptions.push(
api.commands.register('shrug', {
name: 'shrug',
description: 'Append the shrug emoticon',
scope: 'global',
run: () => api.messages.send('shrug')
})
);
```
A command with no `options` runs immediately when picked; a command with options fills `/name ` so the user can type arguments before sending. Slash input is never posted as a chat message; unmatched `/text` falls through as a normal message.
## Capability Cheat Sheet
| API call group | Capabilities |
@@ -1351,6 +1387,7 @@ context.subscriptions.push(
| `ui.registerChannelSection` | `ui.channelsSection` |
| `ui.registerEmbedRenderer` | `ui.embeds` |
| `ui.mountElement` | `ui.dom` |
| `commands.register`, `commands.list` | `ui.commands` |
## Complete Example Plugin

View File

@@ -4,7 +4,7 @@ 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.
The Toju 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

View File

@@ -3,9 +3,9 @@ slug: /
sidebar_position: 1
---
# MetoYou Documentation
# Toju 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.
Toju 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:
@@ -26,7 +26,7 @@ The Electron app can host this documentation locally. The docs endpoint is not a
## Runtime Boundaries
MetoYou keeps responsibilities split by package:
Toju 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.

View File

@@ -318,6 +318,55 @@ interface PluginApiDomMountRequest {
| `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. |
## Slash Commands
Slash commands appear in a Discord-style autocomplete menu when a user types `/` in the chat composer. A command with `scope: 'global'` (the default) is offered in every chat surface, including direct messages; a command with `scope: 'server'` only appears while a chat server is active. The user picks a command from the menu (or types it and presses Enter) and the `run` callback executes with the parsed arguments and the current interaction context.
```ts
type PluginApiSlashCommandScope = 'global' | 'server';
interface PluginApiSlashCommandOption {
description?: string;
name: string;
required?: boolean;
// 'rest' captures all remaining text; otherwise a single whitespace-delimited token
type?: 'string' | 'number' | 'boolean' | 'rest';
}
interface PluginApiSlashCommandContext extends PluginApiActionContext {
args: Record<string, string>; // parsed values keyed by option name
command: string; // invoked name without the leading slash
rawArgs: string; // raw text typed after the command name
}
interface PluginApiSlashCommandContribution {
description?: string;
icon?: string;
name: string;
options?: PluginApiSlashCommandOption[];
run: (context: PluginApiSlashCommandContext) => Promise<void> | void;
scope?: PluginApiSlashCommandScope;
}
```
| Method | Capability | Description |
| ----------------------------------- | -------------- | ------------------------------------------------------------------- |
| `commands.register(id, command)` | `ui.commands` | Registers a `/` slash command for the chat composer. |
| `commands.list()` | `ui.commands` | Lists every slash command currently registered across all plugins. |
```ts
context.subscriptions.push(
api.commands.register('shout', {
description: 'Shout a message in uppercase',
icon: '📢',
name: 'shout',
options: [{ name: 'message', required: true, type: 'rest' }],
run: (slash) => api.messages.send(slash.args.message.toUpperCase()),
scope: 'server'
})
);
```
## Context and Logger
| Method | Capability | Description |

View File

@@ -0,0 +1,114 @@
---
sidebar_position: 12
---
# Slash Commands API
The Commands API lets plugins register `/` slash commands. When a user types `/` in the chat composer, Toju shows a Discord-style autocomplete menu of available commands. Selecting a command (click, `Enter`, or `Tab`) runs it — either immediately when it declares no options, or after the user types the requested arguments.
## Required Capabilities
| Method | Capability |
| --------------------------------- | ------------- |
| `commands.register(id, command)` | `ui.commands` |
| `commands.list()` | `ui.commands` |
Every registration returns a disposable. Push it into `context.subscriptions` so the command is removed when the plugin unloads.
## Command Scope
A command's `scope` controls where it appears:
| Scope | Available in |
| ------------------- | --------------------------------------------- |
| `global` (default) | Chat servers **and** direct messages |
| `server` | Only while a chat server is the active surface |
Use `global` for commands that work without a server context (e.g. `/help`, `/shrug`). Use `server` for commands that act on the current server, channel, or members.
## Options and Argument Parsing
Declare `options` to describe the arguments a command accepts. Toju parses what the user typed after the command name and passes the result to `run` as `context.args`, keyed by option name.
```ts
interface PluginApiSlashCommandOption {
description?: string;
name: string;
required?: boolean;
// 'rest' captures all remaining text; otherwise a single whitespace-delimited token
type?: 'string' | 'number' | 'boolean' | 'rest';
}
```
- Positional options are filled left-to-right from whitespace-delimited tokens.
- A `rest` option captures all remaining text verbatim (use it last, for free-form text).
- Missing positional values are passed as empty strings.
- The autocomplete menu shows required options as `<name>` and optional ones as `[name]`.
Values arrive as strings; convert `number`/`boolean` types yourself inside `run`.
## Command Context
`run` receives a context that extends the standard action context (`source: 'slashCommand'`) with the invocation details:
```ts
interface PluginApiSlashCommandContext extends PluginApiActionContext {
args: Record<string, string>; // parsed values keyed by option name
command: string; // invoked name without the leading slash
rawArgs: string; // raw text typed after the command name
// inherited: server, textChannel, voiceChannel, user, source
}
```
## Register a Command
```js
export function activate(context) {
const api = context.api;
// Server-scoped command with a free-form message argument.
context.subscriptions.push(
api.commands.register('announce', {
name: 'announce',
description: 'Post an announcement to the current channel',
icon: '📢',
scope: 'server',
options: [{ name: 'message', type: 'rest', required: true }],
run: (slash) => {
api.messages.send(`📢 ${slash.args.message}`, slash.textChannel?.id);
}
})
);
// Global command that works in servers and DMs.
context.subscriptions.push(
api.commands.register('shrug', {
name: 'shrug',
description: 'Append the shrug emoticon',
scope: 'global',
run: () => api.messages.send('¯\\_(ツ)_/¯')
})
);
}
```
`api.messages.send` requires the `messages.send` capability, so the example above declares both `ui.commands` and `messages.send` in its manifest.
## List Registered Commands
```js
const allCommands = context.api.commands.list();
```
Returns every slash command currently registered across all active plugins, including their scope and options.
## Built-in Commands
Toju ships first-party commands that are always available without any plugin, such as `/lenny` (posts `( ͡° ͜ʖ ͡°)`). They appear in the same autocomplete menu tagged as **Built-in**. Plugin commands are listed alongside them; if a plugin registers a command with the same name as a built-in, both appear and the user can pick either.
## How Input Is Handled
- Typing `/` opens the menu; typing more characters filters by command name (prefix matches rank first).
- Picking a command **without options** runs it immediately and clears the composer.
- Picking a command **with options** fills `/name ` so the user can type arguments, then `Enter` runs it.
- Slash input is intercepted and never posted as a chat message. Text that starts with `/` but matches no registered command falls through and is sent as a normal message.

View File

@@ -6,6 +6,8 @@ sidebar_position: 11
The UI API lets plugins add pages, settings pages, side panels, channel sections, actions, embed renderers, and controlled DOM mounts.
For `/` slash commands in the chat composer, see the [Slash Commands API](./commands.md) (`api.commands`).
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
@@ -151,7 +153,7 @@ export function activate(context) {
Toolbar actions are command-style plugin entries shown in the server side panel's View plugins menu. Use them for small actions that should be easy to launch from a server, such as opening a plugin page, sending a status message, starting a timer, or toggling a plugin feature.
The View plugins link appears in `[data-testid="plugin-room-side-panel"]` when the plugin side-panel area is rendered. Opening it shows an overlay menu, positioned like profile-card overlays, with registered actions laid out as plugin icon tiles. The `icon` field can be short text such as `RH`, an emoji, or an image URL; when omitted, MetoYou falls back to initials from the plugin/action labels.
The View plugins link appears in `[data-testid="plugin-room-side-panel"]` when the plugin side-panel area is rendered. Opening it shows an overlay menu, positioned like profile-card overlays, with registered actions laid out as plugin icon tiles. The `icon` field can be short text such as `RH`, an emoji, or an image URL; when omitted, Toju falls back to initials from the plugin/action labels.
Toolbar action callbacks receive an action context with `source: 'toolbarAction'`, the current user, current server, active text channel, and current voice channel when available.

View File

@@ -37,6 +37,7 @@ Capabilities protect privileged app surfaces. A plugin must declare a capability
| `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. |
| `ui.commands` | `commands.register()`, `commands.list()` | Registers `/` slash commands (global or server scope) and lists registered commands. |
| `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. |

View File

@@ -4,7 +4,7 @@ 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.
Toju 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

View File

@@ -45,6 +45,61 @@ export function activate(context) {
The action appears as a tile in the server side panel's View plugins menu and runs with `source: 'toolbarAction'`.
## Slash Command Plugin
`toju-plugin.json`
```json
{
"schemaVersion": 1,
"id": "example.slash-commands",
"title": "Slash Commands",
"description": "Registers / commands available from the chat composer.",
"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.commands"]
}
```
`main.js`
```js
export function activate(context) {
const { api } = context;
// Global: works in chat servers and direct messages.
context.subscriptions.push(
api.commands.register('shrug', {
name: 'shrug',
description: 'Append the shrug emoticon',
scope: 'global',
run: () => api.messages.send('¯\\_(ツ)_/¯')
})
);
// Server-scoped: only offered while a chat server is active.
context.subscriptions.push(
api.commands.register('announce', {
name: 'announce',
description: 'Post an announcement to the current channel',
icon: '📢',
scope: 'server',
options: [{ name: 'message', type: 'rest', required: true }],
run: (slash) => api.messages.send(`📢 ${slash.args.message}`, slash.textChannel?.id)
})
);
}
```
Typing `/` in the composer opens the autocomplete menu. `/shrug` runs immediately; `/announce <message>` fills the composer so the user can type the announcement before sending. See the [Slash Commands API](./api/commands.md) for option parsing and the command context.
## Settings Page Plugin
```json

View File

@@ -41,6 +41,7 @@ type PluginCapabilityId =
| 'ui.channelsSection'
| 'ui.embeds'
| 'ui.dom'
| 'ui.commands'
| 'storage.local'
| 'storage.serverData.read'
| 'storage.serverData.write'
@@ -131,7 +132,7 @@ interface TojuPluginManifest {
`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.
When a user installs a server-scoped plugin into the server they are currently viewing, Toju 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

View File

@@ -4,7 +4,7 @@ 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.
Toju 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
@@ -18,11 +18,11 @@ MetoYou is a chat app for servers, text conversations, direct messages, and live
## Sign In
1. Open MetoYou.
1. Open Toju.
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.
A signaling server handles accounts, server discovery, membership, and connection setup. In normal use you can think of it as the place Toju checks when you log in and join servers.
## Find a Server

View File

@@ -4,7 +4,7 @@ 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.
Plugins add features to Toju. They can add pages, buttons, panels, settings, sounds, message tools, custom embeds, or server-specific behavior.
## Types of Plugins
@@ -30,6 +30,8 @@ Server-scoped plugins installed to the server you are currently viewing are enab
When plugins add quick actions to a server, the server side panel shows a View plugins link in the plugin area. Open it to see a grid of plugin action tiles. Selecting a tile runs that plugin's action in the current server and channel context.
Plugins can also add `/` slash commands. Type `/` in the message box to open the command menu; plugin commands appear there tagged with the plugin name, alongside built-in commands like `/lenny`. See [Text and Direct Messages](./text-and-direct-messages.md#slash-commands) for how to use the menu.
## Install a Local Plugin
Desktop builds can discover local plugin folders from the app data plugins directory.
@@ -42,7 +44,7 @@ Desktop builds can discover local plugin folders from the app data plugins direc
## Server Plugin Prompts
When a server uses plugins, MetoYou may show a prompt.
When a server uses plugins, Toju may show a prompt.
| Status | Meaning |
| ------------ | --------------------------------------------------------------------------------- |
@@ -65,7 +67,7 @@ Examples:
| 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. |
| UI | Add pages, settings pages, side panels, toolbar buttons, slash commands, or DOM elements. |
| Storage | Save plugin preferences locally or per server. |
Only grant capabilities to plugins you trust.
@@ -83,4 +85,4 @@ The Plugin Manager lets you:
## 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.
Plugins are browser-safe JavaScript modules loaded by the client. They do not run on the signaling server. A plugin can only call privileged Toju APIs when its manifest declares the capability and you grant it.

View File

@@ -4,7 +4,7 @@ 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.
A server is the main shared space in Toju. Servers contain members, channels, permissions, optional plugins, and server settings.
## Server Rail

View File

@@ -20,7 +20,7 @@ Settings control the app, voice, plugins, servers, themes, updates, local APIs,
## 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.
Desktop Toju 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

View File

@@ -13,6 +13,7 @@ Text channels belong to a server. Everyone with access to that server and channe
You can use text channels to:
- send normal messages;
- run slash commands by typing `/`;
- edit or delete your own messages when allowed;
- react to messages;
- send attachments;
@@ -24,14 +25,25 @@ You can use text channels to:
Direct messages are private conversations outside a server channel. Use them when a message is meant for one person instead of the server.
## Slash Commands
Type `/` at the start of the message box to open the slash command menu. It lists the commands you can run, with a short description for each.
- Keep typing to filter the list (for example `/le`).
- Use the up and down arrow keys to move through the list, then press `Enter` or `Tab` to pick a command. You can also click one.
- Press `Escape` to close the menu.
- A command that needs extra text fills the box with `/name ` so you can type the rest, then send it.
Toju includes built-in commands such as `/lenny`, which posts `( ͡° ͜ʖ ͡°)`. Plugins can add their own commands, which appear in the same menu (tagged with the plugin name). Slash commands are available in both text channels and direct messages; some plugin commands only appear inside a server. Text that starts with `/` but matches no command is sent as a normal message.
## 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.
Toju 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.
Some plugins can send messages, create bot-style plugin users, render custom embeds, or add composer buttons. Toju asks for plugin capability grants before plugins can use privileged message features.

View File

@@ -45,7 +45,7 @@ When someone shares camera or screen, the voice workspace can expand into a larg
## 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.
If you navigate away from the server while still connected to voice, Toju can show floating voice controls. Use them to return to the voice server or leave the call.
## Voice Settings

View File

@@ -2,11 +2,11 @@
sidebar_position: 2
---
# Using MetoYou
# Using Toju
## 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.
Toju 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.
@@ -39,7 +39,7 @@ Desktop builds include platform integrations such as Linux display-server detect
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.
Plugins are explicit runtime modules. Toju loads browser-safe ES modules, passes a frozen API object, and cleans up registered disposables when a plugin unloads.
## Desktop Settings

View File

@@ -2,7 +2,7 @@ import type { Config } from '@docusaurus/types';
import type * as Preset from '@docusaurus/preset-classic';
const config: Config = {
title: 'MetoYou Docs',
title: 'Toju Docs',
tagline: 'Desktop chat, local APIs, and plugin development',
url: 'http://127.0.0.1',
baseUrl: '/docusaurus/',
@@ -31,7 +31,7 @@ const config: Config = {
],
themeConfig: {
navbar: {
title: 'MetoYou Docs',
title: 'Toju Docs',
items: [
{ type: 'docSidebar', sidebarId: 'mainSidebar', position: 'left', label: 'Guides' },
{ to: '/user-guide/first-steps', label: 'User Guide', position: 'left' },
@@ -56,7 +56,7 @@ const config: Config = {
]
}
],
copyright: 'MetoYou local documentation. Built with Docusaurus.'
copyright: 'Toju local documentation. Built with Docusaurus.'
},
prism: {
additionalLanguages: [

View File

@@ -13,7 +13,7 @@ const sidebars: SidebarsConfig = {
'user-guide/voice-channels',
'user-guide/plugins',
'user-guide/settings',
'using-metoyou'
'using-toju'
]
},
{
@@ -50,7 +50,8 @@ const sidebars: SidebarsConfig = {
'plugin-development/api/message-bus',
'plugin-development/api/p2p-and-media',
'plugin-development/api/storage',
'plugin-development/api/ui'
'plugin-development/api/ui',
'plugin-development/api/commands'
]
},
'plugin-development/examples'

View File

@@ -48,7 +48,8 @@ export const test = base.extend<MultiClientFixture>({
const context = await browser.newContext({
permissions: ['microphone', 'camera'],
baseURL: 'http://localhost:4200'
baseURL: 'http://localhost:4200',
viewport: { width: 1440, height: 900 }
});
await installTestServerEndpoint(context, testServer.port);

20
e2e/helpers/app-menu.ts Normal file
View File

@@ -0,0 +1,20 @@
import { expect, type Page } from '@playwright/test';
export async function openTitleBarMenu(page: Page): Promise<void> {
const menuButton = page.getByRole('button', { name: 'Menu' });
await expect(menuButton).toBeVisible({ timeout: 15_000 });
await menuButton.click();
await expect(page.locator('app-title-bar .absolute.right-0.top-full').first()).toBeVisible({ timeout: 10_000 });
}
export async function openPluginStore(page: Page): Promise<void> {
await openTitleBarMenu(page);
await page.getByRole('button', { name: 'Plugin Store' }).click();
await expect(page).toHaveURL(/\/plugin-store/, { timeout: 20_000 });
}
export async function openSettingsFromMenu(page: Page): Promise<void> {
await openTitleBarMenu(page);
await page.getByRole('button', { name: 'Settings' }).click();
}

106
e2e/helpers/auth-api.ts Normal file
View File

@@ -0,0 +1,106 @@
import { type APIRequestContext, type Page } from '@playwright/test';
export const AUTH_TOKENS_STORAGE_KEY = 'metoyou.authTokens';
export const SIGNAL_SERVER_CREDENTIALS_STORAGE_KEY = 'metoyou.signalServerCredentials';
export interface AuthSession {
id: string;
username: string;
displayName: string;
token: string;
expiresAt: number;
}
export function authHeaders(token: string): Record<string, string> {
return {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json'
};
}
export async function registerTestUser(
request: APIRequestContext,
baseUrl: string,
username: string,
password: string,
displayName?: string
): Promise<AuthSession> {
const response = await request.post(`${baseUrl}/api/users/register`, {
data: {
username,
password,
displayName: displayName ?? username
}
});
if (!response.ok()) {
throw new Error(`Failed to register test user ${username}: ${response.status()} ${await response.text()}`);
}
return await response.json() as AuthSession;
}
export async function loginTestUser(
request: APIRequestContext,
baseUrl: string,
username: string,
password: string
): Promise<AuthSession> {
const response = await request.post(`${baseUrl}/api/users/login`, {
data: { username, password }
});
if (!response.ok()) {
throw new Error(`Failed to login test user ${username}: ${response.status()} ${await response.text()}`);
}
return await response.json() as AuthSession;
}
export async function readSignalServerCredentialFromPage(
page: Page,
serverUrl: string
): Promise<{ userId: string; token: string; username: string } | null> {
return await page.evaluate(({ storageKey, url }) => {
try {
const store = JSON.parse(localStorage.getItem(storageKey) || '{}') as Record<string, {
userId: string;
token: string;
username: string;
expiresAt: number;
}>;
const normalizedUrl = url.trim().replace(/\/+$/, '');
const entry = store[normalizedUrl];
if (!entry || entry.expiresAt <= Date.now()) {
return null;
}
return {
userId: entry.userId,
token: entry.token,
username: entry.username
};
} catch {
return null;
}
}, { storageKey: SIGNAL_SERVER_CREDENTIALS_STORAGE_KEY, url: serverUrl });
}
export async function readAuthTokenFromPage(page: Page, serverUrl: string): Promise<string | null> {
return await page.evaluate(({ storageKey, url }) => {
try {
const store = JSON.parse(localStorage.getItem(storageKey) || '{}') as Record<string, { token: string; expiresAt: number }>;
const normalizedUrl = url.trim().replace(/\/+$/, '');
const entry = store[normalizedUrl];
if (!entry || entry.expiresAt <= Date.now()) {
return null;
}
return entry.token;
} catch {
return null;
}
}, { storageKey: AUTH_TOKENS_STORAGE_KEY, url: serverUrl });
}

11
e2e/helpers/dashboard.ts Normal file
View File

@@ -0,0 +1,11 @@
import { expect, type Page } from '@playwright/test';
/** Dashboard omnibox (desktop placeholder copy changed with i18n refresh). */
export function dashboardSearchInput(page: Page) {
return page.getByRole('textbox', { name: 'Search people, servers, and invites' });
}
export async function expectDashboardReady(page: Page, timeout = 30_000): Promise<void> {
await expect(page).toHaveURL(/\/dashboard/, { timeout });
await expect(dashboardSearchInput(page)).toBeVisible({ timeout });
}

View File

@@ -0,0 +1,219 @@
import { expect, type Page } from '@playwright/test';
import { type Client } from '../fixtures/multi-client';
import { LoginPage } from '../pages/login.page';
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';
export const MULTI_DEVICE_PASSWORD = 'TestPass123!';
export const MULTI_DEVICE_VOICE_CHANNEL = 'General';
export interface MultiDeviceCredentials {
username: string;
displayName: string;
password: string;
}
export interface MultiDeviceScenario {
clientA: Client;
clientB: Client;
credentials: MultiDeviceCredentials;
serverName: string;
messagesA: ChatMessagesPage;
messagesB: ChatMessagesPage;
roomA: ChatRoomPage;
roomB: ChatRoomPage;
}
export function uniqueMultiDeviceName(prefix: string): string {
return `${prefix}-${Date.now()}-${Math.floor(Math.random() * 10_000)}`;
}
export async function createMultiDeviceScenario(
createClient: () => Promise<Client>,
options: { suffix?: string; serverDescription?: string } = {}
): Promise<MultiDeviceScenario> {
const suffix = options.suffix ?? uniqueMultiDeviceName('multi-device');
const credentials: MultiDeviceCredentials = {
username: `multi_${suffix}`,
displayName: 'Multi Device User',
password: MULTI_DEVICE_PASSWORD
};
const serverName = `Multi Device Server ${suffix}`;
const clientA = await createClient();
const clientB = await createClient();
await warmClientPage(clientA.page);
await warmClientPage(clientB.page);
const registerPage = new RegisterPage(clientA.page);
await registerPage.goto();
await registerPage.register(credentials.username, credentials.displayName, credentials.password);
await expect(clientA.page).toHaveURL(/\/dashboard/, { timeout: 15_000 });
const searchA = new ServerSearchPage(clientA.page);
await searchA.createServer(serverName, {
description: options.serverDescription ?? 'Multi-device session coverage'
});
await expect(clientA.page).toHaveURL(/\/room\//, { timeout: 15_000 });
await waitForCurrentRoomName(clientA.page, serverName);
const roomA = new ChatRoomPage(clientA.page);
await roomA.ensureVoiceChannelExists(MULTI_DEVICE_VOICE_CHANNEL);
await loginSecondDeviceIntoServer(clientB.page, credentials, serverName);
await waitForCurrentRoomName(clientB.page, serverName);
const messagesA = new ChatMessagesPage(clientA.page);
const messagesB = new ChatMessagesPage(clientB.page);
const roomB = new ChatRoomPage(clientB.page);
await messagesA.waitForReady();
await messagesB.waitForReady();
return {
clientA,
clientB,
credentials,
serverName,
messagesA,
messagesB,
roomA,
roomB
};
}
export async function loginSecondDeviceIntoServer(
page: Page,
credentials: MultiDeviceCredentials,
serverName: string
): Promise<void> {
const loginPage = new LoginPage(page);
await loginPage.goto();
await loginPage.login(credentials.username, credentials.password);
await expect(page).toHaveURL(/\/dashboard/, { timeout: 15_000 });
const search = new ServerSearchPage(page);
await search.joinServerFromSearch(serverName);
await expect(page).toHaveURL(/\/room\//, { timeout: 20_000 });
await expect(page.locator('app-rooms-side-panel').first()).toBeVisible({ timeout: 20_000 });
}
export async function expectCrossDeviceMessage(
sender: ChatMessagesPage,
receiver: ChatMessagesPage,
message: string,
timeout = 60_000
): Promise<void> {
await sender.sendMessage(message);
await expect.poll(async () => {
return await receiver.getMessageItemByText(message).isVisible()
.catch(() => false);
}, { timeout }).toBe(true);
}
async function warmClientPage(page: Page): Promise<void> {
await page.goto('/dashboard', { waitUntil: 'domcontentloaded' });
await page.waitForLoadState('networkidle').catch(() => undefined);
}
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 }
);
}
export async function readClientInstanceId(page: Page): Promise<string | null> {
return page.evaluate(() => {
const sessionId = sessionStorage.getItem('metoyou.clientInstanceId')?.trim();
if (sessionId) {
return sessionId;
}
return localStorage.getItem('metoyou.clientInstanceId')?.trim() ?? null;
});
}
export async function logoutFromMenu(page: Page): Promise<void> {
const menuButton = page.getByRole('button', { name: 'Menu' });
const logoutButton = page.getByRole('button', { name: 'Logout' });
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 });
}
export function channelsSidePanel(page: Page) {
return page.locator('app-rooms-side-panel').first();
}
export function membersSidePanel(page: Page) {
return page.locator('app-rooms-side-panel').last();
}
export function passiveVoiceChannelJoinBadge(page: Page, channelName = MULTI_DEVICE_VOICE_CHANNEL) {
return page
.locator(`button[data-channel-type="voice"][data-channel-name="${channelName}"]`)
.getByText('Join', { exact: true });
}
export async function expectPassiveVoiceOnDevice(
page: Page,
options: { timeout?: number; displayName?: string; channelName?: string } = {}
): Promise<void> {
const timeout = options.timeout ?? 45_000;
const channelName = options.channelName ?? MULTI_DEVICE_VOICE_CHANNEL;
const displayName = options.displayName;
await expect.poll(async () => {
const membersLabel = await membersSidePanel(page)
.getByText('In voice on another device', { exact: false })
.isVisible()
.catch(() => false);
const joinBadge = await passiveVoiceChannelJoinBadge(page, channelName).isVisible()
.catch(() => false);
const grayedVoiceUser = displayName
? await channelsSidePanel(page).locator('.opacity-50')
.filter({ hasText: displayName })
.first()
.isVisible()
.catch(() => false)
: false;
return membersLabel || joinBadge || grayedVoiceUser;
}, { timeout }).toBe(true);
}
export async function expectActiveVoiceOnDevice(page: Page, timeout = 20_000): Promise<void> {
await expect(page.locator('app-voice-controls, app-voice-workspace').first()).toBeVisible({ timeout });
}

View File

@@ -0,0 +1,19 @@
import { expect, type Page } from '@playwright/test';
export const E2E_PLUGIN_SOURCE_URL = 'http://localhost:4200/plugins/e2e-plugin-source.json';
export const E2E_PLUGIN_TITLE = 'E2E All API Plugin';
export async function addPluginSource(page: Page, sourceUrl = E2E_PLUGIN_SOURCE_URL): Promise<void> {
const sourceInput = page.getByLabel('Plugin source manifest URL');
await expect(sourceInput).toBeVisible({ timeout: 15_000 });
await sourceInput.click();
await sourceInput.fill(sourceUrl);
await expect(sourceInput).toHaveValue(sourceUrl, { timeout: 5_000 });
const addSourceButton = page.getByRole('button', { name: 'Add Source' });
await expect(addSourceButton).toBeEnabled({ timeout: 10_000 });
await addSourceButton.click();
await expect(page.getByRole('heading', { name: E2E_PLUGIN_TITLE })).toBeVisible({ timeout: 20_000 });
}

View File

@@ -7,16 +7,19 @@
*
* Cleanup: the temp directory is removed when the process exits.
*/
const { mkdtempSync, writeFileSync, mkdirSync, rmSync } = require('fs');
const { existsSync, mkdtempSync, writeFileSync, mkdirSync, rmSync } = require('fs');
const { join } = require('path');
const { tmpdir } = require('os');
const { spawn } = require('child_process');
const TEST_PORT = process.env.TEST_SERVER_PORT || '3099';
const SERVER_DIR = join(__dirname, '..', '..', 'server');
const SERVER_ENTRY = join(SERVER_DIR, 'src', 'index.ts');
const SERVER_DIST_ENTRY = join(SERVER_DIR, 'dist', 'index.js');
const SERVER_SRC_ENTRY = join(SERVER_DIR, 'src', 'index.ts');
const SERVER_TSCONFIG = join(SERVER_DIR, 'tsconfig.json');
const TS_NODE_BIN = join(SERVER_DIR, 'node_modules', 'ts-node', 'dist', 'bin.js');
const SERVER_ENTRY = existsSync(SERVER_DIST_ENTRY) ? SERVER_DIST_ENTRY : SERVER_SRC_ENTRY;
const USE_COMPILED_SERVER = SERVER_ENTRY === SERVER_DIST_ENTRY;
// ── Create isolated temp data directory ──────────────────────────────
const tmpDir = mkdtempSync(join(tmpdir(), 'metoyou-e2e-'));
@@ -45,7 +48,7 @@ console.log(`[E2E Server] Starting on port ${TEST_PORT}...`);
// and node_modules are found from the real server/ directory.
const child = spawn(
process.execPath,
[TS_NODE_BIN, '--project', SERVER_TSCONFIG, SERVER_ENTRY],
USE_COMPILED_SERVER ? [SERVER_ENTRY] : [TS_NODE_BIN, '--project', SERVER_TSCONFIG, SERVER_ENTRY],
{
cwd: tmpDir,
env: {

View File

@@ -1,15 +1,19 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import { type Page } from '@playwright/test';
import { type BrowserContext, type Page } from '@playwright/test';
/**
* Install RTCPeerConnection monkey-patch on a page BEFORE navigating.
* Tracks all created peer connections and their remote tracks so tests
* can inspect WebRTC state via `page.evaluate()`.
*
* Call immediately after page creation, before any `goto()`.
* Call on the browser context (preferred) or page before any `goto()`.
*/
export async function installWebRTCTracking(page: Page): Promise<void> {
await page.addInitScript(() => {
export async function installWebRTCTracking(target: BrowserContext | Page): Promise<void> {
const addInitScript = 'addInitScript' in target && typeof target.addInitScript === 'function'
? target.addInitScript.bind(target)
: (target as Page).addInitScript.bind(target);
await addInitScript(() => {
const connections: RTCPeerConnection[] = [];
const dataChannels: RTCDataChannel[] = [];
const syntheticMediaResources: {
@@ -197,6 +201,7 @@ export async function waitForPeerConnected(page: Page, timeout = 30_000): Promis
() => (window as any).__rtcConnections?.some(
(pc: RTCPeerConnection) => pc.connectionState === 'connected'
) ?? false,
undefined,
{ timeout }
);
}
@@ -611,6 +616,7 @@ export async function waitForAudioStatsPresent(page: Page, timeout = 15_000): Pr
return false;
},
undefined,
{ timeout }
);
}
@@ -818,6 +824,7 @@ export async function waitForVideoStatsPresent(page: Page, timeout = 15_000): Pr
return false;
},
undefined,
{ timeout }
);
}

View File

@@ -34,9 +34,22 @@ export class ChatMessagesPage {
}
async sendMessage(content: string): Promise<void> {
await this.waitForReady();
await this.composerInput.fill(content);
await this.sendButton.click();
let lastError: unknown;
for (let attempt = 1; attempt <= 3; attempt += 1) {
try {
await this.waitForReady();
await this.composerInput.fill(content);
await expect(this.composerInput).toHaveValue(content, { timeout: 5_000 });
await expect(this.sendButton).toBeEnabled({ timeout: 5_000 });
await this.sendButton.click();
return;
} catch (error) {
lastError = error;
}
}
throw lastError instanceof Error ? lastError : new Error('Failed to send chat message');
}
async typeDraft(content: string): Promise<void> {
@@ -44,6 +57,13 @@ export class ChatMessagesPage {
await this.composerInput.fill(content);
}
/** Types into the composer in a way that emits input/typing events (not just fill). */
async typeDraftWithTypingEvents(content: string): Promise<void> {
await this.waitForReady();
await this.composerInput.click();
await this.composerInput.pressSequentially(content, { delay: 40 });
}
async clearDraft(): Promise<void> {
await this.waitForReady();
await this.composerInput.fill('');

View File

@@ -317,13 +317,22 @@ export class ChatRoomPage {
throw new Error('Missing room, user, or endpoint when persisting channels');
}
const authTokens = JSON.parse(localStorage.getItem('metoyou.authTokens') || '{}') as Record<string, { token: string; expiresAt: number }>;
const normalizedApiUrl = apiBaseUrl.trim().replace(/\/+$/, '');
const authEntry = authTokens[normalizedApiUrl];
const authToken = authEntry && authEntry.expiresAt > Date.now() ? authEntry.token : null;
if (!authToken) {
throw new Error('Missing session token for channel persistence');
}
const response = await fetch(`${apiBaseUrl}/api/servers/${room.id}`, {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
'Content-Type': 'application/json',
Authorization: `Bearer ${authToken}`
},
body: JSON.stringify({
currentOwnerId: currentUser.id,
channels: nextChannels
})
});

View File

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

27
e2e/run-playwright.mjs Normal file
View File

@@ -0,0 +1,27 @@
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
const e2eDirectory = fileURLToPath(new URL('.', import.meta.url));
const env = { ...process.env };
const browsersPath = env.PLAYWRIGHT_BROWSERS_PATH;
if (browsersPath?.includes('/cursor-sandbox-cache/')) {
delete env.PLAYWRIGHT_BROWSERS_PATH;
}
const [command = 'test', ...args] = process.argv.slice(2);
const executable = process.platform === 'win32' ? 'npx.cmd' : 'npx';
const child = spawn(executable, ['playwright', command, ...args], {
cwd: e2eDirectory,
env,
stdio: 'inherit'
});
child.on('exit', (code, signal) => {
if (signal) {
process.kill(process.pid, signal);
return;
}
process.exit(code ?? 1);
});

View File

@@ -0,0 +1,153 @@
import { test, expect } from '../../fixtures/multi-client';
import { LoginPage } from '../../pages/login.page';
import { RegisterPage } from '../../pages/register.page';
interface TestUser {
username: string;
displayName: string;
password: string;
}
test.describe('Login returnUrl handling', () => {
test.describe.configure({ timeout: 120_000 });
test('unwraps nested login returnUrl chains after successful login', async ({ createClient }) => {
const client = await createClient();
const { page } = client;
const suffix = uniqueName('nested-return');
const user: TestUser = {
username: `user_${suffix}`,
displayName: 'Return Url User',
password: 'TestPass123!'
};
await test.step('Create an account', async () => {
const registerPage = new RegisterPage(page);
await registerPage.goto();
await registerPage.register(user.username, user.displayName, user.password);
await expect(page).toHaveURL(/\/dashboard/, { timeout: 15_000 });
});
await test.step('Log out and open a deeply nested login returnUrl', async () => {
await logout(page);
const nestedReturnUrl = '/login?returnUrl=%2Flogin%3FreturnUrl%3D%252Fservers';
await page.goto(`/login?returnUrl=${encodeURIComponent(nestedReturnUrl)}`, {
waitUntil: 'domcontentloaded'
});
await expect(page.locator('#login-username')).toBeVisible({ timeout: 15_000 });
});
await test.step('Login lands on the original destination instead of looping on /login', async () => {
const loginPage = new LoginPage(page);
await loginPage.login(user.username, user.password);
await expect(page).toHaveURL(/\/servers/, { timeout: 15_000 });
await expect(page).not.toHaveURL(/returnUrl=.*login/);
});
});
test('redirects unauthenticated /servers visits to login and returns there after login', async ({ createClient }) => {
const client = await createClient();
const { page } = client;
const suffix = uniqueName('servers-return');
const user: TestUser = {
username: `user_${suffix}`,
displayName: 'Servers Return User',
password: 'TestPass123!'
};
await test.step('Create an account and log out', async () => {
const registerPage = new RegisterPage(page);
await registerPage.goto();
await registerPage.register(user.username, user.displayName, user.password);
await expect(page).toHaveURL(/\/dashboard/, { timeout: 15_000 });
await logout(page);
});
await test.step('Visiting /servers sends the user to a single-level login returnUrl', async () => {
await page.goto('/servers', { waitUntil: 'domcontentloaded' });
await expect(page).toHaveURL(/\/login/, { timeout: 15_000 });
await expect(page).toHaveURL(/returnUrl=%2Fservers/);
await expect(page).not.toHaveURL(/returnUrl=.*login/);
});
await test.step('Logging in returns to /servers', async () => {
const loginPage = new LoginPage(page);
await loginPage.login(user.username, user.password);
await expect(page).toHaveURL(/\/servers/, { timeout: 15_000 });
await expect(page.locator('app-server-browser')).toBeVisible({ timeout: 15_000 });
});
});
test('lets a returning user log back in after an expired session redirect', async ({ createClient }) => {
const client = await createClient();
const { page } = client;
const suffix = uniqueName('expired-session');
const user: TestUser = {
username: `user_${suffix}`,
displayName: 'Expired Session User',
password: 'TestPass123!'
};
await test.step('Create an account', async () => {
const registerPage = new RegisterPage(page);
await registerPage.goto();
await registerPage.register(user.username, user.displayName, user.password);
await expect(page).toHaveURL(/\/dashboard/, { timeout: 15_000 });
});
await test.step('Simulate an expired session while keeping the persisted user id', async () => {
await page.evaluate(() => {
const storageKey = 'metoyou.authTokens';
const raw = localStorage.getItem(storageKey);
if (!raw) {
return;
}
const parsed = JSON.parse(raw) as Record<string, { token: string; expiresAt: number }>;
const expiredStore = Object.fromEntries(
Object.entries(parsed).map(([url, entry]) => [url, { ...entry, expiresAt: 0 }])
);
localStorage.setItem(storageKey, JSON.stringify(expiredStore));
});
await page.goto('/servers', { waitUntil: 'domcontentloaded' });
await expect(page).toHaveURL(/\/login/, { timeout: 15_000 });
await expect(page).toHaveURL(/returnUrl=%2Fservers/);
await expect(page).not.toHaveURL(/returnUrl=.*login/);
});
await test.step('The user can authenticate again and reach /servers', async () => {
const loginPage = new LoginPage(page);
await loginPage.login(user.username, user.password);
await expect(page).toHaveURL(/\/servers/, { timeout: 15_000 });
await expect(page.locator('app-server-browser')).toBeVisible({ timeout: 15_000 });
});
});
});
async function logout(page: import('@playwright/test').Page): Promise<void> {
const menuButton = page.getByRole('button', { name: 'Menu' });
const logoutButton = page.getByRole('button', { name: 'Logout' });
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 });
}
function uniqueName(prefix: string): string {
return `${prefix}-${Date.now().toString(36)}-${Math.random().toString(36)
.slice(2, 8)}`;
}

View File

@@ -0,0 +1,94 @@
import { test, expect } from '../../fixtures/multi-client';
import {
MULTI_DEVICE_VOICE_CHANNEL,
channelsSidePanel,
createMultiDeviceScenario,
expectCrossDeviceMessage,
expectActiveVoiceOnDevice,
expectPassiveVoiceOnDevice,
logoutFromMenu,
membersSidePanel,
passiveVoiceChannelJoinBadge,
readClientInstanceId,
uniqueMultiDeviceName
} from '../../helpers/multi-device-session';
test.describe('Multi-device session', () => {
test.describe.configure({ timeout: 300_000, retries: 1 });
test('covers identity, chat sync, typing exclusion, and voice exclusivity', async ({ createClient }) => {
const scenario = await createMultiDeviceScenario(createClient);
const messageAtoB = `Cross-device A to B ${uniqueMultiDeviceName('msg')}`;
const messageBtoA = `Cross-device B to A ${uniqueMultiDeviceName('msg')}`;
const typingDraft = `Typing draft ${uniqueMultiDeviceName('draft')}`;
await test.step('assigns distinct clientInstanceId per browser context', async () => {
const instanceA = await readClientInstanceId(scenario.clientA.page);
const instanceB = await readClientInstanceId(scenario.clientB.page);
expect(instanceA).toBeTruthy();
expect(instanceB).toBeTruthy();
expect(instanceA).not.toEqual(instanceB);
});
await test.step('syncs chat from device A to device B', async () => {
await expectCrossDeviceMessage(scenario.messagesA, scenario.messagesB, messageAtoB);
});
await test.step('syncs chat from device B to device A', async () => {
await expectCrossDeviceMessage(scenario.messagesB, scenario.messagesA, messageBtoA);
});
await test.step('does not show own typing indicator on the other device for the same user', async () => {
await scenario.messagesA.typeDraftWithTypingEvents(typingDraft);
await expect(
scenario.clientB.page.getByText(`${scenario.credentials.displayName} is typing`, { exact: false })
).toHaveCount(0, { timeout: 5_000 });
});
await test.step('shows passive in-voice UI on the second device when the first joins voice', async () => {
await scenario.roomA.joinVoiceChannel(MULTI_DEVICE_VOICE_CHANNEL);
await expectActiveVoiceOnDevice(scenario.clientA.page);
await expectPassiveVoiceOnDevice(scenario.clientB.page, {
displayName: scenario.credentials.displayName
});
await expect(
membersSidePanel(scenario.clientB.page).getByText('In voice on another device', { exact: false })
).toBeVisible({ timeout: 20_000 });
await expect(
channelsSidePanel(scenario.clientB.page).locator('.opacity-50')
.filter({
hasText: scenario.credentials.displayName
})
.first()
).toBeVisible({ timeout: 20_000 });
});
await test.step('shows Join takeover affordance on passive device voice channel', async () => {
await expect(passiveVoiceChannelJoinBadge(scenario.clientB.page)).toBeVisible({ timeout: 20_000 });
});
await test.step('transfers voice ownership when the passive device takes over', async () => {
await scenario.roomB.joinVoiceChannel(MULTI_DEVICE_VOICE_CHANNEL);
await expectActiveVoiceOnDevice(scenario.clientB.page);
await expectPassiveVoiceOnDevice(scenario.clientA.page, {
displayName: scenario.credentials.displayName
});
});
await test.step('keeps the second device logged in when the first device logs out', async () => {
const message = `Still logged in ${uniqueMultiDeviceName('logout')}`;
await logoutFromMenu(scenario.clientA.page);
await scenario.messagesB.sendMessage(message);
await expect(scenario.messagesB.getMessageItemByText(message)).toBeVisible({ timeout: 20_000 });
await expect(scenario.clientB.page).toHaveURL(/\/room\//, { timeout: 10_000 });
});
});
});

View File

@@ -0,0 +1,111 @@
import { expect } from '@playwright/test';
import { test } from '../../fixtures/multi-client';
import { openSettingsFromMenu } from '../../helpers/app-menu';
import { expectDashboardReady } from '../../helpers/dashboard';
import { installTestServerEndpoints } from '../../helpers/seed-test-endpoint';
import { startTestServer } from '../../helpers/test-server';
import {
readAuthTokenFromPage,
readSignalServerCredentialFromPage,
registerTestUser
} from '../../helpers/auth-api';
import { RegisterPage } from '../../pages/register.page';
const PRIMARY_ENDPOINT_ID = 'e2e-multi-auth-primary';
const USER_PASSWORD = 'TestPass123!';
test.describe('Multi-signal-server authentication', () => {
test.describe.configure({ timeout: 180_000 });
test('auto-provisions a foreign signal server when a new endpoint is added', async ({ createClient, request }) => {
const primaryServer = await startTestServer();
const secondaryServer = await startTestServer();
try {
const client = await createClient();
const suffix = `multi_auth_${Date.now()}`;
const username = `user_${suffix}`;
await installTestServerEndpoints(client.context, [
{
id: PRIMARY_ENDPOINT_ID,
name: 'E2E Primary Signal',
url: primaryServer.url,
isActive: true,
status: 'online'
}
]);
await test.step('Register on the home signal server', async () => {
const register = new RegisterPage(client.page);
await register.goto();
await register.register(username, 'Multi Auth User', USER_PASSWORD);
await expectDashboardReady(client.page);
});
await test.step('Add a second signal server in network settings', async () => {
await openSettingsFromMenu(client.page);
await client.page.getByRole('button', { name: 'Network' }).click();
await client.page.getByPlaceholder('Server name').fill('E2E Secondary Signal');
await client.page.getByPlaceholder('Server URL (e.g., http://localhost:3001)').fill(secondaryServer.url);
await client.page.getByTestId('add-signal-server-button').click();
await expect(client.page.getByText(secondaryServer.url)).toBeVisible({ timeout: 15_000 });
});
await test.step('Wait for auto-provisioned credentials on the secondary server', async () => {
await expect.poll(async () =>
await readSignalServerCredentialFromPage(client.page, secondaryServer.url),
{ timeout: 30_000 }
).not.toBeNull();
const homeToken = await readAuthTokenFromPage(client.page, primaryServer.url);
const secondaryCredential = await readSignalServerCredentialFromPage(client.page, secondaryServer.url);
expect(homeToken).toBeTruthy();
expect(secondaryCredential?.username).toBe(username);
expect(secondaryCredential?.token).toBeTruthy();
});
await test.step('Secondary credential can call authenticated APIs', async () => {
const secondaryCredential = await readSignalServerCredentialFromPage(client.page, secondaryServer.url);
if (!secondaryCredential) {
throw new Error('Expected secondary signal-server credential to be provisioned');
}
const response = await request.post(`${secondaryServer.url}/api/servers`, {
headers: {
Authorization: `Bearer ${secondaryCredential.token}`,
'Content-Type': 'application/json'
},
data: {
name: `Secondary Provisioned Server ${suffix}`,
description: 'Created with auto-provisioned credentials',
ownerId: secondaryCredential.userId,
ownerPublicKey: 'e2e-secondary-owner-key'
}
});
expect(response.ok(), `POST /api/servers failed: ${response.status()} ${await response.text()}`).toBe(true);
});
await test.step('Home registration still works independently on the secondary server', async () => {
const otherUser = await registerTestUser(
request,
secondaryServer.url,
`other_${suffix}`,
USER_PASSWORD,
'Other User'
);
expect(otherUser.username).toBe(`other_${suffix}`);
});
} finally {
await primaryServer.stop();
await secondaryServer.stop();
}
});
});

View File

@@ -48,14 +48,13 @@ test.describe('User session data isolation', () => {
await test.step('Alice registers and creates local chat history', async () => {
await registerUser(client.page, alice);
await createServerAndSendMessage(client.page, aliceServerName, aliceMessage);
await createServerAndSendMessage(client.page, alice, 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);
await expectSavedRoomAndHistory(client.page, alice, aliceServerName, aliceMessage);
});
} finally {
await closePersistentClient(client);
@@ -88,11 +87,11 @@ test.describe('User session data isolation', () => {
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 createServerAndSendMessage(client.page, alice, aliceServerName, aliceMessage);
await restartPersistentClient(client, testServer.port);
await openApp(client.page);
await expectSavedRoomAndHistory(client.page, aliceServerName, aliceMessage);
await expectSavedRoomAndHistory(client.page, alice, aliceServerName, aliceMessage);
});
await test.step('Bob starts from a blank slate in the same browser profile', async () => {
@@ -102,11 +101,11 @@ test.describe('User session data isolation', () => {
});
await test.step('Bob gets only his own saved room and history after a restart', async () => {
await createServerAndSendMessage(client.page, bobServerName, bobMessage);
await createServerAndSendMessage(client.page, bob, bobServerName, bobMessage);
await restartPersistentClient(client, testServer.port);
await openApp(client.page);
await expectSavedRoomAndHistory(client.page, bobServerName, bobMessage);
await expectSavedRoomAndHistory(client.page, bob, bobServerName, bobMessage);
await expectSavedRoomHidden(client.page, aliceServerName);
});
@@ -117,7 +116,7 @@ test.describe('User session data isolation', () => {
await expectSavedRoomVisible(client.page, aliceServerName);
await expectSavedRoomHidden(client.page, bobServerName);
await expectSavedRoomAndHistory(client.page, aliceServerName, aliceMessage);
await expectSavedRoomAndHistory(client.page, alice, aliceServerName, aliceMessage);
});
} finally {
await closePersistentClient(client);
@@ -194,32 +193,58 @@ async function logoutUser(page: Page): Promise<void> {
await expect(loginPage.usernameInput).toBeVisible({ timeout: 10_000 });
}
async function createServerAndSendMessage(page: Page, serverName: string, messageText: string): Promise<void> {
async function createServerAndSendMessage(page: Page, user: TestUser, 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 loginIfNeeded(page, user);
await ensureCurrentUserScope(page, user);
await page.goto('/create-server', { waitUntil: 'domcontentloaded' });
if (await waitForLoginForm(page, 5_000)) {
await loginUser(page, user);
await page.goto('/create-server', { waitUntil: 'domcontentloaded' });
}
await expect(searchPage.serverNameInput).toBeVisible({ timeout: 10_000 });
await searchPage.serverNameInput.fill(serverName);
await searchPage.serverDescriptionInput.fill(`User session isolation coverage for ${serverName}`);
await searchPage.createSubmitButton.click();
await expect(page).toHaveURL(/\/room\//, { timeout: 15_000 });
await messagesPage.sendMessage(messageText);
await expect(messagesPage.getMessageItemByText(messageText)).toBeVisible({ timeout: 20_000 });
await expectMessagePersistedInIndexedDb(page, messageText);
}
async function expectSavedRoomAndHistory(page: Page, roomName: string, messageText: string): Promise<void> {
const railRoomButton = getRailSavedRoomButton(page, roomName);
const messagesPage = new ChatMessagesPage(page);
async function expectSavedRoomAndHistory(page: Page, user: TestUser, roomName: string, messageText: string): Promise<void> {
if (await waitForVisibleText(page, messageText, 5_000)) {
return;
}
await expect(railRoomButton).toBeVisible({ timeout: 20_000 });
await page.goto('/servers', { waitUntil: 'domcontentloaded' });
const searchRoomButton = getSearchSavedRoomButton(page, roomName);
if (await new LoginPage(page).usernameInput.isVisible().catch(() => false)) {
await loginUser(page, user);
}
await expect(searchRoomButton).toBeVisible({ timeout: 20_000 });
await searchRoomButton.click();
await expectMessagePersistedInIndexedDb(page, messageText);
const persistedRoomId = await getPersistedRoomIdForMessage(page, messageText);
if (persistedRoomId) {
await openPersistedRoomById(page, user, persistedRoomId);
await expect(page.getByText(messageText, { exact: false })).toBeVisible({ timeout: 20_000 });
return;
}
if (await openSavedRoomFromRail(page, roomName)) {
await expect(page.getByText(messageText, { exact: false })).toBeVisible({ timeout: 20_000 });
return;
}
await joinServerFromSearchAfterLogin(page, user, roomName);
await expect(page).toHaveURL(/\/room\//, { timeout: 20_000 });
await expect(messagesPage.getMessageItemByText(messageText)).toBeVisible({ timeout: 20_000 });
await expect(page.getByText(messageText, { exact: false })).toBeVisible({ timeout: 20_000 });
}
async function expectBlankSlate(page: Page, hiddenRoomNames: string[]): Promise<void> {
@@ -232,14 +257,17 @@ async function expectBlankSlate(page: Page, hiddenRoomNames: string[]): Promise<
}
async function expectSavedRoomVisible(page: Page, roomName: string): Promise<void> {
await expect(getRailSavedRoomButton(page, roomName)).toBeVisible({ timeout: 20_000 });
if (await page.getByText(roomName, { exact: false }).first()
.isVisible()
.catch(() => false)) {
return;
}
await page.goto('/servers', { 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('/servers')) {
await page.goto('/servers', { waitUntil: 'domcontentloaded' });
}
@@ -247,14 +275,227 @@ async function expectSavedRoomHidden(page: Page, roomName: string): Promise<void
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-browser').getByRole('button', { name: roomName, exact: true });
}
async function openSavedRoomFromRail(page: Page, roomName: string): Promise<boolean> {
try {
await expect(page.locator('app-servers-rail')).toBeVisible({ timeout: 10_000 });
const clicked = await page.locator('app-servers-rail button').evaluateAll((buttons, expectedName) => {
const expectedPrefix = expectedName.slice(0, 24);
const button = buttons.find((candidate) => {
const title = (candidate as HTMLButtonElement).title;
return title === expectedName || title.startsWith(expectedPrefix);
}) as HTMLButtonElement | undefined;
button?.click();
return !!button;
}, roomName);
if (!clicked) {
return await openSavedRoomFromDashboard(page, roomName);
}
await expect(page).toHaveURL(/\/room\//, { timeout: 20_000 });
return true;
} catch {
return await openSavedRoomFromDashboard(page, roomName);
}
}
async function openSavedRoomFromDashboard(page: Page, roomName: string): Promise<boolean> {
const roomNamePattern = new RegExp(escapeRegExp(roomName.slice(0, 24)));
const roomButton = page.getByRole('button', { name: roomNamePattern }).first();
try {
await expect(roomButton).toBeVisible({ timeout: 10_000 });
await roomButton.click();
await expect(page).toHaveURL(/\/room\//, { timeout: 20_000 });
return true;
} catch {
return await joinVisibleServerFromDashboard(page, roomNamePattern);
}
}
async function joinVisibleServerFromDashboard(page: Page, roomNamePattern: RegExp): Promise<boolean> {
const serverRow = page.locator('div', { hasText: roomNamePattern }).filter({
has: page.getByRole('button', { name: 'Join' })
})
.last();
const joinButton = serverRow.getByRole('button', { name: 'Join' });
try {
await expect(joinButton).toBeVisible({ timeout: 10_000 });
await joinButton.click();
await expect(page).toHaveURL(/\/room\//, { timeout: 20_000 });
return true;
} catch {
return false;
}
}
async function joinServerFromSearchAfterLogin(page: Page, user: TestUser, roomName: string): Promise<void> {
const searchPage = new ServerSearchPage(page);
await loginIfNeeded(page, user);
await searchPage.goto();
if (!await waitForServerSearch(page, 5_000)) {
await loginUser(page, user);
await searchPage.goto();
}
await expect(searchPage.searchInput).toBeVisible({ timeout: 15_000 });
await searchPage.searchInput.fill(roomName);
const serverCard = page.locator('div[title]', { hasText: roomName }).first();
await expect(serverCard).toBeVisible({ timeout: 15_000 });
await serverCard.dblclick();
}
async function loginIfNeeded(page: Page, user: TestUser): Promise<void> {
const loginPage = new LoginPage(page);
if (page.url().includes('/login')) {
await expect(loginPage.usernameInput).toBeVisible({ timeout: 15_000 });
await loginUser(page, user);
return;
}
if (await loginPage.usernameInput.isVisible().catch(() => false)) {
await loginUser(page, user);
}
}
async function ensureCurrentUserScope(page: Page, user: TestUser): Promise<void> {
if (await hasCurrentUserScope(page)) {
return;
}
await loginUser(page, user);
await expect.poll(() => hasCurrentUserScope(page), { timeout: 10_000 }).toBe(true);
}
async function hasCurrentUserScope(page: Page): Promise<boolean> {
return page.evaluate(() => !!localStorage.getItem('metoyou_currentUserId')?.trim());
}
async function openPersistedRoomById(page: Page, user: TestUser, roomId: string): Promise<void> {
for (let attempt = 1; attempt <= 3; attempt += 1) {
await page.goto(`/room/${roomId}`, { waitUntil: 'domcontentloaded' });
if (await waitForLoginForm(page, 5_000)) {
await loginUser(page, user);
continue;
}
await expect(page).toHaveURL(/\/room\//, { timeout: 20_000 });
if (!await waitForLoginForm(page, 2_000)) {
return;
}
await loginUser(page, user);
}
await page.goto(`/room/${roomId}`, { waitUntil: 'domcontentloaded' });
await expect(page).toHaveURL(/\/room\//, { timeout: 20_000 });
}
async function waitForLoginForm(page: Page, timeout: number): Promise<boolean> {
try {
await expect(new LoginPage(page).usernameInput).toBeVisible({ timeout });
return true;
} catch {
return false;
}
}
async function waitForServerSearch(page: Page, timeout: number): Promise<boolean> {
try {
await expect(new ServerSearchPage(page).searchInput).toBeVisible({ timeout });
return true;
} catch {
return false;
}
}
async function waitForVisibleText(page: Page, text: string, timeout: number): Promise<boolean> {
try {
await expect(page.getByText(text, { exact: false })).toBeVisible({ timeout });
return true;
} catch {
return false;
}
}
async function expectMessagePersistedInIndexedDb(page: Page, messageText: string): Promise<void> {
await expect.poll(
() => getPersistedRoomIdForMessage(page, messageText).then((roomId) => !!roomId),
{ timeout: 10_000 }
).toBe(true);
}
async function getPersistedRoomIdForMessage(page: Page, messageText: string): Promise<string | null> {
return page.evaluate(async (expectedContent) => {
const currentUserId = localStorage.getItem('metoyou_currentUserId')?.trim();
const preferredDatabaseName = `metoyou::${encodeURIComponent(currentUserId || 'anonymous')}`;
const discoveredDatabaseNames = typeof indexedDB.databases === 'function'
? (await indexedDB.databases())
.map((database) => database.name)
.filter((name): name is string => !!name && (name === 'metoyou' || name.startsWith('metoyou::')))
: null;
const databaseNames = discoveredDatabaseNames ?? [preferredDatabaseName];
const remainingDatabaseNames = databaseNames.filter((name) => name !== preferredDatabaseName);
const orderedDatabaseNames = databaseNames.includes(preferredDatabaseName)
? [preferredDatabaseName].concat(remainingDatabaseNames)
: remainingDatabaseNames;
for (const databaseName of orderedDatabaseNames) {
const database = await new Promise<IDBDatabase>((resolve, reject) => {
const request = indexedDB.open(databaseName);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
});
try {
if (!database.objectStoreNames.contains('messages')) {
continue;
}
const transaction = database.transaction('messages', 'readonly');
const request = transaction.objectStore('messages').getAll();
const roomId = await new Promise<string | null>((resolve, reject) => {
request.onerror = () => reject(request.error);
request.onsuccess = () => {
const match = ((request.result as { content?: string; roomId?: string }[]) ?? [])
.find((message) => message.content === expectedContent);
resolve(match?.roomId ?? null);
};
});
if (roomId) {
return roomId;
}
} finally {
database.close();
}
}
return null;
}, messageText);
}
function escapeRegExp(value: string): string {
return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
async function retryTransientNavigation<T>(navigate: () => Promise<T>, attempts = 4): Promise<T> {
let lastError: unknown;

View File

@@ -1,5 +1,6 @@
import {
expect,
type BrowserContext,
type Locator,
type Page
} from '@playwright/test';
@@ -35,6 +36,7 @@ test.describe('Chat notifications', () => {
await clearDesktopNotifications(scenario.alice.page);
await scenario.bobRoom.joinTextChannel(scenario.channelName);
await scenario.bobMessages.sendMessage(message);
await expectUnreadCounts(scenario.alice.page, scenario.serverName, scenario.channelName);
});
await test.step('Alice receives a desktop notification with the channel preview', async () => {
@@ -67,8 +69,7 @@ test.describe('Chat notifications', () => {
});
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 expectUnreadCounts(scenario.alice.page, scenario.serverName, scenario.channelName);
});
await test.step('Alice does not get a muted desktop popup', async () => {
@@ -96,7 +97,7 @@ async function createNotificationScenario(createClient: () => Promise<Client>):
const alice = await createClient();
const bob = await createClient();
await installDesktopNotificationSpy(alice.page);
await installDesktopNotificationSpy(alice.context);
await registerUser(alice.page, aliceCredentials.username, aliceCredentials.displayName, aliceCredentials.password);
await registerUser(bob.page, bobCredentials.username, bobCredentials.displayName, bobCredentials.password);
@@ -143,8 +144,8 @@ async function registerUser(page: Page, username: string, displayName: string, p
await expect(page).toHaveURL(/\/dashboard/, { timeout: 15_000 });
}
async function installDesktopNotificationSpy(page: Page): Promise<void> {
await page.addInitScript(() => {
async function installDesktopNotificationSpy(context: BrowserContext): Promise<void> {
await context.addInitScript(() => {
const notifications: DesktopNotificationRecord[] = [];
class MockNotification {
@@ -250,6 +251,11 @@ function getUnreadBadge(container: Locator): Locator {
return container.locator('span.rounded-full').first();
}
async function expectUnreadCounts(page: Page, serverName: string, channelName: string): Promise<void> {
await expect(getUnreadBadge(getSavedRoomButton(page, serverName))).toHaveText('1', { timeout: 45_000 });
await expect(getUnreadBadge(getTextChannelButton(page, channelName))).toHaveText('1', { timeout: 45_000 });
}
function uniqueName(prefix: string): string {
return `${prefix}-${Date.now()}-${Math.random().toString(36)
.slice(2, 8)}`;

View File

@@ -367,11 +367,10 @@ async function launchPersistentSession(
});
await installTestServerEndpoint(context, testServerPort);
await installWebRTCTracking(context);
const page = context.pages()[0] ?? await context.newPage();
await installWebRTCTracking(page);
return { context, page };
}

View File

@@ -196,11 +196,10 @@ async function launchPersistentSession(userDataDir: string, testServerPort: numb
});
await installTestServerEndpoint(context, testServerPort);
await installWebRTCTracking(context);
const page = context.pages()[0] ?? (await context.newPage());
await installWebRTCTracking(page);
return { context, page };
}

View File

@@ -4,13 +4,20 @@ import {
test,
type Client
} from '../../fixtures/multi-client';
import { openPluginStore } from '../../helpers/app-menu';
import {
addPluginSource,
E2E_PLUGIN_SOURCE_URL,
E2E_PLUGIN_TITLE
} from '../../helpers/plugin-store';
import { installWebRTCTracking } from '../../helpers/webrtc-helpers';
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 PLUGIN_SOURCE_URL = E2E_PLUGIN_SOURCE_URL;
const PLUGIN_TITLE = E2E_PLUGIN_TITLE;
const EDITED_MESSAGE = 'Plugin API edited message';
const ORIGINAL_MESSAGE = 'Plugin API original message';
const DELETED_MESSAGE = 'Plugin API deleted message';
@@ -87,6 +94,9 @@ async function createPluginApiScenario(createClient: () => Promise<Client>): Pro
const alice = await createClient();
const bob = await createClient();
await installWebRTCTracking(alice.page);
await installWebRTCTracking(bob.page);
await registerUser(alice.page, `alice_${suffix}`, 'Alice');
await registerUser(bob.page, `bob_${suffix}`, 'Bob');
@@ -98,13 +108,10 @@ async function createPluginApiScenario(createClient: () => Promise<Client>): Pro
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 bobSearch.joinServerFromSearch(serverName);
await expect(bob.page).toHaveURL(/\/room\//, { timeout: 30_000 });
const bobRoom = new ChatRoomPage(bob.page);
@@ -113,6 +120,9 @@ async function createPluginApiScenario(createClient: () => Promise<Client>): Pro
await bobRoom.joinVoiceChannel(VOICE_CHANNEL);
await expect(aliceRoom.voiceControls).toBeVisible({ timeout: 30_000 });
await expect(bobRoom.voiceControls).toBeVisible({ timeout: 30_000 });
await installGrantAndActivatePlugin(alice.page, true);
await closeSettingsModal(alice.page);
await expect(soundboardComposerButton(alice.page)).toBeVisible({ timeout: 20_000 });
const aliceMessages = new ChatMessagesPage(alice.page);
const bobMessages = new ChatMessagesPage(bob.page);
@@ -141,14 +151,11 @@ async function registerUser(page: Page, username: string, displayName: string):
}
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 openPluginStore(page);
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 addPluginSource(page, PLUGIN_SOURCE_URL);
await page.locator('article', { hasText: PLUGIN_TITLE }).getByRole('button', { exact: true, name: /^(Install|Install to Server)$/ })
.click();

View File

@@ -1,4 +1,7 @@
import { expect, test } from '../../fixtures/multi-client';
import { openPluginStore } from '../../helpers/app-menu';
import { expectDashboardReady } from '../../helpers/dashboard';
import { addPluginSource } from '../../helpers/plugin-store';
import { RegisterPage } from '../../pages/register.page';
import { ServerSearchPage } from '../../pages/server-search.page';
@@ -15,7 +18,7 @@ test.describe('Plugin manager UI', () => {
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 people, servers, or paste an invite...')).toBeVisible({ timeout: 30_000 });
await expectDashboardReady(page);
await search.createServer(`Plugin API Server ${suffix}`, {
description: 'Plugin manager UI E2E coverage'
});
@@ -23,16 +26,13 @@ test.describe('Plugin manager UI', () => {
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 test.step('Open Plugin Store from the title-bar menu', async () => {
await openPluginStore(page);
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 addPluginSource(page);
const pluginCard = page.locator('article', { hasText: 'E2E All API Plugin' });
await pluginCard.getByRole('button', { name: 'Readme' }).click();

View File

@@ -1,6 +1,11 @@
import type { APIRequestContext, APIResponse } from '@playwright/test';
import WebSocket from 'ws';
import { expect, test } from '../../fixtures/multi-client';
import {
authHeaders,
registerTestUser,
type AuthSession
} from '../../helpers/auth-api';
import {
getPluginApiTestEvent,
readPluginApiTestManifest,
@@ -9,8 +14,6 @@ import {
TEST_PLUGIN_RELAY_EVENT
} from '../../helpers/plugin-api-test-fixture';
const OWNER_USER_ID = 'plugin-api-owner';
interface CreatedServerResponse {
id: string;
}
@@ -54,10 +57,25 @@ interface TestSocket {
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 owner = await registerTestUser(
request,
testServer.url,
`plugin-owner-${Date.now()}`,
'TestPass123!',
'Plugin Owner'
);
const peer = await registerTestUser(
request,
testServer.url,
`plugin-peer-${Date.now()}`,
'TestPass123!',
'Plugin Peer'
);
const server = await createServer(request, testServer.url, owner, `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`;
const ownerHeaders = authHeaders(owner.token);
await test.step('Initial snapshot is empty', async () => {
const snapshot = await expectJson<PluginSnapshotResponse>(await request.get(pluginsApi));
@@ -71,8 +89,8 @@ test.describe('Plugin support API', () => {
await test.step('Requirement API enforces server management permission', async () => {
const response = await request.put(`${pluginsApi}/${TEST_PLUGIN_ID}/requirement`, {
headers: authHeaders(peer.token),
data: {
actorUserId: 'not-the-owner',
status: 'required'
}
});
@@ -83,8 +101,8 @@ test.describe('Plugin support API', () => {
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`, {
headers: ownerHeaders,
data: {
actorUserId: OWNER_USER_ID,
reason: manifest.description,
status: 'required',
versionRange: `^${manifest.version}`
@@ -98,8 +116,8 @@ test.describe('Plugin support API', () => {
versionRange: `^${manifest.version}`
}));
const relayDefinition = await upsertEventDefinition(request, pluginsApi, relayEvent);
const p2pDefinition = await upsertEventDefinition(request, pluginsApi, p2pEvent);
const relayDefinition = await upsertEventDefinition(request, pluginsApi, ownerHeaders, relayEvent);
const p2pDefinition = await upsertEventDefinition(request, pluginsApi, ownerHeaders, p2pEvent);
expect(relayDefinition.eventDefinition).toEqual(expect.objectContaining({
direction: 'serverRelay',
@@ -123,8 +141,8 @@ test.describe('Plugin support API', () => {
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`, {
headers: ownerHeaders,
data: {
actorUserId: OWNER_USER_ID,
schemaVersion: 1,
scope: 'server',
value: {
@@ -140,15 +158,15 @@ test.describe('Plugin support API', () => {
params: {
key: 'settings',
scope: 'server',
userId: OWNER_USER_ID
userId: owner.id
}
}), 410);
expect(listed.errorCode).toBe('PLUGIN_DATA_DISABLED');
const afterDelete = await expectJson<{ errorCode: string }>(await request.delete(`${pluginsApi}/${TEST_PLUGIN_ID}/data/settings`, {
headers: ownerHeaders,
data: {
actorUserId: OWNER_USER_ID,
scope: 'server'
}
}), 410);
@@ -161,8 +179,8 @@ test.describe('Plugin support API', () => {
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' });
await identifySocket(alice, owner.token, 'Plugin Owner');
await identifySocket(bob, peer.token, 'Plugin Peer');
alice.send({ type: 'join_server', serverId: server.id });
bob.send({ type: 'join_server', serverId: server.id });
@@ -193,7 +211,7 @@ test.describe('Plugin support API', () => {
pluginId: TEST_PLUGIN_ID,
serverId: server.id,
sourcePluginUserId: 'fixture-plugin-user',
sourceUserId: OWNER_USER_ID
sourceUserId: owner.id
}));
expect(relayedEvent['payload']).toEqual({ message: 'hello from fixture plugin' });
@@ -237,15 +255,15 @@ test.describe('Plugin support API', () => {
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 }
headers: ownerHeaders
}));
await expectJson<{ ok: boolean }>(await request.delete(`${pluginsApi}/${TEST_PLUGIN_ID}/events/${TEST_PLUGIN_P2P_EVENT}`, {
data: { actorUserId: OWNER_USER_ID }
headers: ownerHeaders
}));
await expectJson<{ ok: boolean }>(await request.delete(`${pluginsApi}/${TEST_PLUGIN_ID}/requirement`, {
data: { actorUserId: OWNER_USER_ID }
headers: ownerHeaders
}));
const snapshot = await expectJson<PluginSnapshotResponse>(await request.get(pluginsApi));
@@ -259,9 +277,11 @@ test.describe('Plugin support API', () => {
async function createServer(
request: APIRequestContext,
baseUrl: string,
owner: AuthSession,
serverName: string
): Promise<CreatedServerResponse> {
const response = await request.post(`${baseUrl}/api/servers`, {
headers: authHeaders(owner.token),
data: {
channels: [
{
@@ -275,7 +295,7 @@ async function createServer(
id: `plugin-api-${Date.now()}`,
isPrivate: false,
name: serverName,
ownerId: OWNER_USER_ID,
ownerId: owner.id,
ownerPublicKey: 'plugin-api-owner-public-key',
tags: ['plugins']
}
@@ -287,13 +307,14 @@ async function createServer(
async function upsertEventDefinition(
request: APIRequestContext,
pluginsApi: string,
headers: Record<string, string>,
eventDefinition: ReturnType<typeof getPluginApiTestEvent>
): Promise<PluginEventDefinitionResponse> {
return await expectJson<PluginEventDefinitionResponse>(await request.put(
`${pluginsApi}/${TEST_PLUGIN_ID}/events/${encodeURIComponent(eventDefinition.eventName)}`,
{
headers,
data: {
actorUserId: OWNER_USER_ID,
direction: eventDefinition.direction,
maxPayloadBytes: eventDefinition.maxPayloadBytes,
schemaJson: '{"type":"object"}',
@@ -309,6 +330,20 @@ async function expectJson<T>(response: APIResponse, status = 200): Promise<T> {
return await response.json() as T;
}
async function identifySocket(socket: TestSocket, token: string, displayName: string): Promise<void> {
socket.send({ type: 'identify', token, displayName });
await new Promise((resolve) => {
setTimeout(resolve, 300);
});
const authError = socket.messages.find((message) => message.type === 'auth_error');
if (authError) {
throw new Error(`WebSocket identify failed: ${JSON.stringify(authError)}`);
}
}
async function openTestSocket(baseUrl: string): Promise<TestSocket> {
const socketUrl = baseUrl.replace(/^http/, 'ws');
const socket = new WebSocket(socketUrl);

View File

@@ -1,4 +1,5 @@
import { test, expect } from '../../fixtures/multi-client';
import { expectDashboardReady } from '../../helpers/dashboard';
import { RegisterPage } from '../../pages/register.page';
import { ServerSearchPage } from '../../pages/server-search.page';
import { ChatRoomPage } from '../../pages/chat-room.page';
@@ -88,7 +89,7 @@ test.describe('Connectivity warning', () => {
await register.goto();
await register.register(`alice_${suffix}`, 'Alice', 'TestPass123!');
await expect(alice.page.getByPlaceholder('Search people, servers, or paste an invite...')).toBeVisible({ timeout: 30_000 });
await expectDashboardReady(alice.page);
});
await test.step('Register Bob', async () => {
@@ -96,7 +97,7 @@ test.describe('Connectivity warning', () => {
await register.goto();
await register.register(`bob_${suffix}`, 'Bob', 'TestPass123!');
await expect(bob.page.getByPlaceholder('Search people, servers, or paste an invite...')).toBeVisible({ timeout: 30_000 });
await expectDashboardReady(bob.page);
});
await test.step('Register Charlie', async () => {
@@ -104,7 +105,7 @@ test.describe('Connectivity warning', () => {
await register.goto();
await register.register(`charlie_${suffix}`, 'Charlie', 'TestPass123!');
await expect(charlie.page.getByPlaceholder('Search people, servers, or paste an invite...')).toBeVisible({ timeout: 30_000 });
await expectDashboardReady(charlie.page);
});
// ── Create server and have everyone join ──

View File

@@ -1,4 +1,6 @@
import { test, expect } from '../../fixtures/multi-client';
import { openSettingsFromMenu } from '../../helpers/app-menu';
import { expectDashboardReady } from '../../helpers/dashboard';
import { RegisterPage } from '../../pages/register.page';
test.describe('ICE server settings', () => {
@@ -9,8 +11,8 @@ test.describe('ICE server settings', () => {
await register.goto();
await register.register(`user_${suffix}`, 'IceTestUser', 'TestPass123!');
await expect(page.getByPlaceholder('Search people, servers, or paste an invite...')).toBeVisible({ timeout: 30_000 });
await page.getByTitle('Settings').click();
await expectDashboardReady(page);
await openSettingsFromMenu(page);
await expect(page.getByRole('button', { name: 'Network' })).toBeVisible({ timeout: 10_000 });
await page.getByRole('button', { name: 'Network' }).click();
await expect(page.getByTestId('ice-server-settings')).toBeVisible({ timeout: 10_000 });
@@ -101,7 +103,7 @@ test.describe('ICE server settings', () => {
await expect(page.getByText('stun:persist-test.example.com:3478')).toBeVisible({ timeout: 5_000 });
await page.reload({ waitUntil: 'domcontentloaded' });
await page.getByTitle('Settings').click();
await openSettingsFromMenu(page);
await expect(page.getByRole('button', { name: 'Network' })).toBeVisible({ timeout: 10_000 });
await page.getByRole('button', { name: 'Network' }).click();
await expect(page.getByText('stun:persist-test.example.com:3478')).toBeVisible({ timeout: 10_000 });

View File

@@ -1,4 +1,5 @@
import { test, expect } from '../../fixtures/multi-client';
import { expectDashboardReady } from '../../helpers/dashboard';
import { RegisterPage } from '../../pages/register.page';
import { ServerSearchPage } from '../../pages/server-search.page';
import { ChatRoomPage } from '../../pages/chat-room.page';
@@ -89,7 +90,7 @@ test.describe('STUN/TURN fallback behaviour', () => {
await register.goto();
await register.register(`alice_${suffix}`, 'Alice', 'TestPass123!');
await expect(alice.page.getByPlaceholder('Search people, servers, or paste an invite...')).toBeVisible({ timeout: 30_000 });
await expectDashboardReady(alice.page);
});
await test.step('Register Bob', async () => {
@@ -97,7 +98,7 @@ test.describe('STUN/TURN fallback behaviour', () => {
await register.goto();
await register.register(`bob_${suffix}`, 'Bob', 'TestPass123!');
await expect(bob.page.getByPlaceholder('Search people, servers, or paste an invite...')).toBeVisible({ timeout: 30_000 });
await expectDashboardReady(bob.page);
});
await test.step('Alice creates a server', async () => {

View File

@@ -1,4 +1,8 @@
import { expect, type Page } from '@playwright/test';
import {
expect,
type APIRequestContext,
type Page
} from '@playwright/test';
import { test, type Client } from '../../fixtures/multi-client';
import { installTestServerEndpoints, type SeededEndpointInput } from '../../helpers/seed-test-endpoint';
import { startTestServer } from '../../helpers/test-server';
@@ -11,6 +15,11 @@ import {
waitForConnectedPeerCount,
waitForPeerConnected
} from '../../helpers/webrtc-helpers';
import {
authHeaders,
readAuthTokenFromPage,
registerTestUser
} from '../../helpers/auth-api';
import { RegisterPage } from '../../pages/register.page';
import { ServerSearchPage } from '../../pages/server-search.page';
import { ChatRoomPage } from '../../pages/chat-room.page';
@@ -104,6 +113,7 @@ function endpointsForGroup(
test.describe('Mixed signal-config voice', () => {
test('8 users with different signal configs can voice, mute, deafen, and chat concurrently', async ({
createClient,
request,
testServer
}) => {
test.setTimeout(720_000);
@@ -140,10 +150,32 @@ test.describe('Mixed signal-config voice', () => {
}
});
let secondaryRoomId = '';
// ── Create rooms ────────────────────────────────────────────
await test.step('Create voice room on primary and chat room on secondary', async () => {
// Use a "both" user (client 0) to create both rooms
const searchPage = new ServerSearchPage(clients[0].page);
const secondarySession = await registerTestUser(
request,
secondaryServer.url,
clients[0].user.username,
clients[0].user.password,
clients[0].user.displayName
);
await clients[0].page.evaluate(({ serverUrl, token, expiresAt }) => {
const storageKey = 'metoyou.authTokens';
const store = JSON.parse(localStorage.getItem(storageKey) || '{}') as Record<string, { token: string; expiresAt: number }>;
const normalizedUrl = serverUrl.trim().replace(/\/+$/, '');
store[normalizedUrl] = { token, expiresAt };
localStorage.setItem(storageKey, JSON.stringify(store));
}, {
serverUrl: secondaryServer.url,
token: secondarySession.token,
expiresAt: secondarySession.expiresAt
});
await searchPage.createServer(VOICE_ROOM_NAME, {
description: 'Voice room on primary signal',
@@ -152,12 +184,14 @@ test.describe('Mixed signal-config voice', () => {
await expect(clients[0].page).toHaveURL(/\/room\//, { timeout: 20_000 });
await searchPage.createServer(SECONDARY_ROOM_NAME, {
description: 'Chat room on secondary signal',
sourceId: SECONDARY_SIGNAL_ID
});
const secondaryRoom = await createServerViaApi(
request,
secondaryServer.url,
secondarySession,
SECONDARY_ROOM_NAME
);
await expect(clients[0].page).toHaveURL(/\/room\//, { timeout: 20_000 });
secondaryRoomId = secondaryRoom.id;
});
// ── Create invite links ─────────────────────────────────────
@@ -171,26 +205,33 @@ test.describe('Mixed signal-config voice', () => {
// Navigate to voice room to get its ID
await openSavedRoomByName(clients[0].page, VOICE_ROOM_NAME);
const primaryRoomId = await getCurrentRoomId(clients[0].page);
const userId = await getCurrentUserId(clients[0].page);
// Navigate to secondary room to get its ID
await openSavedRoomByName(clients[0].page, SECONDARY_ROOM_NAME);
const secondaryRoomId = await getCurrentRoomId(clients[0].page);
// Create invite for primary room (voice) via API
const primaryToken = await readAuthTokenFromPage(clients[0].page, testServer.url);
if (!primaryToken) {
throw new Error('Missing session token for primary signal invite creation');
}
const primaryInvite = await createInviteViaApi(
testServer.url,
primaryRoomId,
userId,
primaryToken,
clients[0].user.displayName
);
primaryRoomInviteUrl = `/invite/${primaryInvite.id}?server=${encodeURIComponent(testServer.url)}`;
// Create invite for secondary room (chat) via API
const secondaryToken = await readAuthTokenFromPage(clients[0].page, secondaryServer.url);
if (!secondaryToken) {
throw new Error('Missing session token for secondary signal invite creation');
}
const secondaryInvite = await createInviteViaApi(
secondaryServer.url,
secondaryRoomId,
userId,
secondaryToken,
clients[0].user.displayName
);
@@ -463,17 +504,55 @@ function buildUsers(): TestUser[] {
// ── API helpers ──────────────────────────────────────────────────────
async function createServerViaApi(
request: APIRequestContext,
serverBaseUrl: string,
owner: { id: string; token: string },
serverName: string
): Promise<{ id: string }> {
const response = await request.post(`${serverBaseUrl}/api/servers`, {
headers: authHeaders(owner.token),
data: {
channels: [
{
id: 'general-text',
name: 'general',
position: 0,
type: 'text'
}
],
description: `E2E room on ${serverBaseUrl}`,
id: `mixed-signal-${Date.now()}-${Math.random()
.toString(36)
.slice(2, 8)}`,
isPrivate: false,
name: serverName,
ownerId: owner.id,
ownerPublicKey: 'mixed-signal-owner-public-key',
tags: ['e2e']
}
});
if (!response.ok()) {
throw new Error(`Failed to create server via API: ${response.status()} ${await response.text()}`);
}
return await response.json() as { id: string };
}
async function createInviteViaApi(
serverBaseUrl: string,
roomId: string,
userId: string,
authToken: string,
displayName: string
): Promise<{ id: string }> {
const response = await fetch(`${serverBaseUrl}/api/servers/${roomId}/invites`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${authToken}`
},
body: JSON.stringify({
requesterUserId: userId,
requesterDisplayName: displayName
})
});
@@ -510,34 +589,6 @@ async function getCurrentRoomId(page: Page): Promise<string> {
});
}
async function getCurrentUserId(page: Page): Promise<string> {
return await page.evaluate(() => {
interface AngularDebugApi {
getComponent: (element: Element) => Record<string, unknown>;
}
interface UserShape {
id: string;
}
const host = document.querySelector('app-rooms-side-panel');
const debugApi = (window as { ng?: AngularDebugApi }).ng;
if (!host || !debugApi?.getComponent) {
throw new Error('Angular debug API unavailable');
}
const component = debugApi.getComponent(host);
const user = (component['currentUser'] as (() => UserShape | null) | undefined)?.();
if (!user?.id) {
throw new Error('Current user not found');
}
return user.id;
});
}
// ── Navigation helpers ───────────────────────────────────────────────
async function installDeterministicVoiceSettings(page: Page): Promise<void> {

View File

@@ -0,0 +1,14 @@
import {
describe,
expect,
it
} from 'vitest';
import { getLocalApiTokenTtlMs } from './auth-store';
const TEN_YEARS_MS = 10 * 365 * 24 * 60 * 60 * 1000;
describe('auth-store', () => {
it('defaults local API tokens to a very long lifetime', () => {
expect(getLocalApiTokenTtlMs()).toBe(TEN_YEARS_MS);
});
});

View File

@@ -10,9 +10,13 @@ export interface IssuedToken {
expiresAt: number;
}
const TOKEN_TTL_MS = 24 * 60 * 60 * 1000;
const DEFAULT_TOKEN_TTL_MS = 10 * 365 * 24 * 60 * 60 * 1000;
const tokens = new Map<string, IssuedToken>();
export function getLocalApiTokenTtlMs(): number {
return DEFAULT_TOKEN_TTL_MS;
}
export function issueToken(params: {
userId: string;
username: string;
@@ -24,7 +28,7 @@ export function issueToken(params: {
const issued: IssuedToken = {
token,
issuedAt,
expiresAt: issuedAt + TOKEN_TTL_MS,
expiresAt: issuedAt + getLocalApiTokenTtlMs(),
userId: params.userId,
username: params.username,
displayName: params.displayName,

View File

@@ -80,7 +80,7 @@ export function getDocsHtml(specUrl: string): string {
http-equiv="Content-Security-Policy"
content="${contentSecurityPolicy}"
/>
<title>MetoYou Local API</title>
<title>Toju Local API</title>
<style>
:root { color-scheme: light dark; }
body {

View File

@@ -18,10 +18,10 @@ export function buildOpenApiDocument(options: OpenApiBuildOptions): unknown {
return {
openapi: '3.1.0',
info: {
title: 'MetoYou Local Desktop API',
title: 'Toju Local Desktop API',
version: appVersion,
description:
'Authenticated local HTTP API exposed by the MetoYou desktop app. '
'Authenticated local HTTP API exposed by the Toju desktop app. '
+ 'Authentication is performed against a configured signaling server. '
+ 'Bearer tokens issued here are scoped to this device only.'
},

View File

@@ -0,0 +1,60 @@
import { safeStorage } from 'electron';
import {
mkdir,
readFile,
writeFile
} from 'fs/promises';
import path from 'path';
import { app } from 'electron';
const STORAGE_DIR_NAME = 'provision-secrets';
function getStorageDir(): string {
return path.join(app.getPath('userData'), STORAGE_DIR_NAME);
}
function getSecretFilePath(homeUserId: string): string {
return path.join(getStorageDir(), `${homeUserId}.bin`);
}
async function ensureStorageDir(): Promise<void> {
await mkdir(getStorageDir(), { recursive: true });
}
export async function storeProvisionSecret(homeUserId: string, secret: string): Promise<boolean> {
if (!homeUserId.trim() || !secret) {
return false;
}
await ensureStorageDir();
if (!safeStorage.isEncryptionAvailable()) {
await writeFile(getSecretFilePath(homeUserId), secret, 'utf8');
return true;
}
const encrypted = safeStorage.encryptString(secret);
await writeFile(getSecretFilePath(homeUserId), encrypted);
return true;
}
export async function getProvisionSecret(homeUserId: string): Promise<string | null> {
if (!homeUserId.trim()) {
return null;
}
try {
const filePath = getSecretFilePath(homeUserId);
const payload = await readFile(filePath);
if (!safeStorage.isEncryptionAvailable()) {
return payload.toString('utf8');
}
return safeStorage.decryptString(payload);
} catch {
return null;
}
}

23
electron/app-metrics.ts Normal file
View File

@@ -0,0 +1,23 @@
import { app } from 'electron';
export interface AppMetricsProcessSnapshot {
pid: number;
type: string;
workingSetKb: number | null;
}
export interface AppMetricsSnapshot {
collectedAt: number;
processes: AppMetricsProcessSnapshot[];
}
export function collectAppMetricsSnapshot(): AppMetricsSnapshot {
return {
collectedAt: Date.now(),
processes: app.getAppMetrics().map((metric) => ({
pid: metric.pid,
type: metric.type,
workingSetKb: metric.memory?.workingSetSize ?? null
}))
};
}

View File

@@ -3,21 +3,14 @@ import AutoLaunch from 'auto-launch';
import * as fsp from 'fs/promises';
import * as path from 'path';
import { readDesktopSettings } from '../desktop-settings';
import { DESKTOP_APP_DISPLAY_NAME, patchLinuxAutostartDesktopEntryNameField } from './desktop-branding.rules';
import { resolveLaunchPath } from './launch-path';
let autoLauncher: AutoLaunch | null = null;
let autoLaunchPath = '';
const LINUX_AUTO_START_ARGUMENTS = ['--no-sandbox', '%U'];
function resolveLaunchPath(): string {
// AppImage runs from a temporary mount; APPIMAGE points to the real file path.
const appImagePath = process.platform === 'linux'
? String(process.env['APPIMAGE'] || '').trim()
: '';
return appImagePath || process.execPath;
}
function escapeDesktopEntryExecArgument(argument: string): string {
const escapedArgument = argument.replace(/(["\\$`])/g, '\\$1');
@@ -35,14 +28,12 @@ function buildLinuxAutoStartExecLine(launchPath: string): string {
}
function buildLinuxAutoStartDesktopEntry(launchPath: string): string {
const appName = path.basename(launchPath);
return [
'[Desktop Entry]',
'Type=Application',
'Version=1.0',
`Name=${appName}`,
`Comment=${appName}startup script`,
`Name=${DESKTOP_APP_DISPLAY_NAME}`,
`Comment=${DESKTOP_APP_DISPLAY_NAME} startup script`,
buildLinuxAutoStartExecLine(launchPath),
'StartupNotify=false',
'Terminal=false'
@@ -65,11 +56,13 @@ async function synchronizeLinuxAutoStartDesktopEntry(launchPath: string): Promis
// Create the desktop entry if auto-launch did not leave one behind.
}
const nextDesktopEntry = currentDesktopEntry
? /^Exec=.*$/m.test(currentDesktopEntry)
? currentDesktopEntry.replace(/^Exec=.*$/m, execLine)
: `${currentDesktopEntry.trimEnd()}\n${execLine}\n`
: buildLinuxAutoStartDesktopEntry(launchPath);
const nextDesktopEntry = patchLinuxAutostartDesktopEntryNameField(
currentDesktopEntry
? /^Exec=.*$/m.test(currentDesktopEntry)
? currentDesktopEntry.replace(/^Exec=.*$/m, execLine)
: `${currentDesktopEntry.trimEnd()}\n${execLine}\n`
: buildLinuxAutoStartDesktopEntry(launchPath)
);
if (nextDesktopEntry === currentDesktopEntry) {
return;
@@ -87,7 +80,7 @@ function getAutoLauncher(): AutoLaunch | null {
if (!autoLauncher) {
autoLaunchPath = resolveLaunchPath();
autoLauncher = new AutoLaunch({
name: app.getName(),
name: DESKTOP_APP_DISPLAY_NAME,
path: autoLaunchPath
});
}

View File

@@ -0,0 +1,88 @@
import { app } from 'electron';
import AutoLaunch from 'auto-launch';
import * as fsp from 'fs/promises';
import * as path from 'path';
import {
DESKTOP_APP_DISPLAY_NAME,
isLegacyLinuxAutostartEntry,
LEGACY_APP_REGISTRY_NAMES
} from './desktop-branding.rules';
import { resolveLaunchPath } from './launch-path';
function getLinuxAutoStartDirectory(): string {
return path.join(app.getPath('home'), '.config', 'autostart');
}
export function configureDesktopBranding(): void {
if (!app.isPackaged) {
return;
}
app.setName(DESKTOP_APP_DISPLAY_NAME);
if (process.platform !== 'darwin') {
process.title = DESKTOP_APP_DISPLAY_NAME;
}
}
async function removeLegacyLinuxAutostartEntries(launchPath: string): Promise<void> {
if (process.platform !== 'linux') {
return;
}
const autostartDirectory = getLinuxAutoStartDirectory();
const currentLaunchBaseName = path.basename(launchPath);
let fileNames: string[] = [];
try {
fileNames = await fsp.readdir(autostartDirectory);
} catch {
return;
}
await Promise.all(fileNames.map(async (fileName) => {
if (!fileName.endsWith('.desktop')) {
return;
}
if (!isLegacyLinuxAutostartEntry(fileName, currentLaunchBaseName)) {
return;
}
await fsp.unlink(path.join(autostartDirectory, fileName)).catch(() => {});
}));
}
async function disableLegacyWindowsAutoLaunchEntries(launchPath: string): Promise<void> {
if (process.platform !== 'win32') {
return;
}
await Promise.all(LEGACY_APP_REGISTRY_NAMES.map(async (legacyName) => {
const launcher = new AutoLaunch({
name: legacyName,
path: launchPath
});
try {
if (await launcher.isEnabled()) {
await launcher.disable();
}
} catch {
// Best-effort cleanup for renamed desktop binaries.
}
}));
}
export async function migrateLegacyDesktopBranding(): Promise<void> {
if (!app.isPackaged) {
return;
}
const launchPath = resolveLaunchPath();
await removeLegacyLinuxAutostartEntries(launchPath);
await disableLegacyWindowsAutoLaunchEntries(launchPath);
}

View File

@@ -0,0 +1,45 @@
import {
describe,
expect,
it
} from 'vitest';
import {
DESKTOP_APP_DISPLAY_NAME,
DESKTOP_EXECUTABLE_NAME,
LEGACY_APP_REGISTRY_NAMES,
isLegacyLinuxAutostartEntry,
patchLinuxAutostartDesktopEntryNameField
} from './desktop-branding.rules';
describe('desktop-branding.rules', () => {
it('exposes the Toju desktop branding constants', () => {
expect(DESKTOP_APP_DISPLAY_NAME).toBe('Toju');
expect(DESKTOP_EXECUTABLE_NAME).toBe('toju');
expect(LEGACY_APP_REGISTRY_NAMES).toContain('MetoYou');
expect(LEGACY_APP_REGISTRY_NAMES).toContain('metoyou');
});
it('treats legacy linux autostart entries as removable', () => {
expect(isLegacyLinuxAutostartEntry('metoyou.desktop', 'toju')).toBe(true);
expect(isLegacyLinuxAutostartEntry('MetoYou.desktop', 'toju')).toBe(true);
expect(isLegacyLinuxAutostartEntry('MetoYou-1.0.0-x86_64.AppImage.desktop', 'Toju-1.1.0-x86_64.AppImage')).toBe(true);
});
it('keeps the current launch entry when it already uses the Toju binary', () => {
expect(isLegacyLinuxAutostartEntry('toju.desktop', 'toju')).toBe(false);
expect(isLegacyLinuxAutostartEntry('Toju-1.1.0-x86_64.AppImage.desktop', 'Toju-1.1.0-x86_64.AppImage')).toBe(false);
});
it('rewrites the desktop entry display name to Toju', () => {
const patched = patchLinuxAutostartDesktopEntryNameField([
'[Desktop Entry]',
'Type=Application',
'Name=metoyou',
'Exec=/opt/Toju/toju --no-sandbox %U'
].join('\n'));
expect(patched).toContain('Name=Toju');
expect(patched).not.toContain('Name=metoyou');
});
});

View File

@@ -0,0 +1,43 @@
export const DESKTOP_APP_DISPLAY_NAME = 'Toju';
export const DESKTOP_EXECUTABLE_NAME = 'toju';
export const LEGACY_APP_REGISTRY_NAMES = [
'MetoYou',
'MeToYou',
'metoyou'
] as const;
function normalizeAutostartBaseName(fileName: string): string {
return fileName.replace(/\.desktop$/iu, '').replace(/\.exe$/iu, '');
}
export function isLegacyLinuxAutostartEntry(
fileName: string,
currentLaunchBaseName: string
): boolean {
const entryBaseName = normalizeAutostartBaseName(fileName);
const currentBaseName = normalizeAutostartBaseName(currentLaunchBaseName);
if (entryBaseName === currentBaseName) {
return false;
}
const normalizedEntry = entryBaseName.toLowerCase();
if (LEGACY_APP_REGISTRY_NAMES.some((legacyName) => normalizedEntry === legacyName.toLowerCase())) {
return true;
}
return /^metoyou[-.]/iu.test(entryBaseName);
}
export function patchLinuxAutostartDesktopEntryNameField(
desktopEntry: string,
displayName: string = DESKTOP_APP_DISPLAY_NAME
): string {
if (/^Name=.*$/m.test(desktopEntry)) {
return desktopEntry.replace(/^Name=.*$/m, `Name=${displayName}`);
}
return desktopEntry;
}

View File

@@ -1,7 +1,9 @@
import { app } from 'electron';
import { configureDesktopBranding } from './desktop-branding-migration';
import { readDesktopSettings } from '../desktop-settings';
export function configureAppFlags(): void {
configureDesktopBranding();
linuxSpecificFlags();
networkFlags();
setupGpuEncodingFlags();

View File

@@ -0,0 +1,8 @@
/** Resolves the packaged binary path used for auto-start and updater migration. */
export function resolveLaunchPath(): string {
const appImagePath = process.platform === 'linux'
? String(process.env['APPIMAGE'] || '').trim()
: '';
return appImagePath || process.execPath;
}

View File

@@ -2,6 +2,7 @@ import { app, BrowserWindow } from 'electron';
import { cleanupLinuxScreenShareAudioRouting } from '../audio/linux-screen-share-routing';
import { initializeDesktopUpdater, shutdownDesktopUpdater } from '../update/desktop-updater';
import { synchronizeAutoStartSetting } from './auto-start';
import { migrateLegacyDesktopBranding } from './desktop-branding-migration';
import { applyLocalApiSettings, stopLocalApiServer } from '../api';
import {
initializeDatabase,
@@ -21,6 +22,12 @@ import {
setupWindowControlHandlers
} from '../ipc';
import { startIdleMonitor, stopIdleMonitor } from '../idle/idle-monitor';
import {
attachRendererDiagnosticsHooks,
ensurePerfDiagIpcRegistered,
shutdownPerfDiagnostics,
startPerfDiagnostics
} from '../diagnostics';
function startLocalApiAfterWindowReady(): void {
setImmediate(() => {
@@ -31,6 +38,8 @@ function startLocalApiAfterWindowReady(): void {
}
export function registerAppLifecycle(): void {
ensurePerfDiagIpcRegistered();
app.whenReady().then(async () => {
const dockIconPath = getDockIconPath();
@@ -41,9 +50,18 @@ export function registerAppLifecycle(): void {
setupCqrsHandlers();
setupWindowControlHandlers();
setupSystemHandlers();
await migrateLegacyDesktopBranding();
await synchronizeAutoStartSetting();
initializeDesktopUpdater();
startPerfDiagnostics();
await createWindow();
const mainWindow = getMainWindow();
if (mainWindow) {
attachRendererDiagnosticsHooks(mainWindow);
}
startLocalApiAfterWindowReady();
startIdleMonitor();
@@ -65,6 +83,7 @@ export function registerAppLifecycle(): void {
app.on('before-quit', async (event) => {
prepareWindowForAppQuit();
await shutdownPerfDiagnostics();
if (getDataSource()?.isInitialized) {
event.preventDefault();

View File

@@ -20,6 +20,8 @@ export async function handleSaveMessage(command: SaveMessageCommand, dataSource:
content: message.content,
timestamp: message.timestamp,
editedAt: message.editedAt ?? null,
revision: message.revision ?? 0,
headHash: message.headHash ?? null,
isDeleted: message.isDeleted ? 1 : 0,
replyToId: message.replyToId ?? null,
linkMetadata: message.linkMetadata ? JSON.stringify(message.linkMetadata) : null

View File

@@ -36,7 +36,8 @@ export async function handleUpdateMessage(command: UpdateMessageCommand, dataSou
const nullableFields = [
'channelId',
'editedAt',
'replyToId'
'replyToId',
'headHash'
] as const;
for (const field of nullableFields) {
@@ -44,8 +45,13 @@ export async function handleUpdateMessage(command: UpdateMessageCommand, dataSou
entity[field] = updates[field] ?? null;
}
if (updates.isDeleted !== undefined)
if (updates.revision !== undefined) {
existing.revision = updates.revision;
}
if (updates.isDeleted !== undefined) {
existing.isDeleted = updates.isDeleted ? 1 : 0;
}
if (updates.linkMetadata !== undefined)
existing.linkMetadata = updates.linkMetadata ? JSON.stringify(updates.linkMetadata) : null;

View File

@@ -34,6 +34,8 @@ export function rowToMessage(row: MessageEntity, reactions: ReactionPayload[] =
content: isDeleted ? DELETED_MESSAGE_CONTENT : row.content,
timestamp: row.timestamp,
editedAt: row.editedAt ?? undefined,
revision: row.revision ?? 0,
headHash: row.headHash ?? undefined,
reactions: isDeleted ? [] : reactions,
isDeleted,
replyToId: row.replyToId ?? undefined,

View File

@@ -57,6 +57,8 @@ export interface MessagePayload {
content: string;
timestamp: number;
editedAt?: number;
revision?: number;
headHash?: string;
reactions?: ReactionPayload[];
isDeleted?: boolean;
replyToId?: string;

View File

@@ -47,8 +47,8 @@ export async function exportUserData(): Promise<ExportUserDataResult> {
.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'
filters: [{ extensions: ['dat'], name: 'Toju data archive' }],
title: 'Export Toju data'
});
if (canceled || !filePath) {
@@ -87,9 +87,9 @@ export async function exportUserData(): Promise<ExportUserDataResult> {
export async function importUserData(): Promise<ImportUserDataResult> {
const { canceled, filePaths } = await dialog.showOpenDialog({
filters: [{ extensions: ['dat', 'zip'], name: 'MetoYou data archive' }],
filters: [{ extensions: ['dat', 'zip'], name: 'Toju data archive' }],
properties: ['openFile'],
title: 'Import MetoYou data'
title: 'Import Toju data'
});
if (canceled || filePaths.length === 0) {
@@ -235,7 +235,7 @@ 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.');
throw new Error('The selected file is missing a Toju data manifest.');
}
const parsed = JSON.parse(manifest.data.toString('utf8')) as { format?: string; version?: number };

View File

@@ -0,0 +1,27 @@
import {
describe,
it,
expect
} from 'vitest';
import { isPerfDiagEnabled } from './diagnostics.flags';
describe('isPerfDiagEnabled', () => {
it('returns false when the flag is unset', () => {
expect(isPerfDiagEnabled({}, false)).toBe(false);
expect(isPerfDiagEnabled({}, true)).toBe(false);
});
it('returns true in development when METOYOU_PERF_DIAG is truthy', () => {
expect(isPerfDiagEnabled({ METOYOU_PERF_DIAG: '1' }, false)).toBe(true);
expect(isPerfDiagEnabled({ METOYOU_PERF_DIAG: 'true' }, false)).toBe(true);
expect(isPerfDiagEnabled({ METOYOU_PERF_DIAG: 'on' }, false)).toBe(true);
});
it('returns false in packaged builds unless force is set', () => {
expect(isPerfDiagEnabled({ METOYOU_PERF_DIAG: '1' }, true)).toBe(false);
expect(isPerfDiagEnabled({
METOYOU_PERF_DIAG: '1',
METOYOU_PERF_DIAG_FORCE: '1'
}, true)).toBe(true);
});
});

View File

@@ -0,0 +1,29 @@
export const PERF_DIAG_ENV = 'METOYOU_PERF_DIAG';
export const PERF_DIAG_FORCE_ENV = 'METOYOU_PERF_DIAG_FORCE';
const TRUTHY = new Set([
'1',
'true',
'yes',
'on'
]);
function isTruthyFlag(value: string | undefined): boolean {
return TRUTHY.has(String(value ?? '').trim()
.toLowerCase());
}
export function isPerfDiagEnabled(
env: NodeJS.ProcessEnv,
isPackaged: boolean
): boolean {
if (!isTruthyFlag(env[PERF_DIAG_ENV])) {
return false;
}
if (isPackaged && !isTruthyFlag(env[PERF_DIAG_FORCE_ENV])) {
return false;
}
return true;
}

View File

@@ -0,0 +1,214 @@
import {
app,
BrowserWindow,
ipcMain
} from 'electron';
import { collectAppMetricsSnapshot } from '../app-metrics';
import { sumWorkingSetKb } from './process-metrics.rules';
import { isPerfDiagEnabled } from './diagnostics.flags';
import type { PerfDiagEntry } from './diagnostics.models';
import { PerfDiagWriter } from './diagnostics.writer';
const PROCESS_POLL_INTERVAL_MS = 5_000;
let activeWriter: PerfDiagWriter | null = null;
let processPollTimer: NodeJS.Timeout | null = null;
let diagnosticsEnabled = false;
let ipcRegistered = false;
export function isPerfDiagActive(): boolean {
return diagnosticsEnabled;
}
export function ensurePerfDiagIpcRegistered(): void {
if (ipcRegistered) {
return;
}
ipcRegistered = true;
ipcMain.handle('perf-diag-is-enabled', () => diagnosticsEnabled);
ipcMain.handle('perf-diag-report', (_event, entry: PerfDiagEntry) => {
const writer = activeWriter;
if (!diagnosticsEnabled || !writer) {
return false;
}
try {
writer.append(normalizeRendererEntry(entry));
return true;
} catch {
return false;
}
});
}
export function getActivePerfDiagWriter(): PerfDiagWriter | null {
return activeWriter;
}
export function startPerfDiagnostics(): PerfDiagWriter | null {
ensurePerfDiagIpcRegistered();
diagnosticsEnabled = isPerfDiagEnabled(process.env, app.isPackaged);
if (!diagnosticsEnabled) {
return null;
}
const sessionId = `${Date.now().toString(36)}-${process.pid}`;
const writer = new PerfDiagWriter({
userDataPath: app.getPath('userData'),
sessionId
});
activeWriter = writer;
registerProcessCrashHandlers(writer);
startProcessMetricsPolling(writer);
writer.append({
collectedAt: Date.now(),
source: 'main',
type: 'session',
payload: {
event: 'started',
sessionId,
filePath: writer.snapshotFilePath
}
});
return writer;
}
export function attachRendererDiagnosticsHooks(window: BrowserWindow): void {
const writer = activeWriter;
if (!writer) {
return;
}
window.webContents.on('render-process-gone', (_event, details) => {
writer.append({
collectedAt: Date.now(),
source: 'main',
type: 'crash',
payload: {
reason: details.reason,
exitCode: details.exitCode
}
});
void writer.flushSnapshot('render-process-gone');
});
window.webContents.on('unresponsive', () => {
writer.append({
collectedAt: Date.now(),
source: 'main',
type: 'unresponsive',
payload: {}
});
});
window.webContents.on('responsive', () => {
writer.append({
collectedAt: Date.now(),
source: 'main',
type: 'session',
payload: { event: 'renderer-responsive' }
});
});
}
export async function shutdownPerfDiagnostics(): Promise<void> {
if (!activeWriter) {
return;
}
await activeWriter.flushSnapshot('shutdown');
if (processPollTimer) {
clearInterval(processPollTimer);
processPollTimer = null;
}
activeWriter = null;
diagnosticsEnabled = false;
}
function registerProcessCrashHandlers(writer: PerfDiagWriter): void {
app.on('child-process-gone', (_event, details) => {
writer.append({
collectedAt: Date.now(),
source: 'main',
type: 'crash',
payload: {
type: details.type,
reason: details.reason,
exitCode: details.exitCode,
serviceName: details.serviceName ?? null,
name: details.name ?? null
}
});
});
process.on('uncaughtException', (error) => {
writer.append({
collectedAt: Date.now(),
source: 'main',
type: 'crash',
payload: {
scope: 'main-uncaughtException',
message: error.message
}
});
void writer.flushSnapshot('uncaughtException');
});
process.on('unhandledRejection', (reason) => {
writer.append({
collectedAt: Date.now(),
source: 'main',
type: 'crash',
payload: {
scope: 'main-unhandledRejection',
reason: String(reason)
}
});
});
}
function startProcessMetricsPolling(writer: PerfDiagWriter): void {
const sample = (): void => {
try {
const metrics = collectAppMetricsSnapshot();
const totalKb = sumWorkingSetKb(metrics.processes);
writer.append({
collectedAt: metrics.collectedAt,
source: 'main',
type: 'process',
payload: {
totalWorkingSetKb: totalKb,
processes: metrics.processes
}
});
} catch {
// Collector failures must never affect the app.
}
};
sample();
processPollTimer = setInterval(sample, PROCESS_POLL_INTERVAL_MS);
}
function normalizeRendererEntry(entry: PerfDiagEntry): PerfDiagEntry {
return {
collectedAt: Number(entry.collectedAt) || Date.now(),
source: 'renderer',
type: entry.type,
payload: entry.payload ?? {}
};
}

View File

@@ -0,0 +1,17 @@
export type PerfDiagSource = 'main' | 'renderer';
export type PerfDiagEntryType =
| 'session'
| 'process'
| 'store'
| 'components'
| 'heap'
| 'crash'
| 'unresponsive';
export interface PerfDiagEntry {
collectedAt: number;
source: PerfDiagSource;
type: PerfDiagEntryType;
payload: Record<string, unknown>;
}

View File

@@ -0,0 +1,53 @@
import {
describe,
it,
expect
} from 'vitest';
import {
formatPerfDiagLine,
pushRingBuffer,
resolveDiagnosticsFilePath
} from './diagnostics.rules';
describe('pushRingBuffer', () => {
it('appends items until capacity is reached', () => {
expect(pushRingBuffer([1, 2], 3, 4)).toEqual([
1,
2,
3
]);
});
it('drops the oldest items when capacity is exceeded', () => {
expect(pushRingBuffer([
1,
2,
3
], 4, 3)).toEqual([
2,
3,
4
]);
});
});
describe('formatPerfDiagLine', () => {
it('serializes one JSON object per line', () => {
const line = formatPerfDiagLine({
collectedAt: 1_700_000_000_000,
source: 'main',
type: 'process',
payload: { browserKb: 128 }
});
expect(line).toBe('{"collectedAt":1700000000000,"source":"main","type":"process","payload":{"browserKb":128}}');
expect(line.endsWith('\n')).toBe(false);
});
});
describe('resolveDiagnosticsFilePath', () => {
it('places session files under diagnostics/', () => {
expect(resolveDiagnosticsFilePath('/tmp/user-data', 'session-1'))
.toBe('/tmp/user-data/diagnostics/perf-session-1.jsonl');
});
});

View File

@@ -0,0 +1,24 @@
import * as path from 'path';
import type { PerfDiagEntry } from './diagnostics.models';
export function pushRingBuffer<T>(items: readonly T[], item: T, capacity: number): T[] {
const next = [...items, item];
if (next.length <= capacity) {
return next;
}
return next.slice(next.length - capacity);
}
export function formatPerfDiagLine(entry: PerfDiagEntry): string {
return JSON.stringify(entry);
}
export function resolveDiagnosticsFilePath(userDataPath: string, sessionId: string): string {
return path.join(userDataPath, 'diagnostics', `perf-${sessionId}.jsonl`);
}
export function resolveDiagnosticsDirectory(userDataPath: string): string {
return path.join(userDataPath, 'diagnostics');
}

View File

@@ -0,0 +1,108 @@
import * as fsp from 'fs/promises';
import * as path from 'path';
import type { PerfDiagEntry } from './diagnostics.models';
import {
formatPerfDiagLine,
pushRingBuffer,
resolveDiagnosticsFilePath
} from './diagnostics.rules';
const DEFAULT_RING_CAPACITY = 120;
const FLUSH_DEBOUNCE_MS = 250;
export interface PerfDiagWriterOptions {
userDataPath: string;
sessionId: string;
ringCapacity?: number;
}
export class PerfDiagWriter {
private readonly filePath: string;
private readonly ringCapacity: number;
private readonly pendingLines: string[] = [];
private ring: PerfDiagEntry[] = [];
private flushTimer: NodeJS.Timeout | null = null;
private flushInFlight: Promise<void> | null = null;
private disabled = false;
constructor(options: PerfDiagWriterOptions) {
this.filePath = resolveDiagnosticsFilePath(options.userDataPath, options.sessionId);
this.ringCapacity = options.ringCapacity ?? DEFAULT_RING_CAPACITY;
}
get snapshotFilePath(): string {
return this.filePath;
}
get bufferedEntries(): readonly PerfDiagEntry[] {
return this.ring;
}
append(entry: PerfDiagEntry): void {
if (this.disabled) {
return;
}
try {
this.ring = pushRingBuffer(this.ring, entry, this.ringCapacity);
this.pendingLines.push(`${formatPerfDiagLine(entry)}\n`);
this.scheduleFlush();
} catch {
this.disabled = true;
}
}
async flush(): Promise<void> {
if (this.disabled || this.pendingLines.length === 0) {
return;
}
if (this.flushInFlight) {
await this.flushInFlight;
return;
}
const lines = this.pendingLines.splice(0, this.pendingLines.length);
this.flushInFlight = this.writeLines(lines)
.catch(() => {
this.disabled = true;
})
.finally(() => {
this.flushInFlight = null;
});
await this.flushInFlight;
}
async flushSnapshot(label: string): Promise<void> {
this.append({
collectedAt: Date.now(),
source: 'main',
type: 'session',
payload: {
event: label,
filePath: this.filePath,
entries: this.ring
}
});
await this.flush();
}
private scheduleFlush(): void {
if (this.flushTimer) {
return;
}
this.flushTimer = setTimeout(() => {
this.flushTimer = null;
void this.flush();
}, FLUSH_DEBOUNCE_MS);
}
private async writeLines(lines: string[]): Promise<void> {
await fsp.mkdir(path.dirname(this.filePath), { recursive: true });
await fsp.appendFile(this.filePath, lines.join(''), 'utf8');
}
}

View File

@@ -0,0 +1,11 @@
export { isPerfDiagEnabled, PERF_DIAG_ENV, PERF_DIAG_FORCE_ENV } from './diagnostics.flags';
export {
attachRendererDiagnosticsHooks,
ensurePerfDiagIpcRegistered,
getActivePerfDiagWriter,
isPerfDiagActive,
shutdownPerfDiagnostics,
startPerfDiagnostics
} from './diagnostics.lifecycle';
export type { PerfDiagEntry, PerfDiagEntryType, PerfDiagSource } from './diagnostics.models';
export { PerfDiagWriter } from './diagnostics.writer';

View File

@@ -0,0 +1,19 @@
export interface ProcessWorkingSetSnapshot {
workingSetKb: number | null;
}
export function sumWorkingSetKb(processes: readonly ProcessWorkingSetSnapshot[]): number | null {
let total = 0;
let hasAny = false;
for (const process of processes) {
if (process.workingSetKb == null || process.workingSetKb < 0) {
continue;
}
total += process.workingSetKb;
hasAny = true;
}
return hasAny ? total : null;
}

View File

@@ -41,4 +41,10 @@ export class MessageEntity {
@Column('text', { nullable: true })
linkMetadata!: string | null;
@Column('integer', { default: 0 })
revision!: number;
@Column('text', { nullable: true })
headHash!: string | null;
}

View File

@@ -105,6 +105,7 @@ export const HARDCODED_IGNORED_PROCESSES: ReadonlySet<string> = new Set([
'logitechg',
'login',
'metoyou',
'toju',
'msedge',
'msedgewebview2',
'msteams',

View File

@@ -7,13 +7,24 @@ import {
afterEach
} from 'vitest';
// Mock Electron modules before importing the module under test
const mockGetSystemIdleTime = vi.fn(() => 0);
const mockSend = vi.fn();
const mockGetMainWindow = vi.fn(() => ({
isDestroyed: () => false,
webContents: { send: mockSend }
}));
const {
mockGetSystemIdleTime,
mockSend,
mockGetMainWindow
} = vi.hoisted(() => {
const send = vi.fn();
const getSystemIdleTime = vi.fn(() => 0);
const getMainWindow = vi.fn(() => ({
isDestroyed: () => false,
webContents: { send }
}));
return {
mockGetSystemIdleTime: getSystemIdleTime,
mockSend: send,
mockGetMainWindow: getMainWindow
};
});
vi.mock('electron', () => ({
powerMonitor: {

View File

@@ -20,6 +20,7 @@ import {
type DesktopSettings
} from '../desktop-settings';
import { applyLocalApiSettings, getLocalApiSnapshot } from '../api';
import { getProvisionSecret, storeProvisionSecret } from '../api/provision-secret-store';
import {
activateLinuxScreenShareAudioRouting,
deactivateLinuxScreenShareAudioRouting,
@@ -60,6 +61,13 @@ import {
} from '../data-management';
import { listRunningProcessNames } from '../process-list';
import { detectActiveGame } from '../game-detection';
import { collectAppMetricsSnapshot } from '../app-metrics';
import { clearAllTokens } from '../api/auth-store';
import {
assertPathUnderUserData,
grantPluginReadRoot,
resolveReadablePath
} from '../path-jail';
const DEFAULT_MIME_TYPE = 'application/octet-stream';
const MAX_ACTIVE_DESKTOP_NOTIFICATIONS = 20;
@@ -71,6 +79,19 @@ const FILE_CLIPBOARD_FORMATS = [
'public.file-url',
'FileNameW'
] as const;
async function resolveUserDataFilePath(filePath: string): Promise<string | null> {
return await resolveReadablePath(filePath);
}
async function resolveWritableUserDataFilePath(filePath: string): Promise<string | null> {
try {
return await assertPathUnderUserData(filePath);
} catch {
return null;
}
}
const MIME_TYPES_BY_EXTENSION: Record<string, string> = {
'.7z': 'application/x-7z-compressed',
'.aac': 'audio/aac',
@@ -362,6 +383,16 @@ export function setupSystemHandlers(): void {
return await stopLinuxScreenShareMonitorCapture(captureId);
});
ipcMain.handle('get-app-metrics', () => collectAppMetricsSnapshot());
ipcMain.handle('store-provision-secret', async (_event, homeUserId: string, secret: string) =>
await storeProvisionSecret(homeUserId, secret)
);
ipcMain.handle('get-provision-secret', async (_event, homeUserId: string) =>
await getProvisionSecret(homeUserId)
);
ipcMain.handle('get-app-data-path', () => app.getPath('userData'));
ipcMain.handle('open-current-data-folder', async () => await openCurrentDataFolder());
ipcMain.handle('export-user-data', async () => await exportUserData());
@@ -493,6 +524,10 @@ export function setupSystemHandlers(): void {
ipcMain.handle('set-desktop-settings', async (_event, patch: Partial<DesktopSettings>) => {
const snapshot = updateDesktopSettings(patch);
if (Object.prototype.hasOwnProperty.call(patch, 'allowedSignalingServers')) {
clearAllTokens();
}
await synchronizeAutoStartSetting(snapshot.autoStart);
updateCloseToTraySetting(snapshot.closeToTray);
await handleDesktopSettingsChanged();
@@ -562,6 +597,12 @@ export function setupSystemHandlers(): void {
return false;
}
const scopedDestination = await resolveWritableUserDataFilePath(destinationFilePath);
if (!scopedDestination) {
return false;
}
try {
const stats = await fsp.stat(sourceFilePath);
@@ -569,7 +610,7 @@ export function setupSystemHandlers(): void {
return false;
}
await fsp.copyFile(sourceFilePath, destinationFilePath);
await fsp.copyFile(sourceFilePath, scopedDestination);
return true;
} catch {
return false;
@@ -577,8 +618,14 @@ export function setupSystemHandlers(): void {
});
ipcMain.handle('file-exists', async (_event, filePath: string) => {
const scopedPath = await resolveUserDataFilePath(filePath);
if (!scopedPath) {
return false;
}
try {
await fsp.access(filePath, fs.constants.F_OK);
await fsp.access(scopedPath, fs.constants.F_OK);
return true;
} catch {
return false;
@@ -586,26 +633,40 @@ export function setupSystemHandlers(): void {
});
ipcMain.handle('get-file-url', async (_event, filePath: string) => {
if (typeof filePath !== 'string' || !filePath.trim()) {
const scopedPath = await resolveUserDataFilePath(filePath);
if (!scopedPath) {
return null;
}
try {
await fsp.access(filePath, fs.constants.F_OK);
return pathToFileURL(filePath).toString();
await fsp.access(scopedPath, fs.constants.F_OK);
return pathToFileURL(scopedPath).toString();
} catch {
return null;
}
});
ipcMain.handle('read-file', async (_event, filePath: string) => {
const data = await fsp.readFile(filePath);
const scopedPath = await resolveUserDataFilePath(filePath);
if (!scopedPath) {
return null;
}
const data = await fsp.readFile(scopedPath);
return data.toString('base64');
});
ipcMain.handle('read-file-chunk', async (_event, filePath: string, start: number, end: number) => {
const fileHandle = await fsp.open(filePath, 'r');
const scopedPath = await resolveUserDataFilePath(filePath);
if (!scopedPath) {
return null;
}
const fileHandle = await fsp.open(scopedPath, 'r');
try {
const safeStart = Math.max(0, Math.trunc(start));
@@ -620,7 +681,13 @@ export function setupSystemHandlers(): void {
});
ipcMain.handle('get-file-size', async (_event, filePath: string) => {
const stats = await fsp.stat(filePath);
const scopedPath = await resolveUserDataFilePath(filePath);
if (!scopedPath) {
return null;
}
const stats = await fsp.stat(scopedPath);
return stats.size;
});
@@ -629,23 +696,47 @@ export function setupSystemHandlers(): void {
return await readClipboardFiles();
});
ipcMain.handle('grant-plugin-read-root', (_event, rootPath: string) => {
grantPluginReadRoot(rootPath);
return true;
});
ipcMain.handle('write-file', async (_event, filePath: string, base64Data: string) => {
const scopedPath = await resolveWritableUserDataFilePath(filePath);
if (!scopedPath) {
return false;
}
const buffer = Buffer.from(base64Data, 'base64');
await fsp.writeFile(filePath, buffer);
await fsp.writeFile(scopedPath, buffer);
return true;
});
ipcMain.handle('append-file', async (_event, filePath: string, base64Data: string) => {
const scopedPath = await resolveWritableUserDataFilePath(filePath);
if (!scopedPath) {
return false;
}
const buffer = Buffer.from(base64Data, 'base64');
await fsp.appendFile(filePath, buffer);
await fsp.appendFile(scopedPath, buffer);
return true;
});
ipcMain.handle('delete-file', async (_event, filePath: string) => {
const scopedPath = await resolveWritableUserDataFilePath(filePath);
if (!scopedPath) {
return false;
}
try {
await fsp.unlink(filePath);
await fsp.unlink(scopedPath);
return true;
} catch (error) {
if ((error as { code?: string }).code === 'ENOENT') {
@@ -680,7 +771,14 @@ export function setupSystemHandlers(): void {
cancelled: false };
}
const stats = await fsp.stat(sourceFilePath);
const scopedSourcePath = await resolveUserDataFilePath(sourceFilePath);
if (!scopedSourcePath) {
return { saved: false,
cancelled: false };
}
const stats = await fsp.stat(scopedSourcePath);
if (!stats.isFile()) {
return { saved: false,
@@ -688,7 +786,7 @@ export function setupSystemHandlers(): void {
}
const result = await dialog.showSaveDialog({
defaultPath: defaultFileName || path.basename(sourceFilePath)
defaultPath: defaultFileName || path.basename(scopedSourcePath)
});
if (result.canceled || !result.filePath) {
@@ -696,7 +794,7 @@ export function setupSystemHandlers(): void {
cancelled: true };
}
await fsp.copyFile(sourceFilePath, result.filePath);
await fsp.copyFile(scopedSourcePath, result.filePath);
return { saved: true,
cancelled: false };
@@ -708,15 +806,22 @@ export function setupSystemHandlers(): void {
reason: 'missing-path' };
}
const scopedPath = await resolveUserDataFilePath(filePath);
if (!scopedPath) {
return { opened: false,
reason: 'outside-app-data' };
}
try {
const stats = await fsp.stat(filePath);
const stats = await fsp.stat(scopedPath);
if (!stats.isFile()) {
return { opened: false,
reason: 'not-a-file' };
}
const error = await shell.openPath(filePath);
const error = await shell.openPath(scopedPath);
return error
? { opened: false,
@@ -729,7 +834,13 @@ export function setupSystemHandlers(): void {
});
ipcMain.handle('ensure-dir', async (_event, dirPath: string) => {
await fsp.mkdir(dirPath, { recursive: true });
const scopedPath = await resolveWritableUserDataFilePath(dirPath);
if (!scopedPath) {
return false;
}
await fsp.mkdir(scopedPath, { recursive: true });
return true;
});

View File

@@ -0,0 +1,15 @@
import { MigrationInterface, QueryRunner } from 'typeorm';
export class MessageIntegrity1000000000013 implements MigrationInterface {
name = 'MessageIntegrity1000000000013';
async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query('ALTER TABLE "messages" ADD COLUMN "revision" integer NOT NULL DEFAULT 0');
await queryRunner.query('ALTER TABLE "messages" ADD COLUMN "headHash" text');
}
async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query('ALTER TABLE "messages" DROP COLUMN "headHash"');
await queryRunner.query('ALTER TABLE "messages" DROP COLUMN "revision"');
}
}

View File

@@ -0,0 +1,73 @@
import {
describe,
it,
expect,
beforeEach,
afterEach
} from 'vitest';
import * as fs from 'fs';
import * as os from 'os';
import * as path from 'path';
import {
assertPathUnderRoot,
clearGrantedPluginReadRoots,
grantPluginReadRoot,
resolveReadablePath
} from './path-jail';
describe('path-jail', () => {
let tempRoot = '';
beforeEach(() => {
tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'metoyou-path-jail-'));
fs.mkdirSync(path.join(tempRoot, 'server', 'room-1'), { recursive: true });
fs.writeFileSync(path.join(tempRoot, 'server', 'room-1', 'file.txt'), 'ok');
});
afterEach(() => {
clearGrantedPluginReadRoots();
fs.rmSync(tempRoot, { recursive: true, force: true });
});
it('accepts paths inside allowed subdirectories', async () => {
const allowedPath = path.join(tempRoot, 'server', 'room-1', 'file.txt');
await expect(assertPathUnderRoot(tempRoot, allowedPath, ['server'])).resolves.toBe(allowedPath);
});
it('accepts cached plugin bundle paths under plugin-bundles', async () => {
const bundleDir = path.join(tempRoot, 'plugin-bundles', 'example.plugin', '1.0.0');
fs.mkdirSync(bundleDir, { recursive: true });
const bundlePath = path.join(bundleDir, 'main.js');
fs.writeFileSync(bundlePath, 'export default {}');
await expect(assertPathUnderRoot(tempRoot, bundlePath)).resolves.toBe(bundlePath);
});
it('rejects paths outside the user data root', async () => {
const outsidePath = path.join(os.tmpdir(), 'outside.txt');
await expect(assertPathUnderRoot(tempRoot, outsidePath, ['server'])).rejects.toThrow('outside allowed app-data paths');
});
it('rejects paths outside allowed subdirectories', async () => {
const pluginsPath = path.join(tempRoot, 'plugins', 'evil.txt');
await expect(assertPathUnderRoot(tempRoot, pluginsPath, ['server'])).rejects.toThrow('outside allowed app-data paths');
});
it('allows user-granted plugin source roots outside app data', async () => {
const externalRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'metoyou-plugin-source-'));
const manifestPath = path.join(externalRoot, 'plugin-source.json');
fs.writeFileSync(manifestPath, '{}');
grantPluginReadRoot(externalRoot);
await expect(resolveReadablePath(manifestPath)).resolves.toBe(manifestPath);
fs.rmSync(externalRoot, { recursive: true, force: true });
});
});

108
electron/path-jail.ts Normal file
View File

@@ -0,0 +1,108 @@
import { app } from 'electron';
import * as fsp from 'fs/promises';
import * as path from 'path';
export const DEFAULT_USER_DATA_SUBDIRS = [
'server',
'direct-messages',
'plugins',
'plugin-bundles',
'plugin-cache',
'themes',
'metoyou'
] as const;
export function isPathInside(parentPath: string, candidatePath: string): boolean {
const relativePath = path.relative(parentPath, candidatePath);
return relativePath === '' || (!relativePath.startsWith('..') && !path.isAbsolute(relativePath));
}
async function realpathOrSelf(filePath: string): Promise<string> {
try {
return await fsp.realpath(filePath);
} catch {
return path.resolve(filePath);
}
}
function normalizeAllowedSubdirs(allowedSubdirs: readonly string[]): string[] {
return allowedSubdirs.map((entry) => entry.replace(/\\/g, '/').replace(/^\/+|\/+$/g, '')).filter(Boolean);
}
export async function assertPathUnderRoot(
rootPath: string,
candidatePath: string,
allowedSubdirs: readonly string[] = DEFAULT_USER_DATA_SUBDIRS
): Promise<string> {
if (typeof candidatePath !== 'string' || !candidatePath.trim()) {
throw new Error('Invalid file path');
}
const [realRoot, realCandidate] = await Promise.all([realpathOrSelf(rootPath), realpathOrSelf(candidatePath)]);
if (!isPathInside(realRoot, realCandidate)) {
throw new Error('Path is outside allowed app-data paths');
}
const relativePath = path.relative(realRoot, realCandidate).replace(/\\/g, '/');
const [topLevelSegment] = relativePath.split('/');
if (!topLevelSegment || !normalizeAllowedSubdirs(allowedSubdirs).includes(topLevelSegment)) {
throw new Error('Path is outside allowed app-data paths');
}
return realCandidate;
}
export async function assertPathUnderUserData(
candidatePath: string,
allowedSubdirs: readonly string[] = DEFAULT_USER_DATA_SUBDIRS
): Promise<string> {
return assertPathUnderRoot(app.getPath('userData'), candidatePath, allowedSubdirs);
}
const grantedPluginReadRoots = new Set<string>();
export function grantPluginReadRoot(rootPath: string): void {
if (typeof rootPath !== 'string' || !rootPath.trim()) {
return;
}
grantedPluginReadRoots.add(path.resolve(rootPath));
}
export function clearGrantedPluginReadRoots(): void {
grantedPluginReadRoots.clear();
}
async function assertPathUnderGrantedPluginRoot(candidatePath: string): Promise<string> {
const realCandidate = await realpathOrSelf(candidatePath);
for (const rootPath of grantedPluginReadRoots) {
const realRoot = await realpathOrSelf(rootPath);
if (isPathInside(realRoot, realCandidate)) {
return realCandidate;
}
}
throw new Error('Path is outside allowed app-data paths');
}
/** Resolves readable paths under app data or user-granted plugin source roots. */
export async function resolveReadablePath(candidatePath: string): Promise<string | null> {
if (typeof candidatePath !== 'string' || !candidatePath.trim()) {
return null;
}
try {
return await assertPathUnderUserData(candidatePath);
} catch {
try {
return await assertPathUnderGrantedPluginRoot(candidatePath);
} catch {
return null;
}
}
}

View File

@@ -1,4 +1,8 @@
import { contextBridge, ipcRenderer, webUtils } from 'electron';
import {
contextBridge,
ipcRenderer,
webUtils
} from 'electron';
import { Command, Query } from './cqrs/types';
const LINUX_SCREEN_SHARE_MONITOR_AUDIO_CHUNK_CHANNEL = 'linux-screen-share-monitor-audio-chunk';
@@ -240,6 +244,21 @@ export interface ElectronAPI {
stopLinuxScreenShareMonitorCapture: (captureId?: string) => Promise<boolean>;
onLinuxScreenShareMonitorAudioChunk: (listener: (payload: LinuxScreenShareMonitorAudioChunkPayload) => void) => () => void;
onLinuxScreenShareMonitorAudioEnded: (listener: (payload: LinuxScreenShareMonitorAudioEndedPayload) => void) => () => void;
getAppMetrics: () => Promise<{
collectedAt: number;
processes: {
pid: number;
type: string;
workingSetKb: number | null;
}[];
}>;
isPerfDiagEnabled: () => Promise<boolean>;
reportPerfDiagSample: (entry: {
collectedAt: number;
source: 'main' | 'renderer';
type: string;
payload: Record<string, unknown>;
}) => Promise<boolean>;
getAppDataPath: () => Promise<string>;
openCurrentDataFolder: () => Promise<boolean>;
exportUserData: () => Promise<ExportUserDataResult>;
@@ -302,9 +321,10 @@ export interface ElectronAPI {
relaunchApp: () => Promise<boolean>;
onDeepLinkReceived: (listener: (url: string) => void) => () => void;
readClipboardFiles: () => Promise<ClipboardFilePayload[]>;
readFile: (filePath: string) => Promise<string>;
readFileChunk: (filePath: string, start: number, end: number) => Promise<string>;
getFileSize: (filePath: string) => Promise<number>;
readFile: (filePath: string) => Promise<string | null>;
readFileChunk: (filePath: string, start: number, end: number) => Promise<string | null>;
getFileSize: (filePath: string) => Promise<number | null>;
grantPluginReadRoot: (rootPath: string) => Promise<boolean>;
writeFile: (filePath: string, data: string) => Promise<boolean>;
appendFile: (filePath: string, data: string) => Promise<boolean>;
saveFileAs: (defaultFileName: string, data: string) => Promise<{ saved: boolean; cancelled: boolean }>;
@@ -326,6 +346,9 @@ export interface ElectronAPI {
command: <T = unknown>(command: Command) => Promise<T>;
query: <T = unknown>(query: Query) => Promise<T>;
storeProvisionSecret: (homeUserId: string, secret: string) => Promise<boolean>;
getProvisionSecret: (homeUserId: string) => Promise<string | null>;
}
const electronAPI: ElectronAPI = {
@@ -374,6 +397,9 @@ const electronAPI: ElectronAPI = {
ipcRenderer.removeListener(LINUX_SCREEN_SHARE_MONITOR_AUDIO_ENDED_CHANNEL, wrappedListener);
};
},
getAppMetrics: () => ipcRenderer.invoke('get-app-metrics'),
isPerfDiagEnabled: () => ipcRenderer.invoke('perf-diag-is-enabled'),
reportPerfDiagSample: (entry) => ipcRenderer.invoke('perf-diag-report', entry),
getAppDataPath: () => ipcRenderer.invoke('get-app-data-path'),
openCurrentDataFolder: () => ipcRenderer.invoke('open-current-data-folder'),
exportUserData: () => ipcRenderer.invoke('export-user-data'),
@@ -438,6 +464,7 @@ const electronAPI: ElectronAPI = {
readFile: (filePath) => ipcRenderer.invoke('read-file', filePath),
readFileChunk: (filePath, start, end) => ipcRenderer.invoke('read-file-chunk', filePath, start, end),
getFileSize: (filePath) => ipcRenderer.invoke('get-file-size', filePath),
grantPluginReadRoot: (rootPath) => ipcRenderer.invoke('grant-plugin-read-root', rootPath),
writeFile: (filePath, data) => ipcRenderer.invoke('write-file', filePath, data),
appendFile: (filePath, data) => ipcRenderer.invoke('append-file', filePath, data),
saveFileAs: (defaultFileName, data) => ipcRenderer.invoke('save-file-as', defaultFileName, data),
@@ -478,7 +505,10 @@ const electronAPI: ElectronAPI = {
},
command: (command) => ipcRenderer.invoke('cqrs:command', command),
query: (query) => ipcRenderer.invoke('cqrs:query', query)
query: (query) => ipcRenderer.invoke('cqrs:query', query),
storeProvisionSecret: (homeUserId, secret) => ipcRenderer.invoke('store-provision-secret', homeUserId, secret),
getProvisionSecret: (homeUserId) => ipcRenderer.invoke('get-provision-secret', homeUserId)
};
contextBridge.exposeInMainWorld('electronAPI', electronAPI);

View File

@@ -1,5 +1,6 @@
import { app, net } from 'electron';
import { autoUpdater } from 'electron-updater';
import { migrateLegacyDesktopBranding } from '../app/desktop-branding-migration';
import { readDesktopSettings, type AutoUpdateMode } from '../desktop-settings';
import { getMainWindow } from '../window/create-window';
import {
@@ -500,7 +501,7 @@ async function performUpdateCheck(
setDesktopUpdateState({
lastCheckedAt: Date.now(),
status: 'checking',
statusMessage: `Checking for MetoYou ${targetRelease.version}...`,
statusMessage: `Checking for Toju ${targetRelease.version}...`,
targetVersion: targetRelease.version
});
@@ -641,7 +642,7 @@ async function refreshDesktopUpdater(
setDesktopUpdateState({
status: 'target-older-than-installed',
statusMessage: `MetoYou ${app.getVersion()} is newer than ${selectedRelease.version}. Downgrades are not applied automatically.`,
statusMessage: `Toju ${app.getVersion()} is newer than ${selectedRelease.version}. Downgrades are not applied automatically.`,
targetVersion: selectedRelease.version
});
@@ -698,7 +699,7 @@ export function initializeDesktopUpdater(): void {
setDesktopUpdateState({
lastCheckedAt: Date.now(),
status: 'downloading',
statusMessage: `Downloading MetoYou ${nextVersion ?? 'update'}...`,
statusMessage: `Downloading Toju ${nextVersion ?? 'update'}...`,
targetVersion: nextVersion
});
});
@@ -715,8 +716,8 @@ export function initializeDesktopUpdater(): void {
lastCheckedAt: Date.now(),
status: 'up-to-date',
statusMessage: isPinnedVersion
? `MetoYou ${desktopUpdateState.targetVersion} is already installed.`
: 'MetoYou is up to date.'
? `Toju ${desktopUpdateState.targetVersion} is already installed.`
: 'Toju is up to date.'
});
});
@@ -726,11 +727,13 @@ export function initializeDesktopUpdater(): void {
const nextVersion = normalizeSemanticVersion(updateInfo.version)
?? desktopUpdateState.targetVersion;
void migrateLegacyDesktopBranding();
setDesktopUpdateState({
lastCheckedAt: Date.now(),
restartRequired: true,
status: 'restart-required',
statusMessage: `MetoYou ${nextVersion ?? 'update'} is ready. Restart the app to finish installing it.`,
statusMessage: `Toju ${nextVersion ?? 'update'} is ready. Restart the app to finish installing it.`,
targetVersion: nextVersion
});
});

View File

@@ -9,6 +9,7 @@ import {
} from 'electron';
import * as fs from 'fs';
import * as path from 'path';
import { DESKTOP_APP_DISPLAY_NAME } from '../app/desktop-branding.rules';
import { readDesktopSettings } from '../desktop-settings';
let mainWindow: BrowserWindow | null = null;
@@ -114,11 +115,11 @@ function ensureTray(): void {
}
tray = new Tray(trayIconPath);
tray.setToolTip('MetoYou');
tray.setToolTip('Toju');
tray.setContextMenu(
Menu.buildFromTemplate([
{
label: 'Open MetoYou',
label: 'Open Toju',
click: () => {
void showMainWindow();
}
@@ -127,7 +128,7 @@ function ensureTray(): void {
type: 'separator'
},
{
label: 'Close MetoYou',
label: 'Close Toju',
click: () => {
requestAppQuit();
}
@@ -200,6 +201,7 @@ export async function createWindow(): Promise<void> {
minWidth: 800,
minHeight: 600,
frame: false,
title: DESKTOP_APP_DISPLAY_NAME,
titleBarStyle: 'hidden',
backgroundColor: '#0a0a0f',
...(windowIconPath ? { icon: windowIconPath } : {}),

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