feat: implement role-based access control
Introduce 'gm', 'player', and 'observer' roles to the journal system. This includes: - Restricting command usage and completions to the GM role. - Implementing role-based message emission permissions. - Adding a player list and role indicators in the UI. - Persisting the user's role in localStorage. - Updating the connection logic to include the role in the client ID.
This commit is contained in:
parent
e216b94e25
commit
59236f6dba
|
|
@ -4,12 +4,7 @@
|
|||
|
||||
import { Component, createSignal, For, Show, createMemo } from "solid-js";
|
||||
import { registeredTypes, canEmit } from "./registry";
|
||||
import {
|
||||
sendMessage,
|
||||
revertLatest,
|
||||
canRevert,
|
||||
useJournalStream,
|
||||
} from "../stores/journalStream";
|
||||
import { sendMessage, useJournalStream } from "../stores/journalStream";
|
||||
import type { MessageTypeDef } from "./registry";
|
||||
import { DynamicForm } from "./DynamicForm";
|
||||
|
||||
|
|
@ -20,7 +15,7 @@ export const ComposePanel: Component = () => {
|
|||
const [error, setError] = createSignal<string | null>(null);
|
||||
const [sending, setSending] = createSignal(false);
|
||||
|
||||
const role = () => stream.myName;
|
||||
const role = () => stream.myRole;
|
||||
|
||||
// Available types filtered by role
|
||||
const availableTypes = createMemo(() => {
|
||||
|
|
@ -51,12 +46,6 @@ export const ComposePanel: Component = () => {
|
|||
setSending(false);
|
||||
};
|
||||
|
||||
const handleRevert = () => {
|
||||
revertLatest();
|
||||
};
|
||||
|
||||
const showRevert = () => canRevert() && stream.myName === "gm";
|
||||
|
||||
return (
|
||||
<div class="border-t border-gray-200 p-2 space-y-2 bg-white">
|
||||
{/* Type picker */}
|
||||
|
|
@ -81,16 +70,6 @@ export const ComposePanel: Component = () => {
|
|||
>
|
||||
{sending() ? "..." : "Send"}
|
||||
</button>
|
||||
|
||||
<Show when={showRevert()}>
|
||||
<button
|
||||
onClick={handleRevert}
|
||||
class="text-xs text-gray-400 hover:text-red-500"
|
||||
title="Revert last message"
|
||||
>
|
||||
↩
|
||||
</button>
|
||||
</Show>
|
||||
</div>
|
||||
|
||||
{/* Dynamic form */}
|
||||
|
|
|
|||
|
|
@ -21,11 +21,7 @@ import {
|
|||
Match,
|
||||
} from "solid-js";
|
||||
import { sendMessage, useJournalStream } from "../stores/journalStream";
|
||||
import {
|
||||
useJournalCompletions,
|
||||
ensureCompletions,
|
||||
type CompletionsState,
|
||||
} from "./completions";
|
||||
import { useJournalCompletions, ensureCompletions } from "./completions";
|
||||
|
||||
// ---- Helpers ----
|
||||
|
||||
|
|
@ -78,6 +74,10 @@ export const JournalInput: Component = () => {
|
|||
const stream = useJournalStream();
|
||||
const comp = useJournalCompletions();
|
||||
|
||||
const isObserver = () => stream.myRole === "observer";
|
||||
const isPlayer = () => stream.myRole === "player";
|
||||
const isGm = () => stream.myRole === "gm";
|
||||
|
||||
const [text, setText] = createSignal("");
|
||||
const [error, setError] = createSignal<string | null>(null);
|
||||
const [sending, setSending] = createSignal(false);
|
||||
|
|
@ -98,6 +98,18 @@ export const JournalInput: Component = () => {
|
|||
const raw = text().trim();
|
||||
if (!raw) return;
|
||||
|
||||
// Players can't use commands — everything is narrative
|
||||
if (isPlayer() || isObserver()) {
|
||||
const result = sendMessage("narrative", { text: raw });
|
||||
if (!result.success) {
|
||||
setError(result.error);
|
||||
} else {
|
||||
setText("");
|
||||
}
|
||||
textareaRef?.focus();
|
||||
return;
|
||||
}
|
||||
|
||||
const parsed = parseInput(raw);
|
||||
if (parsed.error) {
|
||||
setError(parsed.error);
|
||||
|
|
@ -132,6 +144,8 @@ export const JournalInput: Component = () => {
|
|||
|
||||
function buildCompletions(): CompletionItem[] {
|
||||
const raw = text().trim();
|
||||
// Only GM gets completions
|
||||
if (!isGm()) return [];
|
||||
const data = comp.data;
|
||||
const commands = [
|
||||
{ label: "/roll", kind: "command" as const, insertText: "/roll " },
|
||||
|
|
@ -235,9 +249,9 @@ export const JournalInput: Component = () => {
|
|||
}
|
||||
return;
|
||||
}
|
||||
// If not open and starts with /, open completions
|
||||
// If not open and starts with /, open completions (GM only)
|
||||
const raw = text();
|
||||
if (raw.startsWith("/")) {
|
||||
if (isGm() && raw.startsWith("/")) {
|
||||
e.preventDefault();
|
||||
setShowCompletions(true);
|
||||
setSelectedIdx(0);
|
||||
|
|
@ -280,8 +294,8 @@ export const JournalInput: Component = () => {
|
|||
const raw = input.value;
|
||||
setText(raw);
|
||||
|
||||
// Completions visibility — keep open while user types any /
|
||||
if (raw.startsWith("/")) {
|
||||
// Completions visibility — keep open while user types any / (GM only)
|
||||
if (isGm() && raw.startsWith("/")) {
|
||||
setShowCompletions(true);
|
||||
setSelectedIdx(0);
|
||||
} else {
|
||||
|
|
@ -386,12 +400,25 @@ export const JournalInput: Component = () => {
|
|||
|
||||
{/* Textarea + actions */}
|
||||
<div class="flex flex-col">
|
||||
<Show
|
||||
when={!isObserver()}
|
||||
fallback={
|
||||
<div class="px-3 py-4 text-xs text-gray-400 italic text-center">
|
||||
You are observing. Open this panel on another device to join as GM
|
||||
or player.
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<textarea
|
||||
ref={textareaRef}
|
||||
value={text()}
|
||||
onInput={handleInput}
|
||||
onKeyDown={handleKeyDown}
|
||||
placeholder="Type a message, or /roll or /link..."
|
||||
placeholder={
|
||||
isGm()
|
||||
? "Type a message, or /roll or /link..."
|
||||
: "Type a message..."
|
||||
}
|
||||
rows={2}
|
||||
class="w-full resize-none border-0 px-3 pt-2.5 pb-1 text-sm
|
||||
text-gray-800 placeholder-gray-400 focus:outline-none
|
||||
|
|
@ -415,6 +442,7 @@ export const JournalInput: Component = () => {
|
|||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Show>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
|
|
|||
|
|
@ -11,6 +11,7 @@ import {
|
|||
hydrateFromServer,
|
||||
useJournalStream,
|
||||
setMyName,
|
||||
setMyRole,
|
||||
setSessionId,
|
||||
sessions,
|
||||
createSession,
|
||||
|
|
@ -27,6 +28,12 @@ export interface JournalPanelProps {
|
|||
export const JournalPanel: Component<JournalPanelProps> = (props) => {
|
||||
const stream = useJournalStream();
|
||||
|
||||
// Player list (exclude gm and observer)
|
||||
const playerEntries = () =>
|
||||
Object.entries(stream.players).filter(
|
||||
([_, p]) => p.role !== "gm" && p.role !== "observer",
|
||||
);
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Backdrop — only on mobile, starts below header */}
|
||||
|
|
@ -47,6 +54,19 @@ export const JournalPanel: Component<JournalPanelProps> = (props) => {
|
|||
{/* Header */}
|
||||
<JournalHeader onClose={props.onClose} />
|
||||
|
||||
{/* Player list tabs */}
|
||||
<Show when={stream.connected && playerEntries().length > 0}>
|
||||
<div class="flex items-center gap-1 px-3 py-1.5 border-b border-gray-100 bg-gray-50 overflow-x-auto shrink-0">
|
||||
<For each={playerEntries()}>
|
||||
{([name]) => (
|
||||
<span class="text-xs bg-blue-100 text-blue-700 px-2 py-0.5 rounded-full whitespace-nowrap">
|
||||
{name}
|
||||
</span>
|
||||
)}
|
||||
</For>
|
||||
</div>
|
||||
</Show>
|
||||
|
||||
<Show
|
||||
when={stream.connected}
|
||||
fallback={
|
||||
|
|
@ -134,10 +154,22 @@ const JournalHeader: Component<JournalHeaderProps> = (props) => {
|
|||
}
|
||||
>
|
||||
<div class="min-w-0">
|
||||
<p class="text-sm font-semibold text-gray-700 truncate leading-tight">
|
||||
<p class="text-sm font-semibold text-gray-700 truncate leading-tight flex items-center gap-1">
|
||||
{stream.myName}
|
||||
<Show when={stream.myRole !== "gm"}>
|
||||
<span
|
||||
class={`text-[10px] px-1 rounded ${
|
||||
stream.myRole === "observer"
|
||||
? "bg-gray-200 text-gray-500"
|
||||
: "bg-blue-100 text-blue-600"
|
||||
}`}
|
||||
>
|
||||
{stream.myRole}
|
||||
</span>
|
||||
</Show>
|
||||
</p>
|
||||
{/* Clickable subtitle — session dropdown */}
|
||||
{/* Clickable subtitle — session dropdown (GM only) */}
|
||||
<Show when={stream.myRole === "gm"}>
|
||||
<div ref={dropdownRef} class="relative">
|
||||
<button
|
||||
onClick={() => setDropdownOpen((v) => !v)}
|
||||
|
|
@ -203,6 +235,7 @@ const JournalHeader: Component<JournalHeaderProps> = (props) => {
|
|||
</div>
|
||||
</Show>
|
||||
</div>
|
||||
</Show>
|
||||
</div>
|
||||
</Show>
|
||||
</div>
|
||||
|
|
@ -235,16 +268,12 @@ const JournalHeader: Component<JournalHeaderProps> = (props) => {
|
|||
const ConnectDialog: Component = () => {
|
||||
const stream = useJournalStream();
|
||||
const [playerName, setPlayerName] = createSignal(stream.myName);
|
||||
const [role, setRole] = createSignal<"gm" | "player" | "observer">(
|
||||
stream.myRole,
|
||||
);
|
||||
const [connecting, setConnecting] = createSignal(false);
|
||||
const [error, setError] = createSignal<string | null>(null);
|
||||
|
||||
// Auto-connect if we have a name from localStorage
|
||||
onMount(() => {
|
||||
if (stream.myName && stream.myName !== "gm") {
|
||||
handleConnect();
|
||||
}
|
||||
});
|
||||
|
||||
const handleConnect = async () => {
|
||||
const name = playerName().trim() || stream.myName;
|
||||
if (!name) return;
|
||||
|
|
@ -256,6 +285,7 @@ const ConnectDialog: Component = () => {
|
|||
|
||||
try {
|
||||
setMyName(name);
|
||||
setMyRole(role());
|
||||
const sessionId = stream.sessionId || "default";
|
||||
setSessionId(sessionId);
|
||||
await hydrateFromServer(sessionId);
|
||||
|
|
@ -263,8 +293,6 @@ const ConnectDialog: Component = () => {
|
|||
} catch (e) {
|
||||
const msg = e instanceof Error ? e.message : "Connection failed";
|
||||
setError(msg);
|
||||
// If connectStream threw, the error handler also sets connectionStatus to error.
|
||||
// Make sure the error message is captured.
|
||||
} finally {
|
||||
setConnecting(false);
|
||||
}
|
||||
|
|
@ -273,7 +301,7 @@ const ConnectDialog: Component = () => {
|
|||
return (
|
||||
<div class="w-full max-w-sm space-y-3">
|
||||
<p class="text-sm text-gray-600 text-center">
|
||||
Enter your name to join the session.
|
||||
Enter your name and role to join the session.
|
||||
<br />
|
||||
<span class="text-xs text-gray-400">
|
||||
Connecting to {window.location.host}
|
||||
|
|
@ -284,10 +312,25 @@ const ConnectDialog: Component = () => {
|
|||
value={playerName()}
|
||||
onInput={(e) => setPlayerName(e.currentTarget.value)}
|
||||
onKeyDown={(e) => e.key === "Enter" && handleConnect()}
|
||||
placeholder="Your name (GM or player)"
|
||||
placeholder="Your name"
|
||||
class="w-full border border-gray-300 rounded px-3 py-1.5 text-sm"
|
||||
autofocus
|
||||
/>
|
||||
{/* Role selector */}
|
||||
<div class="flex gap-1">
|
||||
{(["gm", "player", "observer"] as const).map((r) => (
|
||||
<button
|
||||
onClick={() => setRole(r)}
|
||||
class={`flex-1 rounded px-2 py-1.5 text-xs font-medium border transition-colors ${
|
||||
role() === r
|
||||
? "bg-blue-600 text-white border-blue-600"
|
||||
: "bg-white text-gray-600 border-gray-300 hover:border-gray-400"
|
||||
}`}
|
||||
>
|
||||
{r === "gm" ? "GM" : r === "player" ? "Player" : "Observer"}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<button
|
||||
onClick={handleConnect}
|
||||
disabled={connecting() || !playerName().trim()}
|
||||
|
|
|
|||
|
|
@ -5,11 +5,7 @@
|
|||
import { Component, Show, createMemo } from "solid-js";
|
||||
import type { StreamMessage as StreamMessageType } from "./registry";
|
||||
import { getMessageType } from "./registry";
|
||||
import {
|
||||
revertLatest,
|
||||
canRevert,
|
||||
useJournalStream,
|
||||
} from "../stores/journalStream";
|
||||
import { revertLatest, useJournalStream } from "../stores/journalStream";
|
||||
|
||||
export const StreamMessageCard: Component<{
|
||||
message: StreamMessageType;
|
||||
|
|
|
|||
|
|
@ -46,8 +46,8 @@ export interface MessageTypeDef<P = unknown> {
|
|||
type: string;
|
||||
/** Human-readable label shown in the compose panel dropdown */
|
||||
label: string;
|
||||
/** Which roles can emit this type. Empty array = all roles allowed. */
|
||||
emitters?: ("gm" | "player")[];
|
||||
/** Which roles can emit this type. Empty array = all roles (including observer) allowed. */
|
||||
emitters?: ("gm" | "player" | "observer")[];
|
||||
/** Zod schema used to validate payload before publish */
|
||||
schema: ZodType<P>;
|
||||
/** Returns a default payload for compose panel initialization */
|
||||
|
|
@ -110,7 +110,9 @@ export function validatePayload<P>(
|
|||
}
|
||||
return {
|
||||
success: false,
|
||||
error: result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join("; "),
|
||||
error: result.error.issues
|
||||
.map((i) => `${i.path.join(".")}: ${i.message}`)
|
||||
.join("; "),
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -122,5 +124,5 @@ export function canEmit(type: string, role: string): boolean {
|
|||
if (!def) return false;
|
||||
const emitters = def.emitters;
|
||||
if (!emitters || emitters.length === 0) return true;
|
||||
return emitters.includes(role as "gm" | "player");
|
||||
return emitters.includes(role as "gm" | "player" | "observer");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -42,9 +42,7 @@ const RevealLink: Component<ArticleRevealPayload> = (p) => {
|
|||
|
||||
const displayLabel = () => {
|
||||
if (p.label) return p.label;
|
||||
const file = fileNameFromPath(p.path);
|
||||
if (p.section) return `${file} § ${slugToTitle(p.section)}`;
|
||||
return file;
|
||||
return fileNameFromPath(p.path);
|
||||
};
|
||||
|
||||
const handleClick = (e: MouseEvent) => {
|
||||
|
|
|
|||
|
|
@ -17,6 +17,7 @@ export type NarrativePayload = z.infer<typeof schema>;
|
|||
registerMessageType<NarrativePayload>({
|
||||
type: "narrative",
|
||||
label: "Narrative",
|
||||
emitters: ["gm", "player"],
|
||||
schema,
|
||||
defaultPayload: () => ({ text: "" }),
|
||||
render: (p) => <p class="text-sm whitespace-pre-wrap">{p.text}</p>,
|
||||
|
|
|
|||
|
|
@ -41,8 +41,12 @@ export interface JournalStreamState {
|
|||
connectionError: string | null;
|
||||
/** This client's identity */
|
||||
myName: string;
|
||||
/** Role: gm | player | observer. Immutable while connected. */
|
||||
myRole: "gm" | "player" | "observer";
|
||||
/** Broker URL, set after connect */
|
||||
brokerUrl: string | null;
|
||||
/** Active player list (keyed by player name) */
|
||||
players: Record<string, { role: string }>;
|
||||
}
|
||||
|
||||
export interface SessionMeta {
|
||||
|
|
@ -62,19 +66,22 @@ export interface SessionManifest {
|
|||
const LS_PLAYER_NAME = "ttrpg.playerName";
|
||||
const LS_BROKER_URL = "ttrpg.brokerUrl";
|
||||
const LS_LAST_SESSION = "ttrpg.lastSessionId";
|
||||
const LS_PLAYER_ROLE = "ttrpg.playerRole";
|
||||
|
||||
function loadPersisted(): {
|
||||
myName: string;
|
||||
brokerUrl: string | null;
|
||||
lastSessionId: string | null;
|
||||
myRole: string;
|
||||
} {
|
||||
if (typeof localStorage === "undefined") {
|
||||
return { myName: "gm", brokerUrl: null, lastSessionId: null };
|
||||
return { myName: "gm", brokerUrl: null, lastSessionId: null, myRole: "gm" };
|
||||
}
|
||||
return {
|
||||
myName: localStorage.getItem(LS_PLAYER_NAME) || "gm",
|
||||
brokerUrl: localStorage.getItem(LS_BROKER_URL),
|
||||
lastSessionId: localStorage.getItem(LS_LAST_SESSION),
|
||||
myRole: localStorage.getItem(LS_PLAYER_ROLE) || "gm",
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -99,7 +106,9 @@ const [state, setState] = createStore<JournalStreamState>({
|
|||
connectionStatus: "disconnected",
|
||||
connectionError: null,
|
||||
myName: initialName,
|
||||
myRole: (persisted.myRole as "gm" | "player" | "observer") || "gm",
|
||||
brokerUrl: persisted.brokerUrl,
|
||||
players: {},
|
||||
});
|
||||
|
||||
// Sync initial URL params if they came from localStorage (not URL)
|
||||
|
|
@ -127,6 +136,17 @@ export function setMyName(name: string): void {
|
|||
syncUrlParam("player", name);
|
||||
}
|
||||
|
||||
/**
|
||||
* Change the current player's role. Persisted to localStorage.
|
||||
* Only callable when disconnected.
|
||||
*/
|
||||
export function setMyRole(role: "gm" | "player" | "observer"): void {
|
||||
setState("myRole", role);
|
||||
if (typeof localStorage !== "undefined") {
|
||||
localStorage.setItem(LS_PLAYER_ROLE, role);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the active session ID and sync to URL. Also resolves the human-readable
|
||||
* session name from the cached manifest.
|
||||
|
|
@ -270,7 +290,7 @@ export async function connectStream(
|
|||
|
||||
return new Promise<void>((resolve, reject) => {
|
||||
const client = mqtt.connect(brokerUrl, {
|
||||
clientId: `${state.myName}-${Date.now()}`,
|
||||
clientId: `${state.myName}-${state.myRole}-${Date.now()}`,
|
||||
protocol: brokerUrl.startsWith("wss") ? "wss" : "ws",
|
||||
reconnectPeriod: 2000,
|
||||
});
|
||||
|
|
@ -297,6 +317,19 @@ export async function connectStream(
|
|||
if (err) console.error("[stream] sessions sub err:", err);
|
||||
});
|
||||
client.subscribe(`ttrpg/${sessionId}/meta`, { qos: 1 });
|
||||
// Presence tracking
|
||||
client.subscribe(`ttrpg/${sessionId}/presence/+`, { qos: 1 });
|
||||
|
||||
// Publish own presence (retained)
|
||||
const presenceData = JSON.stringify({
|
||||
name: state.myName,
|
||||
role: state.myRole,
|
||||
});
|
||||
client.publish(
|
||||
`ttrpg/${sessionId}/presence/${state.myName}`,
|
||||
presenceData,
|
||||
{ qos: 1, retain: true },
|
||||
);
|
||||
|
||||
resolve();
|
||||
});
|
||||
|
|
@ -340,6 +373,33 @@ export async function connectStream(
|
|||
return;
|
||||
}
|
||||
|
||||
// Presence: ttrpg/{sessionId}/presence/{playerName}
|
||||
if (
|
||||
parts.length >= 4 &&
|
||||
parts[0] === "ttrpg" &&
|
||||
parts[2] === "presence"
|
||||
) {
|
||||
const playerName = parts[3];
|
||||
if (raw) {
|
||||
try {
|
||||
const presence = JSON.parse(raw);
|
||||
setState("players", playerName, {
|
||||
role: presence.role || "player",
|
||||
});
|
||||
} catch {
|
||||
setState("players", playerName, { role: "player" });
|
||||
}
|
||||
} else {
|
||||
// Tombstone — player disconnected
|
||||
setState(
|
||||
produce((s) => {
|
||||
delete s.players[playerName];
|
||||
}),
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (parts.length >= 3 && parts[0] === "ttrpg" && parts[2] === "stream") {
|
||||
try {
|
||||
const msg: StreamMessage = JSON.parse(raw);
|
||||
|
|
@ -505,12 +565,24 @@ export function revertLatest():
|
|||
|
||||
export function disconnectStream(): void {
|
||||
if (_mqttClient) {
|
||||
_mqttClient.end(true);
|
||||
// Clear our presence before disconnecting (tombstone)
|
||||
const sessionId = state.sessionId;
|
||||
if (sessionId) {
|
||||
_mqttClient.publish(`ttrpg/${sessionId}/presence/${state.myName}`, "", {
|
||||
qos: 1,
|
||||
retain: true,
|
||||
});
|
||||
}
|
||||
// Force disconnect without reconnect
|
||||
_mqttClient.end(true, void 0, () => {
|
||||
// noop
|
||||
});
|
||||
_mqttClient = null;
|
||||
_mqttConnected = false;
|
||||
}
|
||||
setState("connected", false);
|
||||
setState("connectionStatus", "disconnected");
|
||||
setState("players", {});
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
|
|
|||
Loading…
Reference in New Issue