v3: the frontend stops trusting what it last saw — a review of src/ turned up counts that fell to zero, stale copies winning over fresh ones, sessions that tabs trampled on each other, and a player queue that outlived its listener, and this closes them. Voting or liking something with no live count yet started from 0, so a dump with five votes read 1 on the click and, with the socket down, 0 for good once the undo fired; the buttons now pass the count they show, which the optimistic update and its undo start from. After a reconnect the chat re-read its history as the truth, but the merge let the live copy of a message win, so an edit made while the socket was down never showed; the resync now replaces live copies with what it fetched. Every dump_updated added the dump to the live list if it wasn't there, so retitling a months-old dump put it at the top of New, Hot and Journal for everyone, while one that had arrived live kept its old title; an edit now refreshes a live entry in place and adds nothing, and the server announces a dump going public as a dump_created, which is the one case that is an arrival. The new-dump modal let a slow preview for the previous link land on the new one, title suggestion included; changing the link now aborts both lookups. Markdown found mentions by rewriting the source text with a rule that, unlike the server's, didn't skip an @ after a word character, so an email address linked its domain, a URL like mastodon.social/@bob was split, and @ in code came out as literal link syntax; mentions are now found by a remark step over text nodes only, by the server's rule. Changing the password in one tab stored fresh tokens that any other open tab wiped the moment its old token drew a 401; the session now lives behind utils/authStorage.ts, tabs follow each other through storage events (so a logout also signs out every tab), a 401 only forgets the stored session if it still holds that token, and in-place session updates go through a new updateSession() rather than re-reading localStorage. The persisted player queue carries media-token URLs yet survived logout for the next person to sign in; it is now stamped with its owner, not restored for anyone else, cleared on logout or account switch (a guest's queue survives signing in), and older unstamped queues holding a file are dropped. Playlist checkboxes in the new-dump and add-to-playlist modals flipped whether or not the server agreed and now wait for it. CommentThread and the Dump page's loads use authFetch like the rest, so a 401 there signs out consistently; isTokenExpired has one home; and the useScrollLock imports carry their extension so deno check passes.
All checks were successful
Build and Publish Docker Image / build-and-push (push) Successful in 42s

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
khannurien
2026-09-24 20:24:38 +00:00
parent 2ad8ae73d5
commit bfce3186f8
24 changed files with 360 additions and 215 deletions

View File

@@ -1,10 +1,10 @@
import { createContext } from "react";
import { createContext, type Dispatch, type SetStateAction } from "react";
import { type AuthResponse } from "../model.ts";
export interface AuthContextValue {
authResponse: AuthResponse | null;
setAuthResponse: (authResponse: AuthResponse | null) => void;
setAuthResponse: Dispatch<SetStateAction<AuthResponse | null>>;
}
export const AuthContext = createContext<AuthContextValue>({

View File

@@ -2,48 +2,31 @@ import { type ReactNode, useEffect, useState } from "react";
import { AuthContext, type AuthContextValue } from "./AuthContext.ts";
import {
type AuthResponse,
deserializeAuthResponse,
deserializePublicUser,
} from "../model.ts";
import { type AuthResponse, deserializePublicUser } from "../model.ts";
import { API_URL } from "../config/api.ts";
function isTokenExpired(token: string): boolean {
try {
const payload = JSON.parse(atob(token.split(".")[1]));
return typeof payload.exp === "number" && payload.exp * 1000 < Date.now();
} catch {
return true;
}
}
import {
AUTH_STORAGE_KEY,
forgetStoredSession,
readStoredSession,
storeSession,
} from "../utils/authStorage.ts";
export function AuthProvider({ children }: { children: ReactNode }) {
const [authResponse, setAuthResponse] = useState<AuthResponse | null>(() => {
const stored = localStorage.getItem("authResponse");
if (!stored) return null;
const [authResponse, setAuthResponse] = useState<AuthResponse | null>(
readStoredSession,
);
let parsed;
try {
parsed = deserializeAuthResponse(JSON.parse(stored));
} catch {
localStorage.removeItem("authResponse");
return null;
}
if (isTokenExpired(parsed.token)) {
localStorage.removeItem("authResponse");
return null;
}
// Sessions persisted before roles existed have no `role`; the server also
// rejects their tokens, but discard them here so the UI never renders with
// a roleless user.
if (!parsed.user.role) {
localStorage.removeItem("authResponse");
return null;
}
return parsed;
});
// Every tab shares the stored session, so follow it: a login, logout or
// password change in another tab applies here too, rather than this tab
// carrying on with a token the server has since revoked.
useEffect(() => {
const onStorage = (e: StorageEvent) => {
if (e.key !== AUTH_STORAGE_KEY && e.key !== null) return;
setAuthResponse(readStoredSession());
};
globalThis.addEventListener("storage", onStorage);
return () => globalThis.removeEventListener("storage", onStorage);
}, []);
// The `exp` pre-check above only catches expiry; it cannot detect a token the
// server rejects for another reason (e.g. a changed GERBEUR_JWT_SECRET, which
@@ -62,8 +45,10 @@ export function AuthProvider({ children }: { children: ReactNode }) {
cache: "no-store",
});
if (res.status === 401) {
localStorage.removeItem("authResponse");
setAuthResponse(null);
// Only this token is dead; the session may have moved on to a
// fresh one (another tab's password change) while we asked.
forgetStoredSession(token);
setAuthResponse((prev) => prev?.token === token ? null : prev);
return;
}
// The stored user is a snapshot from login time; the role (and other
@@ -77,7 +62,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
setAuthResponse((prev) => {
if (!prev || prev.user.role === freshUser.role) return prev;
const updated = { ...prev, user: freshUser };
localStorage.setItem("authResponse", JSON.stringify(updated));
storeSession(updated);
return updated;
});
}
@@ -116,7 +101,7 @@ export function AuthProvider({ children }: { children: ReactNode }) {
setAuthResponse((prev) => {
if (!prev || prev.token !== token) return prev;
const updated = { ...prev, mediaToken };
localStorage.setItem("authResponse", JSON.stringify(updated));
storeSession(updated);
return updated;
});
})

View File

@@ -5,6 +5,7 @@ import {
playerItemKey,
} from "./PlayerContext.ts";
import { isStreamStale, resolveStreamQueue } from "../utils/streamSources.ts";
import { useAuth } from "../hooks/useAuth.ts";
const STORAGE_KEY = "player";
@@ -20,6 +21,11 @@ interface StoredSession {
queue: PlayerItem[];
index: number;
time: number;
/**
* Whose queue this is (null for a guest). File URLs carry the listener's
* media token, so a queue must never be handed to whoever signs in next.
*/
owner?: string | null;
}
function isPlayerItem(value: unknown): value is PlayerItem {
@@ -28,13 +34,25 @@ function isPlayerItem(value: unknown): value is PlayerItem {
return kind === "embed" || kind === "file" || kind === "stream";
}
function readSession(): { queue: PlayerItem[]; index: number; time: number } | null {
function readSession(
owner: string | null,
): { queue: PlayerItem[]; index: number; time: number } | null {
try {
const raw = localStorage.getItem(STORAGE_KEY);
if (!raw) return null;
const parsed = JSON.parse(raw) as Record<string, unknown>;
const time = Number(parsed.time) || 0;
// Another account's queue, or one saved before queues had owners: the
// latter may be anybody's, and only file URLs hold a token worth keeping
// to themselves.
if (parsed.owner === undefined) {
const items = Array.isArray(parsed.queue) ? parsed.queue : [parsed.item];
if (items.some((i) => isPlayerItem(i) && i.kind === "file")) return null;
} else if (parsed.owner !== owner) {
return null;
}
const rawQueue = parsed.queue;
if (Array.isArray(rawQueue)) {
const queue = rawQueue.filter(isPlayerItem);
@@ -60,8 +78,10 @@ function readSession(): { queue: PlayerItem[]; index: number; time: number } | n
const RERESOLVE_COOLDOWN_MS = 30_000;
export function PlayerProvider({ children }: { children: React.ReactNode }) {
const { user } = useAuth();
const owner = user?.id ?? null;
// Lazy initialiser: readSession runs exactly once, on first render.
const [restored] = useState(readSession);
const [restored] = useState(() => readSession(owner));
const [queue, setQueue] = useState<PlayerItem[]>(restored?.queue ?? []);
const [queueIndex, setQueueIndex] = useState(restored?.index ?? 0);
@@ -323,7 +343,13 @@ export function PlayerProvider({ children }: { children: React.ReactNode }) {
localStorage.setItem(
STORAGE_KEY,
JSON.stringify(
{ v: 2, queue, index: queueIndex, time: currentTime } satisfies StoredSession,
{
v: 2,
queue,
index: queueIndex,
time: currentTime,
owner,
} satisfies StoredSession,
),
);
} else {
@@ -331,12 +357,23 @@ export function PlayerProvider({ children }: { children: React.ReactNode }) {
}
// currentTime intentionally omitted from deps — see pagehide writer below.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [queue, queueIndex]);
}, [queue, queueIndex, owner]);
// Signing out, or in as someone else, ends the listening session: the queue
// was built with the previous account's media token. Signing in keeps a
// guest's queue, which holds no token.
const [queueOwner, setQueueOwner] = useState(owner);
useEffect(() => {
if (owner === queueOwner) return;
// eslint-disable-next-line react-hooks/set-state-in-effect
setQueueOwner(owner);
if (queueOwner !== null) stop();
}, [owner, queueOwner, stop]);
const sessionRef = useRef<StoredSession | null>(null);
useEffect(() => {
sessionRef.current = queue.length > 0
? { v: 2, queue, index: queueIndex, time: currentTime }
? { v: 2, queue, index: queueIndex, time: currentTime, owner }
: null;
});

View File

@@ -101,10 +101,11 @@ export interface WSContextValue {
typingUsers: OnlineUser[];
/** Increments on each WS reconnect so pages can backfill missed events. */
connectionEpoch: number;
castVote: (dumpId: string) => void;
removeVote: (dumpId: string) => void;
castCommentLike: (commentId: string) => void;
removeCommentLike: (commentId: string) => void;
/** `shownCount`: the count on screen, used until a live one arrives. */
castVote: (dumpId: string, shownCount?: number) => void;
removeVote: (dumpId: string, shownCount?: number) => void;
castCommentLike: (commentId: string, shownCount?: number) => void;
removeCommentLike: (commentId: string, shownCount?: number) => void;
injectDump: (dump: Dump) => void;
clearUnreadNotifications: () => void;
sendChatMessage: (body: string, replyTo?: ChatReplyTarget) => void;

View File

@@ -450,9 +450,20 @@ export function WSProvider({ children }: WSProviderProps) {
}
case "dump_created": {
// Also sent when a dump goes from private to public: to everyone
// who couldn't see it, that's an arrival.
const dump = deserializeDump(msg.dump);
setDeletedDumpIds((prev) => {
if (!prev.has(dump.id)) return prev;
const next = new Set(prev);
next.delete(dump.id);
return next;
});
setRecentDumps((prev) =>
[dump, ...prev].slice(0, MAX_RECENT_DUMPS)
[dump, ...prev.filter((d) => d.id !== dump.id)].slice(
0,
MAX_RECENT_DUMPS,
)
);
break;
}
@@ -460,19 +471,13 @@ export function WSProvider({ children }: WSProviderProps) {
case "dump_updated": {
const dump = deserializeDump(msg.dump);
setLastDumpEvent(dump);
// Un-delete if this dump was previously removed from the feed
// (e.g. it was made private, and is now public again).
setDeletedDumpIds((prev) => {
if (!prev.has(dump.id)) return prev;
const next = new Set(prev);
next.delete(dump.id);
return next;
});
// Add to live feed if not already present (private→public).
// An edit is not an arrival: refresh a live entry in place, but
// don't pull an old dump to the top of the feeds (going public
// comes as a `dump_created`).
setRecentDumps((prev) =>
prev.some((d) => d.id === dump.id)
? prev
: [dump, ...prev].slice(0, MAX_RECENT_DUMPS)
? prev.map((d) => d.id === dump.id ? dump : d)
: prev
);
break;
}
@@ -745,9 +750,10 @@ export function WSProvider({ children }: WSProviderProps) {
token,
]);
const castVote = useCallback((dumpId: string) => {
// Optimistic update
const prevCount = voteCountsRef.current[dumpId] ?? 0;
const castVote = useCallback((dumpId: string, shownCount?: number) => {
// Optimistic update. Until a live event arrives there's no count here, only
// the one the caller got over REST and is showing.
const prevCount = voteCountsRef.current[dumpId] ?? shownCount ?? 0;
const prevVoted = myVotesRef.current.has(dumpId);
if (prevVoted) return; // already voted
@@ -778,9 +784,10 @@ export function WSProvider({ children }: WSProviderProps) {
// If socket is not OPEN, the revert timer will handle cleanup after ACK_TIMEOUT
}, [schedulePendingVote]);
const removeVote = useCallback((dumpId: string) => {
// Optimistic update
const prevCount = voteCountsRef.current[dumpId] ?? 0;
const removeVote = useCallback((dumpId: string, shownCount?: number) => {
// Optimistic update. Until a live event arrives there's no count here, only
// the one the caller got over REST and is showing.
const prevCount = voteCountsRef.current[dumpId] ?? shownCount ?? 0;
const prevVoted = myVotesRef.current.has(dumpId);
if (!prevVoted) return; // not voted
@@ -814,9 +821,10 @@ export function WSProvider({ children }: WSProviderProps) {
// If socket is not OPEN, the revert timer will handle cleanup after ACK_TIMEOUT
}, [schedulePendingVote]);
const castCommentLike = useCallback((commentId: string) => {
// Optimistic update
const prevCount = likeCountsRef.current[commentId] ?? 0;
const castCommentLike = useCallback((commentId: string, shownCount?: number) => {
// Optimistic update. Until a live event arrives there's no count here, only
// the one the caller got over REST and is showing.
const prevCount = likeCountsRef.current[commentId] ?? shownCount ?? 0;
const prevLiked = myLikesRef.current.has(commentId);
if (prevLiked) return; // already liked
@@ -847,9 +855,10 @@ export function WSProvider({ children }: WSProviderProps) {
// If socket is not OPEN, the revert timer will handle cleanup after ACK_TIMEOUT
}, [schedulePendingLike]);
const removeCommentLike = useCallback((commentId: string) => {
// Optimistic update
const prevCount = likeCountsRef.current[commentId] ?? 0;
const removeCommentLike = useCallback((commentId: string, shownCount?: number) => {
// Optimistic update. Until a live event arrives there's no count here, only
// the one the caller got over REST and is showing.
const prevCount = likeCountsRef.current[commentId] ?? shownCount ?? 0;
const prevLiked = myLikesRef.current.has(commentId);
if (!prevLiked) return; // not liked
@@ -1038,11 +1047,16 @@ export function WSProvider({ children }: WSProviderProps) {
const reconcileChat = useCallback(
(messages: ChatMessage[], from: Date, to: Date) => {
const ids = new Set(messages.map((m) => m.id));
// In that stretch the fetched copy is the truth: a live copy of a
// message edited while the socket was down is stale, and the merge in
// the chatbox would let it win.
const byId = new Map(messages.map((m) => [m.id, m]));
setChatMessages((prev) =>
prev.filter((m) =>
ids.has(m.id) || m.createdAt < from || m.createdAt > to
)
prev
.filter((m) =>
byId.has(m.id) || m.createdAt < from || m.createdAt > to
)
.map((m) => byId.get(m.id) ?? m)
);
// Failed sends that did land (only the echo was lost) are retired.
const mine = messages.filter((m) => m.userId === userIdRef.current);