[GH-ISSUE #6790] [Feature]: Optional secure multiplayer for Conversation, Roleplay, and Game #3800

Closed
opened 2026-10-21 06:07:36 +07:00 by bsakaguchi · 1 comment
Owner

Originally created by @SpicyMarinara on GitHub (Sep 27, 2026).
Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/6790

Originally assigned to: @SpicyMarinara on GitHub.

What problem does this solve?

Let people create Roleplay, Conversation, and Game sessions and play together, each controlling their own persona/player character, with optional AI-controlled characters and/or an AI GM in every mode.

Game mode should use shared rounds: each participating player character states what they do, and the engine waits for all required player actions before resolving the round. With two player characters, submitting the first action must not trigger the GM; submitting the second completes the collection step.

Security is a release requirement in both directions. A guest must not gain access to the host's private Marinara installation. A malicious host must not be able to use multiplayer to deliver executable files, run scripts, install packages, or invoke capabilities on the guest's machine. A password and an encrypted peer connection alone do not establish these boundaries.

Multiplayer must remain completely optional, inaccessible until the user explicitly enables it in both .env and Settings. Prefer the simplest maintainable solution, reuse existing code where its trust assumptions fit, and avoid over-engineering.

Proposed solution

Product scope and session behavior

  • One host owns a private room, its canonical chat/game state, and the AI connections. Guests join with their own participant identity and persona. The implementation must prove a host and one guest, then larger rosters. Per the maintainer’s updated requirement, do not impose a fixed human-participant or AI-character count cap. Preserve bounded request/snapshot sizes, admission queues, connection/concurrency and rate protections, with clear recoverable errors when a room exceeds transport or provider capacity.
  • Support all three existing modes. Conversation and Roleplay share attributed human messages and AI responses. Preserve manual/automatic response controls and configured autonomous messaging through one host-coordinated pipeline, keeping concurrent human posts ordered and preventing duplicate generation.
  • Allow users to contribute characters and select AI-controlled characters or an AI GM in any mode. The host approves additions and controls AI generation/provider settings. Exchange approved, bounded character/persona text fields; do not transfer an entire executable card/package or automatically import into another participant's library.
  • Game rounds collect one submitted action (or an explicit pass) per required player character. Show who is ready and who is still pending. Lock the collected actions when resolution starts, run the AI/GM resolution once for that logical round, and distribute the same committed result to everyone.
  • A disconnect pauses the missing player's readiness; it must not silently submit a move or advance the round. The host can explicitly pause, record a pass, or remove a player, with a visible room event. Roster changes take effect at a defined round boundary. Rejoining restores the participant's existing submission rather than creating another player/action.
  • AI characters and the GM act through the host's existing generation pipeline. They are not additional human readiness slots. Do not silently replace an existing single-player identity with whichever guest posted last.

UI plan: extend the existing Marinara interface

Multiplayer is a sharing capability of Conversation, Roleplay, and Game, not a fourth mode. Keep the existing home launcher, mode chooser, sidebar, chat surfaces, setup wizards, settings drawer, character/persona pickers, and composer. Use the user's local theme/accent and existing components. The guest's trusted client renders the familiar interface from validated room data; the host never supplies the guest UI code, theme CSS, or executable components.

Existing surface Multiplayer addition
Settings, Advanced A compact Multiplayer section: environment availability, explicit Enable multiplayer control, warning, and Join session action
New Chat / existing setup wizard Optional Play together choice, visible only after both opt-ins; keep the same three modes and normal character/GM setup
Chat settings drawer A Multiplayer section with Players, invitations, pending requests, connection status, and Host/Stop/Leave controls
Existing Persona / Characters / Game Party controls Your own player-character selection, normal AI character/GM selection, and clear player/AI ownership labels
Existing chat toolbar A compact Players count/status control that opens the Multiplayer section directly
Existing composer / Game action input The same commands and writing area; Game adds round readiness and Submit action / Edit action / Pass states
Existing sidebar chat rows Small Hosting / Joined / Disconnected indicators; shared sessions stay under their normal mode

Activation and creating a room

When .env disables the feature, Settings may show a read-only explanation of the required change/restart, but there are no usable host/join controls or Play together choices. With the environment gate enabled, the user must separately enable Multiplayer in Settings. This permits room actions; it does not start networking by itself. Keep Start hosting and Join explicit, and never restore an active session automatically after restart.

The host chooses a mode through the normal New Chat flow and chooses Play together in the existing setup. Reuse the current persona, character, AI GM, command, and autonomy controls. Start hosting reviews the room name, room password, and exactly which setup fields will be shared, then opens the room's Players section. No separate social-network lobby, friends directory, or new global navigation system.

For Game, creating the room and starting the adventure are separate actions: invite and approve players before the existing Start game action generates the initial party/world context. Reuse the Game setup Party/GM and Review stages to show the approved human roster plus AI companions; require every participating human to select a player character before Start game. Invitations and readiness can live in the same reusable Players section during setup and play.

Do not make an existing private chat public merely by pressing Invite. The initial UI creates a fresh shared session from explicitly reviewed setup. Any later Share existing chat path must define history/private-state disclosure separately; do not automatically copy old transcripts, hidden notes, or private memories.

Inviting and admitting a person

  1. Host opens Players and selects Invite player. Show Copy invite code and expiry, with controls to revoke/replace the invite. Keep the room password separate from the code. The host shares it through their chosen channel; Marinara does not automatically contact anyone.
  2. Guest opens Join session in their own trusted Marinara client and pastes the code. Never direct them to load application code from the host's website. Joining does not require the guest to configure a model/API key or pass the existing new-chat connection-setup gate.
  3. Before sending persona data, the guest sees the safety warning, expected host identity/fingerprint, room name/mode, and a preview of the specific persona text fields to share. They choose their own persona using the existing picker pattern. Do not send their library, private notes, images, or full card extensions.
  4. Host sees an inline Join request with the guest's display name and requested persona, and selects Approve or Decline. A request does not receive chat history or other participants' data before approval. Review any proposed character fields as part of admission.
  5. Once approved, the session opens in the usual mode's chat surface and appears in the existing sidebar as Joined. Host can revoke an admitted participant separately from revoking unused invitations. Guest always has Leave; host always has Stop hosting.

Use the existing drawer/inline section as the persistent room management surface. Reserve an existing Modal/confirmation pattern for an actual consent or destructive step; avoid nesting a new lobby modal, invitation modal, and persona modal on top of one another.

Players and AI characters must be visibly distinct

Players rows show connection state, display name, the persona they control, and text labels such as You, Host, Connected, Waiting, or Reconnecting. For example: Mari (Host, You) · playing Luna and Alex · playing Rowan. Use safe local/bundled avatar placeholders while peer media transfer is unavailable. Real-player connection state must not be confused with an AI character's fictional availability/status.

Keep Invite player separate from the existing Add character control. The latter selects an AI character using the current library picker, with an AI label and an optional GM role; it does not add a person. Guests can propose an AI character through the same picker pattern, sharing only reviewed text fields for host approval. In Game, show both human-controlled characters and AI companions in the existing Party presentation, with clear ownership.

Reuse the persona picker's presentation, but bind its multiplayer action to the current participant rather than updating the chat's single global personaId. A guest cannot switch someone else's identity, reassign their message history, or take control of an AI/GM. Game persona/roster changes are pending until a safe round boundary. Host-only setup controls remain host-only; guests see a concise explanation such as AI managed by host, never connection secrets or editable host settings.

Game turns and ordinary chat input

Keep the existing Game writing/action area. Add a compact status row above it, for example: Round 4 · 1/2 ready · Waiting for Alex. The submission button is Submit action; after acceptance, show Action submitted and allow Edit action only while the round is still collecting. An explicit Pass counts as that character's submission. Status updates must use labels/icons, not color alone.

When all required actors are ready, show GM resolving round and prevent duplicate submissions/edits. A disconnected participant shows Reconnecting/Waiting, and the host sees Pause/Record pass/Remove actions with confirmation where appropriate. New arrivals join the next defined round boundary. Preserve unsent drafts across temporary disconnects and make retry/closed-room states explicit.

Conversation and Roleplay keep their current composer and slash-command affordances. Commands, autonomous replies, schedules, and AI results appear in the same transcript/status locations as today after room validation. Annotate who acted and explain a restricted command inline. Do not add a parallel multiplayer command console or silently send a room command to the guest's own Engine.

Mobile, accessibility, and states

Use the existing responsive settings drawer rather than introducing an always-open player sidebar. Keep the Players shortcut, readiness strip, Close/Back, and Leave/Stop reachable on narrow screens and with the software keyboard open. Approval, invitation, and removal actions cannot depend on hover. Preserve keyboard focus/return behavior, announce readiness/connection changes appropriately, and respect reduced motion, light/dark modes, and local theme settings.

Specify empty, loading, joining, awaiting approval, declined, expired invite, wrong password, full room, incompatible version, reconnecting, identity-changed, and host-ended states. Each needs a clear recovery or Leave action without requiring an app restart. Warning acknowledgment does not bypass the feature gates or protocol restrictions.

Concrete reuse points: HomeNewChatLauncher, ChatModeSelectorModal, ChatSetupWizard, GameSetupWizard/GameSetupSummary, ChatSidebar, ChatSettingsDrawer, ChatSettingsSection, PickerDropdown, QuickPersonaSwitcher, ChatToolbarControls, ChatInput/ConversationInput, and existing Game action controls. Extract a small reusable Players section if setup and in-chat management need the same content. Reuse audited presentation components while keeping the guest entrypoint free of administrative hooks and native capability registration. Preserve state-based navigation and existing localization conventions.

Compatibility with commands, autonomous messages, and existing features

Commands and autonomous messages are required compatibility work, not optional follow-ups. Preserve the existing features where they apply to each mode; do not turn multiplayer into a separate basic chat implementation.

  • Inventory slash commands, AI-generated Conversation/Roleplay commands, agent/capability commands, group response order, schedules/autonomous intents, scenes, memories/lorebooks, trackers, game choices/dice, and shared state changes. Produce a compact compatibility matrix for each: mode, authorized caller, host execution path, shared/private output, round behavior, and any explicit restriction. Avoid a new generic permissions framework; attach small explicit policies to existing command dispatch where practical.
  • The host validates participant identity, target character ownership, arguments, room scope, and configured capability before calling the existing command implementation. Broadcast the committed result once. The same checks apply to AI-emitted commands and autonomous actions. Never replay an incoming slash-command string or model-produced command directly through the guest's local command executor.
  • Player actions and normal chat commands should remain usable by authorized participants. Host-only administrative/destructive controls, impersonation of another player, private-chat cross-posting, provider changes, and native/device operations require their own restrictions. Enforce these in code and explain unavailable actions in the UI; do not silently ignore them or claim universal compatibility.
  • Reuse the existing autonomous scheduler, candidate/intent logic, schedules, cooldowns, and generation locks. For a shared room, the host must be the single coordinator even if several guest tabs are active. Guest active/background polling must not independently start the same generation. Define room activity from accepted participant events and a room-level clock/timezone; one guest's local idle setting must not suppress or duplicate everyone else's messages.
  • Serialize manual responses, commands, and autonomous triggers through the same room generation authority. In Game mode, any state-advancing trigger waits behind the required-player-action barrier. Defer scheduled state changes while a round is collecting/resolving; do not let a timer submit a human action or bypass readiness. Pause room autonomous work when hosting ends and define the no-connected-player policy explicitly.
  • Preserve command audience boundaries: private notes/whispers and hidden GM state are sent only to authorized recipients, including reconnect/streaming paths. Shared memories/trackers must retain the correct participant attribution. The host can still inspect hosted data; do not promise privacy from the host.
  • Safe structured command results can use trusted, bundled UI. Commands producing images/audio/files may execute on the host where authorized, but the initial guest protocol must not auto-transfer or open their outputs. Clearly show that limitation. Any richer output needed for full command parity must pass a separate receiving-side media/security increment before being advertised as supported. Never obtain command compatibility by loading a host-provided extension, custom game renderer, or script on guests.

Mandatory double opt-in and shutdown

Proposed name: MULTIPLAYER_ENABLED=false in .env.example; absent, invalid, or false means disabled. This variable does not exist yet.

Environment gate User action in Settings Required behavior
Absent/false/invalid Any UI state or direct request Hosting/joining unavailable; multiplayer routes reject requests; no room discovery, signaling registration, or peer session starts
Explicitly true, after restart No activation Ordinary single-player behavior; no active room or peer connection
Explicitly true Enable multiplayer in Settings, without choosing Host or Join Room actions become available; no active room or peer connection
Explicitly true and Settings enabled Explicitly choose Start hosting or Join Start only the chosen operation, after the relevant warnings/authentication
  • Enforce the gate at the host/backend and trusted guest entrypoints, not just by hiding controls. A URL, old saved preference, peer message, or direct API call cannot enable it. Settings cannot rewrite or bypass the environment gate.
  • This applies to both hosting and joining in supported Marinara clients. Treat remote implementations as potentially hostile regardless of their claimed settings.
  • Starting a room remains an explicit action after configuration. Never automatically resume hosting/joining after a process restart. Changing the environment flag takes effect on restart; Settings provides immediate Stop/Disconnect.
  • Stop hosting closes admission and existing sessions, invalidates invites/reconnect credentials, stops new guest-triggered work, and prevents late results from being broadcast to revoked participants. Define safe handling of any already-running generation without corrupting the host's saved chat. Disconnect gives the guest an immediate exit and clears room credentials.
  • Do not relax existing Basic Auth, CSRF, host validation, trusted-origin rules, or local-auth protection to make multiplayer work. No automatic router port forwarding or broad remote-access environment changes.

Security contract: protect the guest from the host

Assume the host can modify their server, forge every packet and filename, lie about MIME types, and deliberately send malicious AI output or character data. Host-side checks cannot protect a guest from that host.

  1. The guest runs trusted client code obtained independently of the host. The baseline is a restricted guest entrypoint from the guest's own trusted Marinara installation. Do not ask the guest to run a host-supplied installer or use a host-served page as the trusted application. A malicious host controls that page's JavaScript and its CSP. Use a separate origin/context without the local administrative UI's credentials or native bridges; prove this separation in the initial spike. A separately maintained official guest site could be considered later, but is not needed for the first release.
  2. First release: bounded structured data and text only across peers. No arbitrary file-transfer operation, automatic downloads, attachments, archives, executables, documents, HTML/SVG payload rendering, peer-provided audio/video/images, or remote asset fetching. Cards/personas travel as a small allowlisted data projection; avatars and backgrounds use bundled/local placeholders. Do not introduce a generic binary channel merely because WebRTC supports one.
  3. Render peer and AI content as inert data on the receiving side. Start with plain text and trusted UI components. Do not reuse rich local chat rendering without auditing it for this boundary. No raw HTML/CSS/JS, scriptable widgets, iframes, remote fonts, link previews, image embeds, automatic navigation, eval, or dynamic module loading from room content. Links may remain plain text initially; any later external-link action needs explicit user interaction and scheme validation.
  4. No remote access to guest capabilities. Room data cannot call the guest's local APIs, shell, filesystem, package installer/updater, custom tools, extensions, browser storage, clipboard, device integrations, Android/native bridge, or browser permissions. The guest entrypoint must not register those capabilities. A room command is never a generic HTTP proxy or local RPC instruction.
  5. Validate on the guest, even for authenticated hosts. Reject unknown message types/fields, oversized or excessively nested data, invalid IDs/revisions, unexpected URLs, and incompatible protocol versions. Bound queues, message rates, transcript/snapshot size, and rendered content. Use a restrictive client-controlled CSP/connection policy as defense in depth and test that room content causes no unexpected network request.
  6. Future media is a separate security-reviewed increment. If added, define a narrow type allowlist, receiving-side byte/type/size/dimension checks, safe decoding/isolation, and explicit sharing controls. File extensions, claimed MIME types, host-side re-encoding, or a malware scanner are not sufficient evidence of safety against a malicious host. Do not claim that scanning makes arbitrary files safe. OWASP file-upload guidance

The enforceable claim is that the supported multiplayer client provides no peer-controlled executable/file-transfer/native-action path. Do not promise absolute immunity to every browser/OS vulnerability or to files a user independently downloads outside Marinara. Keep the security goal strict, document residual risks honestly, and do not use a warning checkbox to bypass the above restrictions.

Security contract: protect the host and other participants

  • Use a room password separate from host/admin credentials, securely stored/verified with established primitives, rate-limited admission, host approval, and random expiring participant sessions. Support kick/revoke, room closure, and reconnect without exposing a reusable host secret. Never place passwords in URLs or logs.
  • Bind each authenticated session to its participant, room, persona/player-character ownership, and allowed actions. Derive identity on the host; do not trust a client-supplied role or participant ID. Check every read, mutation, asset access, and generation request. Deny all capabilities unless explicitly granted. OWASP authorization guidance
  • Build a small explicit multiplayer protocol/API. It must not expose or proxy the ordinary administrative API. In particular, forwarding a guest action through the host browser/localhost must never turn it into a trusted local/admin request.
  • Send only an explicit room/public-state projection. Exclude API keys, private chats, unrelated cards/lorebooks, private GM notes, hidden reasoning, full debug prompts/logs, paths, configuration, and tool definitions. Reconnect snapshots, streaming events, and error messages obey the same projection rules.
  • Treat all peer content and model output as untrusted for tool execution. Room AI capabilities must be explicitly allowlisted and enforced in code; no shell/filesystem/package/network-fetch capability inherited from the host's normal assistant. Prompt instructions alone are not authorization. Preserve verbatim prompt text where appropriate while validating imports and separating rendering/tool boundaries.
  • Keep AI/provider credentials on the host. Bound guest generation frequency, context/action size, and concurrency; provide host-controlled usage limits and a stop action. Avoid sending full private cards when a public display field is sufficient.

Connection model and minimal architecture

  • Prefer one host with guests connected to it. The host validates actions, persists state, and broadcasts permitted state; guests never directly write storage. No peer mesh, federation, distributed database, CRDT framework, host migration, global account system, or public matchmaking for this release.
  • Evaluate WebRTC data channels as the preferred P2P transport in a bounded feasibility spike. P2P still needs authenticated connection setup and may need TURN relay support. Authenticate the room/host binding; encryption by itself does not establish whose room the guest joined. Direct connections can expose peer IP addresses. WebRTC setup, WebRTC security and IP privacy
  • Select one transport after proving trusted-client delivery, authentication, connectivity, disconnects, and mobile behavior. If an authenticated encrypted room-only WebSocket endpoint proves simpler to secure and maintain, document that choice before implementation. Do not build both transports or invent a generic networking framework. Do not expose the normal Engine API as a shortcut.
  • Do not invent cryptography. Reuse maintained platform/library primitives and document any genuinely necessary dependency. Keep signaling/relay responsibilities and credentials narrow; disclose metadata visibility and any operational cost. No unverified anonymity or end-to-end privacy claims against the host/model provider.
  • Reuse current chat storage, identity snapshots, game state/versioning, generation orchestration/locking, UI primitives, localization, and test infrastructure where appropriate. Add the minimum participant/round metadata and room projection needed. Scope multiplayer behavior to participating chats so normal single-player operation stays unchanged.
  • Use simple versioned events, a monotonic room revision, and a filtered snapshot on reconnect. Bounded live streaming can feed existing presentation components after validation. Stale/duplicate actions must not apply twice; do not add a durable event-sourcing subsystem without demonstrated need.
  • If a browser tab is the host's P2P endpoint, document its foreground/lifetime limitations. Tab suspension or closure must pause/disconnect predictably. Do not promise background hosting on iOS without physical-device proof.

Implementation phases and deliverables

1. Threat model and narrow proof of feasibility

Document host, guest, signaling/relay, AI provider, guest browser/native shell, and local Engine trust boundaries. Inventory dangerous renderers, imports, native bridges, privileged routes, and tool dispatch. Prove an independently trusted guest receiving inert text from a deliberately malicious host with no local capability access. Select one transport and concrete guest isolation arrangement. Record protocol limits and supported initial platforms. Do not start with a full multiplayer UI.

2. Opt-in, admission, and restricted room protocol

Implement the environment gate and Settings activation with fail-closed defaults, password/approval/session handling, participant ownership, narrow message schemas, output projection, Stop/Kick/Disconnect, and local logs that omit credentials/private content. Integrate existing auth protections rather than globally bypassing them. Add isolated regressions proving disabled and unauthorized paths before enabling admission.

3. Shared Conversation and Roleplay

Add create/join room, participant list, persona selection, attributed messages, approved AI characters/GM, host-coordinated response generation, validated streaming, and reconnect snapshots. Integrate the compatibility matrix, existing command dispatch, and a single room autonomous scheduler in this phase. Reuse safe chat layout/state logic with the restricted renderer. Make participant identities explicit in prompts and history; define multi-user macro behavior instead of overwriting the existing chat persona. Preserve existing single-player macro/identity behavior. No peer file imports or rich remote presentation.

4. Game round coordination

Add the smallest persisted round record: round ID/revision, required actor roster, submitted actions/pass state, and collecting/resolving/completed status. Reuse the existing generation lock and game-state write ordering. Atomically close collection only after all required actors are ready, resolve using attributed actions plus participant context, and commit one logical result. Reject stale/duplicate submissions and edits after resolution starts. Handle disconnect, host-approved roster changes, failure, cancellation, and restart recovery explicitly; never silently retry an ambiguous paid generation or double-apply world state.

5. Warnings, security verification, docs, and staged delivery

Add localized enable/join warnings, persistent hosting/guest indicators, clear participant/ready state, accessible controls, mobile layouts, and easy Stop/Leave actions. Complete the negative security matrix below and obtain focused security review before shipping. Deliver small issue-linked PRs against staging; keep each incomplete increment disabled. All three modes and the mandatory boundaries are required before calling this feature complete.

Update .env.example, Settings help, README.md, android/README.md, CONTRIBUTING.md, CHANGELOG.md, and configuration/troubleshooting/FAQ docs as applicable. Update translated docs or file the required [docs-i18n] follow-up. Review the current local-single-user threat-model documentation explicitly; do not silently change prompt escaping to compensate for a new multiplayer boundary. Package-owned agent changes, if needed, belong in Marinara-Agents with linked work; Engine owns this feature's host integration.

Before activation and before joining a new host, clearly say:

Only connect to people you trust. Use your own trusted Marinara client; never install a host-provided client, extension, or required file. The host can read and retain what you share, and shared content may be sent to their configured AI providers. Direct peer connections may reveal your IP address. Do not share passwords, API keys, or sensitive personal information. Leave immediately if anything seems suspicious.

Explain that protection is limited to the supported client's controls and is not a guarantee that an unknown host or external download is safe. Show the host identity/fingerprint and room name in trusted UI separately from peer-controlled text, disclose whether the connection is direct or relayed, and require fresh consent after a host identity change. Host warnings should explain guest-content risks and generation usage. All new UI copy uses semantic English localization keys; community locales may fall back to English.

Acceptance and regression plan

These are required future checks, not claims that implementation or testing has happened:

  • Absent/false/invalid environment gate plus forged requests, saved UI preferences, deep links, and remote messages cannot activate multiplayer. With the flag true but Settings inactive, there are no active peer/signaling sessions. Test host and supported guest entrypoints.
  • Restart never automatically hosts/joins; Stop/Kick/Disconnect revoke the appropriate sessions, reject later/replayed actions, and prevent stale reconnect or late event delivery.
  • Host and guest can complete a session in each of Conversation, Roleplay, and Game with distinct personas and approved AI-controlled characters/GM.
  • Reuse the existing three-mode setup, chat surfaces, sidebar, settings drawer, pickers, and composer. Players/AI controls are clearly distinct; the guest joins without configuring an AI connection. A private chat/history is never published by an Invite action.
  • Test host invitation, guest warning/persona-field review, host approval/decline, expired/revoked invitations, guest Leave, host Stop/Kick, and identity-change consent on desktop and mobile. No room/history data reaches unapproved guests and no guest code is loaded from the host.
  • Verify participant-specific persona switching, Game lobby/party setup before initial generation, readable readiness/round controls, preserved disconnect drafts, and recovery states. Keyboard/focus, touch targets, software-keyboard layouts, light/dark themes, and localized labels remain usable.
  • Publish and verify the command/feature compatibility matrix. Authorized player commands, AI-emitted commands, group replies, and configured autonomous/scheduled messages work through existing host services with correct identity, scope, and recipient visibility. Restricted commands have an explicit explanation.
  • Multiple guest tabs, simultaneous timer/manual triggers, host and client scheduler overlap, reconnects, and retries do not duplicate autonomous messages, command effects, or AI generations. Guests never execute received command text locally. Game commands/autonomous triggers cannot bypass the player-action barrier; stopping hosting stops room autonomous work.
  • With two player characters, the first action does not resolve the Game round; the second produces one logical resolution. Explicit passes, duplicates, stale actions, simultaneous submissions, reconnects, disconnects, roster changes, cancellation, and failed/restarted generation preserve consistent state.
  • A hostile guest cannot impersonate another player, cross room boundaries, read private data, access administrative routes, turn a forwarded request into localhost privilege, or run unapproved AI tools.
  • A hostile host sending scripts, event handlers, encoded HTML, SVG, CSS URLs, iframes, dangerous URL schemes, forged download/import/update/native-action messages, disguised files, and unknown protocol fields causes no execution, download, installation, native bridge call, local API request, or external asset fetch on the trusted guest.
  • Repeat injection checks through names, cards, descriptions, AI replies, errors, history/reconnect snapshots, and incremental streaming fragments. Validate peer data on both receiving sides; host-provided safety flags/MIME claims are ignored.
  • Oversized, deeply nested, flooded, malformed, replayed, and incompatible-version traffic is rejected or disconnected within bounded CPU/memory/queue behavior. Wrong-password/join floods are rate-limited.
  • Network inspection proves credentials and private prompt/debug/GM fields are absent from shared events and snapshots; the guest renderer cannot load peer-supplied code/assets or use local/native capabilities.
  • Existing single-player chats, identity/macros, saving, and game progression remain compatible with multiplayer disabled; any data-format change follows storage version/migration rules.
  • Run pnpm check, pnpm localization:check, relevant Node/security regressions, pnpm regression:prompt, pnpm smoke:ui, and focused multi-client Playwright cases on desktop Chromium, mobile Chromium, and mobile WebKit. Use existing regression conventions; do not retain temporary .test.ts files.
  • Manually verify supported physical iPhone/iPad Home Screen and Android guest paths, host-tab suspension, connection loss/rejoin, warnings, and Stop/Leave. Unsupported platforms remain explicitly disabled. Complete local CodeRabbit, focused security review, and required CI before staging merges; record limitations and untested cases.

Alternatives considered

  • Let guests open the host's current Marinara web UI: fails the malicious-host client-code boundary and exposes too much existing application surface. Do not use it as the guest security model.
  • P2P plus a shared password only: protects part of admission/transport, but does not constrain scripts, downloads, local capabilities, authorization, or malicious authenticated peers.
  • Allow arbitrary files and scan for viruses: substantially expands the attack surface and cannot prove every file safe. Start without peer file transfer; evaluate narrow media support separately.
  • Fork the whole engine or build a generic multiplayer platform: duplicates maintenance and adds unnecessary scope. Reuse Engine services and safe UI pieces behind a small explicit room boundary.
  • Distributed state, federation, automatic host migration, many roles, public lobbies, voice/video, and an account platform: defer; none is necessary to prove small private shared sessions in all three modes.

Additional context

Requested by maintainer @SpicyMarinara. This issue is an implementation plan/feature request, not a claim that the feature exists or that its security has been verified. Implementation is not started or assigned by this ticket.

Related earlier suggestion: #5781, closed with an invitation to reopen/recreate when the maintainer approves the direction. This request provides the current three-mode scope, Game round behavior, explicit double opt-in, and security boundaries in both directions. No matching open multiplayer PR or local multiplayer branch was found during preparation.

Code inspection at 0eac28284c80190c19dfd568d4f6933aa027a0e6 suggests these reuse/audit points; they are starting points, not blanket approval to expose existing code to peers:

  • packages/shared/src/types/chat.ts and types/game.ts: current chat persona and message identity snapshots; game setup/party model.
  • packages/server/src/services/chat-user-identity.ts, services/generation/identity-context-runtime.ts, services/prompt/assembler.ts, services/prompt/macro-context.ts: explicit multi-participant identity and prompt semantics.
  • packages/server/src/routes/generate.routes.ts: existing per-chat generation guard and SSE output; filter room-safe events rather than exposing raw internal events.
  • packages/server/src/services/conversation/{autonomous.service,autonomous-candidates,server-autonomous-scheduler.service,schedule.service}.ts, services/generation/{conversation-command-runtime,roleplay-commands}.ts, and services/capability-packages/capability-command-registry.service.ts: reuse command/scheduling behavior with room scope and single-coordinator guarantees.
  • packages/client/src/lib/slash-commands.ts and hooks/{use-autonomous-messaging,use-background-autonomous,use-roleplay-commands}.ts: route authorized room actions through the host instead of duplicating local execution/polling on guests.
  • packages/server/src/services/storage/chats.storage.ts, game-state.storage.ts, game-engine-state.storage.ts, and db/schema/chats.ts: persisted chat/game state and write ordering.
  • packages/server/src/config/runtime-config.ts and middleware/{basic-auth,privileged-gate,csrf-protection,host-validation,android-local-auth}.ts: environment enforcement and authorization boundaries. privileged-gate.ts currently includes a localhost trust path that must not apply to forwarded peer actions.
  • packages/client/src/lib/chat-html.ts, components/chat/ChatMessage.tsx, chat surfaces, game stores, and hooks/use-generate.ts: reuse candidates requiring a multiplayer-specific audit. Existing HTML sanitization still permits rich markup and image sources; it is not the proposed text-only guest renderer.
  • CONTRIBUTING.md explicitly describes the existing local/single-user prompt-content threat model. Multiplayer changes that deployment assumption; preserve existing prompt-leaf semantics and enforce import, rendering, and tool boundaries deliberately.

Security references: WebRTC trust model, OWASP safe DOM output. These inform the plan; they do not certify an implementation.

Template check

Please uncheck (untick) the box below before submitting so we know you read the template. It is intentionally pre-checked:

  • I DID NOT read this template and provide the requested details.
Originally created by @SpicyMarinara on GitHub (Sep 27, 2026). Original GitHub issue: https://github.com/Pasta-Devs/Marinara-Engine/issues/6790 Originally assigned to: @SpicyMarinara on GitHub. ## What problem does this solve? Let people create **Roleplay, Conversation, and Game sessions and play together**, each controlling their own persona/player character, with optional AI-controlled characters and/or an AI GM in every mode. Game mode should use shared rounds: each participating player character states what they do, and the engine waits for all required player actions before resolving the round. With two player characters, submitting the first action must not trigger the GM; submitting the second completes the collection step. **Security is a release requirement in both directions.** A guest must not gain access to the host's private Marinara installation. A malicious host must not be able to use multiplayer to deliver executable files, run scripts, install packages, or invoke capabilities on the guest's machine. A password and an encrypted peer connection alone do not establish these boundaries. Multiplayer must remain completely optional, inaccessible until the user explicitly enables it in both `.env` and Settings. Prefer the simplest maintainable solution, reuse existing code where its trust assumptions fit, and avoid over-engineering. ## Proposed solution ### Product scope and session behavior - One host owns a private room, its canonical chat/game state, and the AI connections. Guests join with their own participant identity and persona. The implementation must prove a host and one guest, then larger rosters. Per the maintainer’s updated requirement, do not impose a fixed human-participant or AI-character count cap. Preserve bounded request/snapshot sizes, admission queues, connection/concurrency and rate protections, with clear recoverable errors when a room exceeds transport or provider capacity. - Support all three existing modes. Conversation and Roleplay share attributed human messages and AI responses. Preserve manual/automatic response controls and configured autonomous messaging through one host-coordinated pipeline, keeping concurrent human posts ordered and preventing duplicate generation. - Allow users to contribute characters and select AI-controlled characters or an AI GM in any mode. The host approves additions and controls AI generation/provider settings. Exchange approved, bounded character/persona text fields; do not transfer an entire executable card/package or automatically import into another participant's library. - Game rounds collect one submitted action (or an explicit pass) per required player character. Show who is ready and who is still pending. Lock the collected actions when resolution starts, run the AI/GM resolution once for that logical round, and distribute the same committed result to everyone. - A disconnect pauses the missing player's readiness; it must not silently submit a move or advance the round. The host can explicitly pause, record a pass, or remove a player, with a visible room event. Roster changes take effect at a defined round boundary. Rejoining restores the participant's existing submission rather than creating another player/action. - AI characters and the GM act through the host's existing generation pipeline. They are not additional human readiness slots. Do not silently replace an existing single-player identity with whichever guest posted last. ### UI plan: extend the existing Marinara interface Multiplayer is a sharing capability of Conversation, Roleplay, and Game, not a fourth mode. Keep the existing home launcher, mode chooser, sidebar, chat surfaces, setup wizards, settings drawer, character/persona pickers, and composer. Use the user's local theme/accent and existing components. The guest's trusted client renders the familiar interface from validated room data; the host never supplies the guest UI code, theme CSS, or executable components. | Existing surface | Multiplayer addition | | --- | --- | | Settings, Advanced | A compact Multiplayer section: environment availability, explicit Enable multiplayer control, warning, and Join session action | | New Chat / existing setup wizard | Optional Play together choice, visible only after both opt-ins; keep the same three modes and normal character/GM setup | | Chat settings drawer | A Multiplayer section with Players, invitations, pending requests, connection status, and Host/Stop/Leave controls | | Existing Persona / Characters / Game Party controls | Your own player-character selection, normal AI character/GM selection, and clear player/AI ownership labels | | Existing chat toolbar | A compact Players count/status control that opens the Multiplayer section directly | | Existing composer / Game action input | The same commands and writing area; Game adds round readiness and Submit action / Edit action / Pass states | | Existing sidebar chat rows | Small Hosting / Joined / Disconnected indicators; shared sessions stay under their normal mode | **Activation and creating a room** When `.env` disables the feature, Settings may show a read-only explanation of the required change/restart, but there are no usable host/join controls or Play together choices. With the environment gate enabled, the user must separately enable Multiplayer in Settings. This permits room actions; it does not start networking by itself. Keep Start hosting and Join explicit, and never restore an active session automatically after restart. The host chooses a mode through the normal New Chat flow and chooses Play together in the existing setup. Reuse the current persona, character, AI GM, command, and autonomy controls. Start hosting reviews the room name, room password, and exactly which setup fields will be shared, then opens the room's Players section. No separate social-network lobby, friends directory, or new global navigation system. For Game, creating the room and starting the adventure are separate actions: invite and approve players before the existing Start game action generates the initial party/world context. Reuse the Game setup Party/GM and Review stages to show the approved human roster plus AI companions; require every participating human to select a player character before Start game. Invitations and readiness can live in the same reusable Players section during setup and play. Do not make an existing private chat public merely by pressing Invite. The initial UI creates a fresh shared session from explicitly reviewed setup. Any later Share existing chat path must define history/private-state disclosure separately; do not automatically copy old transcripts, hidden notes, or private memories. **Inviting and admitting a person** 1. Host opens Players and selects **Invite player**. Show **Copy invite code** and expiry, with controls to revoke/replace the invite. Keep the room password separate from the code. The host shares it through their chosen channel; Marinara does not automatically contact anyone. 2. Guest opens **Join session in their own trusted Marinara client** and pastes the code. Never direct them to load application code from the host's website. Joining does not require the guest to configure a model/API key or pass the existing new-chat connection-setup gate. 3. Before sending persona data, the guest sees the safety warning, expected host identity/fingerprint, room name/mode, and a preview of the specific persona text fields to share. They choose their own persona using the existing picker pattern. Do not send their library, private notes, images, or full card extensions. 4. Host sees an inline **Join request** with the guest's display name and requested persona, and selects Approve or Decline. A request does not receive chat history or other participants' data before approval. Review any proposed character fields as part of admission. 5. Once approved, the session opens in the usual mode's chat surface and appears in the existing sidebar as Joined. Host can revoke an admitted participant separately from revoking unused invitations. Guest always has Leave; host always has Stop hosting. Use the existing drawer/inline section as the persistent room management surface. Reserve an existing `Modal`/confirmation pattern for an actual consent or destructive step; avoid nesting a new lobby modal, invitation modal, and persona modal on top of one another. **Players and AI characters must be visibly distinct** Players rows show connection state, display name, the persona they control, and text labels such as You, Host, Connected, Waiting, or Reconnecting. For example: `Mari (Host, You) · playing Luna` and `Alex · playing Rowan`. Use safe local/bundled avatar placeholders while peer media transfer is unavailable. Real-player connection state must not be confused with an AI character's fictional availability/status. Keep **Invite player** separate from the existing **Add character** control. The latter selects an AI character using the current library picker, with an AI label and an optional GM role; it does not add a person. Guests can propose an AI character through the same picker pattern, sharing only reviewed text fields for host approval. In Game, show both human-controlled characters and AI companions in the existing Party presentation, with clear ownership. Reuse the persona picker's presentation, but bind its multiplayer action to the current participant rather than updating the chat's single global `personaId`. A guest cannot switch someone else's identity, reassign their message history, or take control of an AI/GM. Game persona/roster changes are pending until a safe round boundary. Host-only setup controls remain host-only; guests see a concise explanation such as AI managed by host, never connection secrets or editable host settings. **Game turns and ordinary chat input** Keep the existing Game writing/action area. Add a compact status row above it, for example: `Round 4 · 1/2 ready · Waiting for Alex`. The submission button is **Submit action**; after acceptance, show **Action submitted** and allow **Edit action** only while the round is still collecting. An explicit **Pass** counts as that character's submission. Status updates must use labels/icons, not color alone. When all required actors are ready, show **GM resolving round** and prevent duplicate submissions/edits. A disconnected participant shows Reconnecting/Waiting, and the host sees Pause/Record pass/Remove actions with confirmation where appropriate. New arrivals join the next defined round boundary. Preserve unsent drafts across temporary disconnects and make retry/closed-room states explicit. Conversation and Roleplay keep their current composer and slash-command affordances. Commands, autonomous replies, schedules, and AI results appear in the same transcript/status locations as today after room validation. Annotate who acted and explain a restricted command inline. Do not add a parallel multiplayer command console or silently send a room command to the guest's own Engine. **Mobile, accessibility, and states** Use the existing responsive settings drawer rather than introducing an always-open player sidebar. Keep the Players shortcut, readiness strip, Close/Back, and Leave/Stop reachable on narrow screens and with the software keyboard open. Approval, invitation, and removal actions cannot depend on hover. Preserve keyboard focus/return behavior, announce readiness/connection changes appropriately, and respect reduced motion, light/dark modes, and local theme settings. Specify empty, loading, joining, awaiting approval, declined, expired invite, wrong password, full room, incompatible version, reconnecting, identity-changed, and host-ended states. Each needs a clear recovery or Leave action without requiring an app restart. Warning acknowledgment does not bypass the feature gates or protocol restrictions. **Concrete reuse points:** `HomeNewChatLauncher`, `ChatModeSelectorModal`, `ChatSetupWizard`, `GameSetupWizard`/`GameSetupSummary`, `ChatSidebar`, `ChatSettingsDrawer`, `ChatSettingsSection`, `PickerDropdown`, `QuickPersonaSwitcher`, `ChatToolbarControls`, `ChatInput`/`ConversationInput`, and existing Game action controls. Extract a small reusable Players section if setup and in-chat management need the same content. Reuse audited presentation components while keeping the guest entrypoint free of administrative hooks and native capability registration. Preserve state-based navigation and existing localization conventions. ### Compatibility with commands, autonomous messages, and existing features **Commands and autonomous messages are required compatibility work, not optional follow-ups.** Preserve the existing features where they apply to each mode; do not turn multiplayer into a separate basic chat implementation. - Inventory slash commands, AI-generated Conversation/Roleplay commands, agent/capability commands, group response order, schedules/autonomous intents, scenes, memories/lorebooks, trackers, game choices/dice, and shared state changes. Produce a compact compatibility matrix for each: mode, authorized caller, host execution path, shared/private output, round behavior, and any explicit restriction. Avoid a new generic permissions framework; attach small explicit policies to existing command dispatch where practical. - The host validates participant identity, target character ownership, arguments, room scope, and configured capability before calling the existing command implementation. Broadcast the committed result once. The same checks apply to AI-emitted commands and autonomous actions. Never replay an incoming slash-command string or model-produced command directly through the guest's local command executor. - Player actions and normal chat commands should remain usable by authorized participants. Host-only administrative/destructive controls, impersonation of another player, private-chat cross-posting, provider changes, and native/device operations require their own restrictions. Enforce these in code and explain unavailable actions in the UI; do not silently ignore them or claim universal compatibility. - Reuse the existing autonomous scheduler, candidate/intent logic, schedules, cooldowns, and generation locks. For a shared room, the host must be the single coordinator even if several guest tabs are active. Guest active/background polling must not independently start the same generation. Define room activity from accepted participant events and a room-level clock/timezone; one guest's local idle setting must not suppress or duplicate everyone else's messages. - Serialize manual responses, commands, and autonomous triggers through the same room generation authority. In Game mode, any state-advancing trigger waits behind the required-player-action barrier. Defer scheduled state changes while a round is collecting/resolving; do not let a timer submit a human action or bypass readiness. Pause room autonomous work when hosting ends and define the no-connected-player policy explicitly. - Preserve command audience boundaries: private notes/whispers and hidden GM state are sent only to authorized recipients, including reconnect/streaming paths. Shared memories/trackers must retain the correct participant attribution. The host can still inspect hosted data; do not promise privacy from the host. - Safe structured command results can use trusted, bundled UI. Commands producing images/audio/files may execute on the host where authorized, but the initial guest protocol must not auto-transfer or open their outputs. Clearly show that limitation. Any richer output needed for full command parity must pass a separate receiving-side media/security increment before being advertised as supported. Never obtain command compatibility by loading a host-provided extension, custom game renderer, or script on guests. ### Mandatory double opt-in and shutdown Proposed name: `MULTIPLAYER_ENABLED=false` in `.env.example`; absent, invalid, or false means disabled. This variable does not exist yet. | Environment gate | User action in Settings | Required behavior | | --- | --- | --- | | Absent/false/invalid | Any UI state or direct request | Hosting/joining unavailable; multiplayer routes reject requests; no room discovery, signaling registration, or peer session starts | | Explicitly true, after restart | No activation | Ordinary single-player behavior; no active room or peer connection | | Explicitly true | Enable multiplayer in Settings, without choosing Host or Join | Room actions become available; no active room or peer connection | | Explicitly true and Settings enabled | Explicitly choose Start hosting or Join | Start only the chosen operation, after the relevant warnings/authentication | - Enforce the gate at the host/backend and trusted guest entrypoints, not just by hiding controls. A URL, old saved preference, peer message, or direct API call cannot enable it. Settings cannot rewrite or bypass the environment gate. - This applies to both hosting and joining in supported Marinara clients. Treat remote implementations as potentially hostile regardless of their claimed settings. - Starting a room remains an explicit action after configuration. Never automatically resume hosting/joining after a process restart. Changing the environment flag takes effect on restart; Settings provides immediate Stop/Disconnect. - Stop hosting closes admission and existing sessions, invalidates invites/reconnect credentials, stops new guest-triggered work, and prevents late results from being broadcast to revoked participants. Define safe handling of any already-running generation without corrupting the host's saved chat. Disconnect gives the guest an immediate exit and clears room credentials. - Do not relax existing Basic Auth, CSRF, host validation, trusted-origin rules, or local-auth protection to make multiplayer work. No automatic router port forwarding or broad remote-access environment changes. ### Security contract: protect the guest from the host Assume the host can modify their server, forge every packet and filename, lie about MIME types, and deliberately send malicious AI output or character data. Host-side checks cannot protect a guest from that host. 1. **The guest runs trusted client code obtained independently of the host.** The baseline is a restricted guest entrypoint from the guest's own trusted Marinara installation. Do not ask the guest to run a host-supplied installer or use a host-served page as the trusted application. A malicious host controls that page's JavaScript and its CSP. Use a separate origin/context without the local administrative UI's credentials or native bridges; prove this separation in the initial spike. A separately maintained official guest site could be considered later, but is not needed for the first release. 2. **First release: bounded structured data and text only across peers.** No arbitrary file-transfer operation, automatic downloads, attachments, archives, executables, documents, HTML/SVG payload rendering, peer-provided audio/video/images, or remote asset fetching. Cards/personas travel as a small allowlisted data projection; avatars and backgrounds use bundled/local placeholders. Do not introduce a generic binary channel merely because WebRTC supports one. 3. **Render peer and AI content as inert data on the receiving side.** Start with plain text and trusted UI components. Do not reuse rich local chat rendering without auditing it for this boundary. No raw HTML/CSS/JS, scriptable widgets, iframes, remote fonts, link previews, image embeds, automatic navigation, `eval`, or dynamic module loading from room content. Links may remain plain text initially; any later external-link action needs explicit user interaction and scheme validation. 4. **No remote access to guest capabilities.** Room data cannot call the guest's local APIs, shell, filesystem, package installer/updater, custom tools, extensions, browser storage, clipboard, device integrations, Android/native bridge, or browser permissions. The guest entrypoint must not register those capabilities. A room command is never a generic HTTP proxy or local RPC instruction. 5. **Validate on the guest, even for authenticated hosts.** Reject unknown message types/fields, oversized or excessively nested data, invalid IDs/revisions, unexpected URLs, and incompatible protocol versions. Bound queues, message rates, transcript/snapshot size, and rendered content. Use a restrictive client-controlled CSP/connection policy as defense in depth and test that room content causes no unexpected network request. 6. **Future media is a separate security-reviewed increment.** If added, define a narrow type allowlist, receiving-side byte/type/size/dimension checks, safe decoding/isolation, and explicit sharing controls. File extensions, claimed MIME types, host-side re-encoding, or a malware scanner are not sufficient evidence of safety against a malicious host. Do not claim that scanning makes arbitrary files safe. [OWASP file-upload guidance](https://cheatsheetseries.owasp.org/cheatsheets/File_Upload_Cheat_Sheet.html) The enforceable claim is that the supported multiplayer client provides no peer-controlled executable/file-transfer/native-action path. **Do not promise absolute immunity to every browser/OS vulnerability or to files a user independently downloads outside Marinara.** Keep the security goal strict, document residual risks honestly, and do not use a warning checkbox to bypass the above restrictions. ### Security contract: protect the host and other participants - Use a room password separate from host/admin credentials, securely stored/verified with established primitives, rate-limited admission, host approval, and random expiring participant sessions. Support kick/revoke, room closure, and reconnect without exposing a reusable host secret. Never place passwords in URLs or logs. - Bind each authenticated session to its participant, room, persona/player-character ownership, and allowed actions. Derive identity on the host; do not trust a client-supplied role or participant ID. Check every read, mutation, asset access, and generation request. Deny all capabilities unless explicitly granted. [OWASP authorization guidance](https://cheatsheetseries.owasp.org/cheatsheets/Authorization_Cheat_Sheet.html) - Build a small explicit multiplayer protocol/API. It must not expose or proxy the ordinary administrative API. In particular, forwarding a guest action through the host browser/localhost must never turn it into a trusted local/admin request. - Send only an explicit room/public-state projection. Exclude API keys, private chats, unrelated cards/lorebooks, private GM notes, hidden reasoning, full debug prompts/logs, paths, configuration, and tool definitions. Reconnect snapshots, streaming events, and error messages obey the same projection rules. - Treat all peer content and model output as untrusted for tool execution. Room AI capabilities must be explicitly allowlisted and enforced in code; no shell/filesystem/package/network-fetch capability inherited from the host's normal assistant. Prompt instructions alone are not authorization. Preserve verbatim prompt text where appropriate while validating imports and separating rendering/tool boundaries. - Keep AI/provider credentials on the host. Bound guest generation frequency, context/action size, and concurrency; provide host-controlled usage limits and a stop action. Avoid sending full private cards when a public display field is sufficient. ### Connection model and minimal architecture - Prefer one host with guests connected to it. The host validates actions, persists state, and broadcasts permitted state; guests never directly write storage. No peer mesh, federation, distributed database, CRDT framework, host migration, global account system, or public matchmaking for this release. - Evaluate WebRTC data channels as the preferred P2P transport in a bounded feasibility spike. P2P still needs authenticated connection setup and may need TURN relay support. Authenticate the room/host binding; encryption by itself does not establish whose room the guest joined. Direct connections can expose peer IP addresses. [WebRTC setup](https://webrtc.org/getting-started/peer-connections), [WebRTC security and IP privacy](https://www.rfc-editor.org/rfc/rfc8827.html) - Select **one** transport after proving trusted-client delivery, authentication, connectivity, disconnects, and mobile behavior. If an authenticated encrypted room-only WebSocket endpoint proves simpler to secure and maintain, document that choice before implementation. Do not build both transports or invent a generic networking framework. Do not expose the normal Engine API as a shortcut. - Do not invent cryptography. Reuse maintained platform/library primitives and document any genuinely necessary dependency. Keep signaling/relay responsibilities and credentials narrow; disclose metadata visibility and any operational cost. No unverified anonymity or end-to-end privacy claims against the host/model provider. - Reuse current chat storage, identity snapshots, game state/versioning, generation orchestration/locking, UI primitives, localization, and test infrastructure where appropriate. Add the minimum participant/round metadata and room projection needed. Scope multiplayer behavior to participating chats so normal single-player operation stays unchanged. - Use simple versioned events, a monotonic room revision, and a filtered snapshot on reconnect. Bounded live streaming can feed existing presentation components after validation. Stale/duplicate actions must not apply twice; do not add a durable event-sourcing subsystem without demonstrated need. - If a browser tab is the host's P2P endpoint, document its foreground/lifetime limitations. Tab suspension or closure must pause/disconnect predictably. Do not promise background hosting on iOS without physical-device proof. ### Implementation phases and deliverables **1. Threat model and narrow proof of feasibility** Document host, guest, signaling/relay, AI provider, guest browser/native shell, and local Engine trust boundaries. Inventory dangerous renderers, imports, native bridges, privileged routes, and tool dispatch. Prove an independently trusted guest receiving inert text from a deliberately malicious host with no local capability access. Select one transport and concrete guest isolation arrangement. Record protocol limits and supported initial platforms. Do not start with a full multiplayer UI. **2. Opt-in, admission, and restricted room protocol** Implement the environment gate and Settings activation with fail-closed defaults, password/approval/session handling, participant ownership, narrow message schemas, output projection, Stop/Kick/Disconnect, and local logs that omit credentials/private content. Integrate existing auth protections rather than globally bypassing them. Add isolated regressions proving disabled and unauthorized paths before enabling admission. **3. Shared Conversation and Roleplay** Add create/join room, participant list, persona selection, attributed messages, approved AI characters/GM, host-coordinated response generation, validated streaming, and reconnect snapshots. Integrate the compatibility matrix, existing command dispatch, and a single room autonomous scheduler in this phase. Reuse safe chat layout/state logic with the restricted renderer. Make participant identities explicit in prompts and history; define multi-user macro behavior instead of overwriting the existing chat persona. Preserve existing single-player macro/identity behavior. No peer file imports or rich remote presentation. **4. Game round coordination** Add the smallest persisted round record: round ID/revision, required actor roster, submitted actions/pass state, and collecting/resolving/completed status. Reuse the existing generation lock and game-state write ordering. Atomically close collection only after all required actors are ready, resolve using attributed actions plus participant context, and commit one logical result. Reject stale/duplicate submissions and edits after resolution starts. Handle disconnect, host-approved roster changes, failure, cancellation, and restart recovery explicitly; never silently retry an ambiguous paid generation or double-apply world state. **5. Warnings, security verification, docs, and staged delivery** Add localized enable/join warnings, persistent hosting/guest indicators, clear participant/ready state, accessible controls, mobile layouts, and easy Stop/Leave actions. Complete the negative security matrix below and obtain focused security review before shipping. Deliver small issue-linked PRs against `staging`; keep each incomplete increment disabled. All three modes and the mandatory boundaries are required before calling this feature complete. Update `.env.example`, Settings help, `README.md`, `android/README.md`, `CONTRIBUTING.md`, `CHANGELOG.md`, and configuration/troubleshooting/FAQ docs as applicable. Update translated docs or file the required `[docs-i18n]` follow-up. Review the current local-single-user threat-model documentation explicitly; do not silently change prompt escaping to compensate for a new multiplayer boundary. Package-owned agent changes, if needed, belong in Marinara-Agents with linked work; Engine owns this feature's host integration. ### Required warnings and consent Before activation and before joining a new host, clearly say: > Only connect to people you trust. Use your own trusted Marinara client; never install a host-provided client, extension, or required file. The host can read and retain what you share, and shared content may be sent to their configured AI providers. Direct peer connections may reveal your IP address. Do not share passwords, API keys, or sensitive personal information. Leave immediately if anything seems suspicious. Explain that protection is limited to the supported client's controls and is not a guarantee that an unknown host or external download is safe. Show the host identity/fingerprint and room name in trusted UI separately from peer-controlled text, disclose whether the connection is direct or relayed, and require fresh consent after a host identity change. Host warnings should explain guest-content risks and generation usage. All new UI copy uses semantic English localization keys; community locales may fall back to English. ### Acceptance and regression plan These are required future checks, not claims that implementation or testing has happened: - [ ] Absent/false/invalid environment gate plus forged requests, saved UI preferences, deep links, and remote messages cannot activate multiplayer. With the flag true but Settings inactive, there are no active peer/signaling sessions. Test host and supported guest entrypoints. - [ ] Restart never automatically hosts/joins; Stop/Kick/Disconnect revoke the appropriate sessions, reject later/replayed actions, and prevent stale reconnect or late event delivery. - [ ] Host and guest can complete a session in each of Conversation, Roleplay, and Game with distinct personas and approved AI-controlled characters/GM. - [ ] Reuse the existing three-mode setup, chat surfaces, sidebar, settings drawer, pickers, and composer. Players/AI controls are clearly distinct; the guest joins without configuring an AI connection. A private chat/history is never published by an Invite action. - [ ] Test host invitation, guest warning/persona-field review, host approval/decline, expired/revoked invitations, guest Leave, host Stop/Kick, and identity-change consent on desktop and mobile. No room/history data reaches unapproved guests and no guest code is loaded from the host. - [ ] Verify participant-specific persona switching, Game lobby/party setup before initial generation, readable readiness/round controls, preserved disconnect drafts, and recovery states. Keyboard/focus, touch targets, software-keyboard layouts, light/dark themes, and localized labels remain usable. - [ ] Publish and verify the command/feature compatibility matrix. Authorized player commands, AI-emitted commands, group replies, and configured autonomous/scheduled messages work through existing host services with correct identity, scope, and recipient visibility. Restricted commands have an explicit explanation. - [ ] Multiple guest tabs, simultaneous timer/manual triggers, host and client scheduler overlap, reconnects, and retries do not duplicate autonomous messages, command effects, or AI generations. Guests never execute received command text locally. Game commands/autonomous triggers cannot bypass the player-action barrier; stopping hosting stops room autonomous work. - [ ] With two player characters, the first action does not resolve the Game round; the second produces one logical resolution. Explicit passes, duplicates, stale actions, simultaneous submissions, reconnects, disconnects, roster changes, cancellation, and failed/restarted generation preserve consistent state. - [ ] A hostile guest cannot impersonate another player, cross room boundaries, read private data, access administrative routes, turn a forwarded request into localhost privilege, or run unapproved AI tools. - [ ] A hostile host sending scripts, event handlers, encoded HTML, SVG, CSS URLs, iframes, dangerous URL schemes, forged download/import/update/native-action messages, disguised files, and unknown protocol fields causes no execution, download, installation, native bridge call, local API request, or external asset fetch on the trusted guest. - [ ] Repeat injection checks through names, cards, descriptions, AI replies, errors, history/reconnect snapshots, and incremental streaming fragments. Validate peer data on both receiving sides; host-provided safety flags/MIME claims are ignored. - [ ] Oversized, deeply nested, flooded, malformed, replayed, and incompatible-version traffic is rejected or disconnected within bounded CPU/memory/queue behavior. Wrong-password/join floods are rate-limited. - [ ] Network inspection proves credentials and private prompt/debug/GM fields are absent from shared events and snapshots; the guest renderer cannot load peer-supplied code/assets or use local/native capabilities. - [ ] Existing single-player chats, identity/macros, saving, and game progression remain compatible with multiplayer disabled; any data-format change follows storage version/migration rules. - [ ] Run `pnpm check`, `pnpm localization:check`, relevant Node/security regressions, `pnpm regression:prompt`, `pnpm smoke:ui`, and focused multi-client Playwright cases on desktop Chromium, mobile Chromium, and mobile WebKit. Use existing regression conventions; do not retain temporary `.test.ts` files. - [ ] Manually verify supported physical iPhone/iPad Home Screen and Android guest paths, host-tab suspension, connection loss/rejoin, warnings, and Stop/Leave. Unsupported platforms remain explicitly disabled. Complete local CodeRabbit, focused security review, and required CI before staging merges; record limitations and untested cases. ## Alternatives considered - **Let guests open the host's current Marinara web UI:** fails the malicious-host client-code boundary and exposes too much existing application surface. Do not use it as the guest security model. - **P2P plus a shared password only:** protects part of admission/transport, but does not constrain scripts, downloads, local capabilities, authorization, or malicious authenticated peers. - **Allow arbitrary files and scan for viruses:** substantially expands the attack surface and cannot prove every file safe. Start without peer file transfer; evaluate narrow media support separately. - **Fork the whole engine or build a generic multiplayer platform:** duplicates maintenance and adds unnecessary scope. Reuse Engine services and safe UI pieces behind a small explicit room boundary. - **Distributed state, federation, automatic host migration, many roles, public lobbies, voice/video, and an account platform:** defer; none is necessary to prove small private shared sessions in all three modes. ## Additional context Requested by maintainer @SpicyMarinara. This issue is an implementation plan/feature request, not a claim that the feature exists or that its security has been verified. Implementation is not started or assigned by this ticket. Related earlier suggestion: #5781, closed with an invitation to reopen/recreate when the maintainer approves the direction. This request provides the current three-mode scope, Game round behavior, explicit double opt-in, and security boundaries in both directions. No matching open multiplayer PR or local multiplayer branch was found during preparation. Code inspection at `0eac28284c80190c19dfd568d4f6933aa027a0e6` suggests these reuse/audit points; they are starting points, not blanket approval to expose existing code to peers: - `packages/shared/src/types/chat.ts` and `types/game.ts`: current chat persona and message identity snapshots; game setup/party model. - `packages/server/src/services/chat-user-identity.ts`, `services/generation/identity-context-runtime.ts`, `services/prompt/assembler.ts`, `services/prompt/macro-context.ts`: explicit multi-participant identity and prompt semantics. - `packages/server/src/routes/generate.routes.ts`: existing per-chat generation guard and SSE output; filter room-safe events rather than exposing raw internal events. - `packages/server/src/services/conversation/{autonomous.service,autonomous-candidates,server-autonomous-scheduler.service,schedule.service}.ts`, `services/generation/{conversation-command-runtime,roleplay-commands}.ts`, and `services/capability-packages/capability-command-registry.service.ts`: reuse command/scheduling behavior with room scope and single-coordinator guarantees. - `packages/client/src/lib/slash-commands.ts` and `hooks/{use-autonomous-messaging,use-background-autonomous,use-roleplay-commands}.ts`: route authorized room actions through the host instead of duplicating local execution/polling on guests. - `packages/server/src/services/storage/chats.storage.ts`, `game-state.storage.ts`, `game-engine-state.storage.ts`, and `db/schema/chats.ts`: persisted chat/game state and write ordering. - `packages/server/src/config/runtime-config.ts` and `middleware/{basic-auth,privileged-gate,csrf-protection,host-validation,android-local-auth}.ts`: environment enforcement and authorization boundaries. `privileged-gate.ts` currently includes a localhost trust path that must not apply to forwarded peer actions. - `packages/client/src/lib/chat-html.ts`, `components/chat/ChatMessage.tsx`, chat surfaces, game stores, and `hooks/use-generate.ts`: reuse candidates requiring a multiplayer-specific audit. Existing HTML sanitization still permits rich markup and image sources; it is not the proposed text-only guest renderer. - `CONTRIBUTING.md` explicitly describes the existing local/single-user prompt-content threat model. Multiplayer changes that deployment assumption; preserve existing prompt-leaf semantics and enforce import, rendering, and tool boundaries deliberately. Security references: [WebRTC trust model](https://www.rfc-editor.org/rfc/rfc8827.html#section-3), [OWASP safe DOM output](https://cheatsheetseries.owasp.org/cheatsheets/DOM_based_XSS_Prevention_Cheat_Sheet.html#rule-6---populate-the-dom-using-safe-javascript-functions-or-properties). These inform the plan; they do not certify an implementation. ## Template check Please **uncheck (untick)** the box below before submitting so we know you read the template. It is intentionally pre-checked: - [ ] I DID NOT read this template and provide the requested details.
Author
Owner

@SpicyMarinara commented on GitHub (Sep 29, 2026):

Implementation is being taken on by @SpicyMarinara with Codex. I am starting with the issue’s trusted-guest isolation and transport feasibility proof, then the double opt-in and room protocol, before integrating the existing three-mode UI and generation paths. The implementation will stay disabled while its security boundaries and mode compatibility are incomplete. An issue-linked draft PR will track the work; no multiplayer implementation branch or PR was present when starting.

<!-- gh-comment-id:5891331707 --> @SpicyMarinara commented on GitHub (Sep 29, 2026): Implementation is being taken on by @SpicyMarinara with Codex. I am starting with the issue’s trusted-guest isolation and transport feasibility proof, then the double opt-in and room protocol, before integrating the existing three-mode UI and generation paths. The implementation will stay disabled while its security boundaries and mode compatibility are incomplete. An issue-linked draft PR will track the work; no multiplayer implementation branch or PR was present when starting.
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Pasta-Devs/Marinara-Engine#3800
No description provided.