security: access control for particles (#169)

* setup firebase custom token

* docs

* docs

* feat: allow admin removing members from a network

* fix: properly handle fallback avatar and names

This is especially helpful in the case of members who were removed from
a network
This commit was merged in pull request #169.
This commit is contained in:
Arjun Patel
2026-04-16 15:14:34 -07:00
committed by GitHub
parent 28b1ff542b
commit ef899ee5cd
36 changed files with 805 additions and 169 deletions
+11 -2
View File
@@ -5,6 +5,7 @@ import {
BillingStatusSchema,
CheckoutSessionResponseSchema,
DepotObjectSchema,
FirebaseTokenResponseSchema,
GetLivekitTokenResponseSchema,
HumanSchema,
ListInvitationsResponseSchema,
@@ -121,6 +122,14 @@ class ApiClient {
await this.requestVoid("POST", "/auth/sign-out");
}
async getFirebaseToken() {
return this.request(
FirebaseTokenResponseSchema,
"POST",
"/auth/firebase-token",
);
}
// TODO: security: require passing in the particle id once api deprecates this
async getParticleDownloadUrl(objectId: string): Promise<string> {
const response = await this.fetch(
@@ -183,10 +192,10 @@ class ApiClient {
);
}
async removeMember(networkId: string, email: string): Promise<void> {
async removeMember(networkId: string, humanId: string): Promise<void> {
await this.requestVoid(
"DELETE",
`/networks/${networkId}/members/${email}`,
`/networks/${networkId}/members/${humanId}`,
);
}
+5
View File
@@ -263,6 +263,11 @@ export const SignInResponseSchema = z.object({
});
export type SignInResponse = z.infer<typeof SignInResponseSchema>;
export const FirebaseTokenResponseSchema = z.object({
token: z.string(),
});
export type FirebaseTokenResponse = z.infer<typeof FirebaseTokenResponseSchema>;
// --- Billing types ---
export const BillingCadenceSchema = z.enum(["monthly", "annual"]);
+3 -3
View File
@@ -1,4 +1,5 @@
import type { Human } from "@/api/types";
import { resolveHumanDisplay } from "@/lib/humans";
import type { ComposingUser } from "@/features/particles/stream-presence-context";
interface ComposingIndicatorProps {
@@ -22,8 +23,7 @@ export function ComposingIndicator({
style={{ writingMode: "vertical-rl" }}
>
{users.map((u) => {
const human = networkHumans?.find((h) => h.id === u.humanId);
const name = human?.email_prefix ?? u.humanId;
const { displayName } = resolveHumanDisplay(u.humanId, networkHumans);
const modeLabel = u.mode === "typing" ? "typing" : "recording";
return (
@@ -37,7 +37,7 @@ export function ComposingIndicator({
<span className="size-1 rounded-full bg-white/70 animate-bounce [animation-delay:300ms]" />
</span>
<span className="whitespace-nowrap text-[10px] text-white/50">
{name} {modeLabel}
{displayName} {modeLabel}
</span>
</div>
);
@@ -0,0 +1,72 @@
import { useEffect } from "react";
import { createPortal } from "react-dom";
import { Button } from "@/components/ui/button";
interface ConfirmDestructiveOverlayProps {
title: string;
description: React.ReactNode;
confirmLabel: string;
pendingLabel?: string;
isPending: boolean;
onConfirm: () => void;
onClose: () => void;
}
export function ConfirmDestructiveOverlay({
title,
description,
confirmLabel,
pendingLabel = "Working…",
isPending,
onConfirm,
onClose,
}: ConfirmDestructiveOverlayProps) {
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
onClose();
}
};
window.addEventListener("keydown", handler, { capture: true });
return () => window.removeEventListener("keydown", handler, { capture: true });
}, [onClose]);
return createPortal(
<div className="fixed inset-0 z-[100]">
<div
className="absolute inset-0 bg-black/60 backdrop-blur-sm"
onClick={onClose}
/>
<div className="absolute left-1/2 top-1/2 w-full max-w-sm -translate-x-1/2 -translate-y-1/2 rounded-2xl border border-white/10 bg-white/5 p-6 shadow-2xl backdrop-blur-xl">
<div className="mb-3 flex items-center justify-between">
<h2 className="text-sm font-semibold text-white/70">{title}</h2>
<span className="text-xs text-white/30">
<kbd className="rounded bg-white/10 px-1.5 py-0.5 font-mono text-xs">
Esc
</kbd>{" "}
to close
</span>
</div>
<div className="text-sm text-white/60">{description}</div>
<div className="mt-5 flex items-center justify-end gap-2">
<Button variant="ghost" size="sm" onClick={onClose} disabled={isPending}>
Cancel
</Button>
<Button
variant="destructive"
size="sm"
onClick={onConfirm}
disabled={isPending}
>
{isPending ? pendingLabel : confirmLabel}
</Button>
</div>
</div>
</div>,
document.body,
);
}
+1 -1
View File
@@ -19,7 +19,7 @@ import { Input } from "@/components/ui/input";
import { ScrollArea } from "@/components/ui/scroll-area";
import { Separator } from "@/components/ui/separator";
import { useNetworks } from "@/hooks/use-networks";
import { useMyInvitations, useAcceptInvitation } from "@/hooks/use-invitations";
import { useMyInvitations, useAcceptInvitation } from "@/hooks/use-member-management";
import { apiClient } from "@/api/client";
import { Progress } from "@/components/ui/progress";
import type { Network, Invitation } from "@/api/types";
+78 -13
View File
@@ -15,12 +15,22 @@ import {
useNetworkInvitations,
useInviteMembers,
useRevokeInvitation,
} from "@/hooks/use-invitations";
useRemoveMember,
} from "@/hooks/use-member-management";
import { useAuthStore } from "@/stores/auth-store";
import { BillingSection } from "@/features/network-billing";
import { ConfirmDestructiveOverlay } from "@/components/confirm-destructive-overlay";
import type { Human } from "@/api/types";
function MemberRow({ human, isAdmin }: { human: Human; isAdmin: boolean }) {
function MemberRow({
human,
isAdmin,
onRemove,
}: {
human: Human;
isAdmin: boolean;
onRemove?: () => void;
}) {
const initials = human.email_prefix.slice(0, 2).toUpperCase();
return (
@@ -40,6 +50,17 @@ function MemberRow({ human, isAdmin }: { human: Human; isAdmin: boolean }) {
Admin
</Badge>
)}
{onRemove && (
<Button
variant="ghost"
size="icon-sm"
onClick={onRemove}
className="text-muted-foreground hover:text-destructive shrink-0"
aria-label={`Remove ${human.email}`}
>
<X className="size-3.5" />
</Button>
)}
</div>
);
}
@@ -170,6 +191,8 @@ export default function NetworkSettingsPage() {
const { data: invitations } = useNetworkInvitations(networkId!);
const currentUser = useAuthStore((s) => s.user);
const isAdmin = currentUser?.id === network?.admin_human.id;
const [memberToRemove, setMemberToRemove] = useState<Human | null>(null);
const removeMember = useRemoveMember(networkId!);
const billingRef = useRef<HTMLDivElement>(null);
@@ -228,17 +251,23 @@ export default function NetworkSettingsPage() {
}
/>
<Separator />
{network?.humans.map((human, index) => (
<div key={human.id}>
<MemberRow
human={human}
isAdmin={human.id === network.admin_human.id}
/>
{index < network.humans.length - 1 && (
<Separator className="mx-4" />
)}
</div>
))}
{network?.humans.map((human, index) => {
const isRowAdmin = human.id === network.admin_human.id;
const canRemove =
isAdmin && !isRowAdmin && human.id !== currentUser?.id;
return (
<div key={human.id}>
<MemberRow
human={human}
isAdmin={isRowAdmin}
onRemove={canRemove ? () => setMemberToRemove(human) : undefined}
/>
{index < network.humans.length - 1 && (
<Separator className="mx-4" />
)}
</div>
);
})}
</Section>
{isAdmin && network && (
@@ -299,6 +328,42 @@ export default function NetworkSettingsPage() {
<div className="h-6" />
</ScrollArea>
{memberToRemove && (
<ConfirmDestructiveOverlay
title={`Remove ${memberToRemove.email_prefix}?`}
description={
<ul className="list-disc space-y-1 pl-4">
<li>
They'll lose access to this network's streams and files within
seconds.
</li>
<li>Any content they posted stays in the network.</li>
<li>
If they're in a live huddle, they may remain until the call ends.
</li>
</ul>
}
confirmLabel="Remove"
pendingLabel="Removing…"
isPending={removeMember.isPending}
onConfirm={() => {
const target = memberToRemove;
removeMember.mutate(target.id, {
onSuccess: () => {
toast.success(`Removed ${target.email}`);
setMemberToRemove(null);
},
onError: (err) => {
toast.error(err.message || "Failed to remove member");
},
});
}}
onClose={() => {
if (!removeMember.isPending) setMemberToRemove(null);
}}
/>
)}
</div>
);
}
@@ -1,7 +1,6 @@
import { useCallback, useEffect, useState } from "react";
import { createPortal } from "react-dom";
import { useCallback, useState } from "react";
import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import { ConfirmDestructiveOverlay } from "@/components/confirm-destructive-overlay";
import { softDeleteParticle } from "@/lib/firestore-particles";
import { particlePath, toFirestoreDocPath } from "@/lib/particle-path";
import type { Particle } from "@/api/types";
@@ -40,55 +39,20 @@ export function DeleteParticleOverlay({
}
}, [deleting, networkId, onClose, particle.id, streamId, userId]);
useEffect(() => {
const handler = (e: KeyboardEvent) => {
if (e.key === "Escape") {
e.preventDefault();
e.stopPropagation();
onClose();
}
};
window.addEventListener("keydown", handler, { capture: true });
return () => window.removeEventListener("keydown", handler, { capture: true });
}, [onClose]);
return createPortal(
<div className="fixed inset-0 z-[100]">
<div
className="absolute inset-0 bg-black/60 backdrop-blur-sm"
onClick={onClose}
/>
<div className="absolute left-1/2 top-1/2 w-full max-w-sm -translate-x-1/2 -translate-y-1/2 rounded-2xl border border-white/10 bg-white/5 p-6 shadow-2xl backdrop-blur-xl">
<div className="mb-3 flex items-center justify-between">
<h2 className="text-sm font-semibold text-white/70">Delete this particle?</h2>
<span className="text-xs text-white/30">
<kbd className="rounded bg-white/10 px-1.5 py-0.5 font-mono text-xs">
Esc
</kbd>{" "}
to close
</span>
</div>
<p className="text-sm text-white/60">
return (
<ConfirmDestructiveOverlay
title="Delete this particle?"
description={
<p>
This cannot be undone. Other viewers will see a "This particle was
deleted" message in its place.
</p>
<div className="mt-5 flex items-center justify-end gap-2">
<Button variant="ghost" size="sm" onClick={onClose} disabled={deleting}>
Cancel
</Button>
<Button
variant="destructive"
size="sm"
onClick={handleDelete}
disabled={deleting}
>
{deleting ? "Deleting…" : "Delete"}
</Button>
</div>
</div>
</div>,
document.body,
}
confirmLabel="Delete"
pendingLabel="Deleting…"
isPending={deleting}
onConfirm={handleDelete}
onClose={onClose}
/>
);
}
@@ -2,6 +2,7 @@ import { useEffect } from "react";
import { Trash2 } from "lucide-react";
import type { Particle } from "@/api/types";
import { useNetwork } from "@/hooks/use-networks";
import { resolveHumanDisplay } from "@/lib/humans";
// How long to linger on a tombstone before auto-advancing. Matches the
// "reading" cadence of a short text particle.
@@ -24,8 +25,8 @@ export function DeletedParticleView({
const deleterId =
"deleted_by_human_id" in particle ? particle.deleted_by_human_id : undefined;
const deleter = deleterId
? network?.humans?.find((h) => h.id === deleterId)
: undefined;
? resolveHumanDisplay(deleterId, network?.humans)
: null;
useEffect(() => {
if (paused) return;
@@ -42,7 +43,7 @@ export function DeletedParticleView({
This particle was deleted
</p>
{deleter && (
<p className="text-white/40 text-xs">by {deleter.email_prefix}</p>
<p className="text-white/40 text-xs">by {deleter.displayName}</p>
)}
</div>
</div>
@@ -7,6 +7,8 @@ import {
CardTitle,
} from "@/components/ui/card";
import { FileIcon, HelpCircleIcon, ScrollTextIcon, BookOpenIcon } from "lucide-react";
import { useNetwork } from "@/hooks/use-networks";
import { resolveHumanDisplay } from "@/lib/humans";
const TYPE_META: Record<string, { icon: typeof FileIcon; label: string }> = {
quest: { icon: ScrollTextIcon, label: "Quest" },
@@ -16,9 +18,12 @@ const TYPE_META: Record<string, { icon: typeof FileIcon; label: string }> = {
interface FallbackParticleViewProps {
particle: Particle;
networkId: string;
}
export function FallbackParticleView({ particle }: FallbackParticleViewProps) {
export function FallbackParticleView({ particle, networkId }: FallbackParticleViewProps) {
const network = useNetwork(networkId);
const creator = resolveHumanDisplay(particle.created_by_human_id, network?.humans);
const meta = TYPE_META[particle.type] ?? {
icon: HelpCircleIcon,
label: particle.type,
@@ -51,7 +56,7 @@ export function FallbackParticleView({ particle }: FallbackParticleViewProps) {
</CardHeader>
<CardContent>
<p className="text-muted-foreground text-xs">
From {particle.created_by_human_id}
From {creator.displayName}
</p>
</CardContent>
</Card>
@@ -18,6 +18,7 @@ import { useLiveLatestChild } from "@/hooks/use-particle";
import { useAuthStore } from "@/stores/auth-store";
import { particlePath } from "@/lib/particle-path";
import { getInitials } from "@/lib/utils";
import { resolveHumanDisplay } from "@/lib/humans";
import { RelativeTimestamp } from "@/components/relative-timestamp";
import { Avatar, AvatarFallback } from "@/components/ui/avatar";
import { Separator } from "@/components/ui/separator";
@@ -174,9 +175,11 @@ const StreamRow = memo(function StreamRow({
}
// Group stream
if (isCurrentUser) return "You: ";
const creator = network?.humans?.find((h) => h.id === latestChild.created_by_human_id);
const name = creator?.email_prefix ?? latestChild.created_by_human_id;
const capitalized = name.charAt(0).toUpperCase() + name.slice(1);
const { displayName } = resolveHumanDisplay(
latestChild.created_by_human_id,
network?.humans,
);
const capitalized = displayName.charAt(0).toUpperCase() + displayName.slice(1);
return `${capitalized}: `;
}, [latestChild, userId, isDM, network]);
@@ -1,6 +1,10 @@
import { useParams } from "react-router-dom";
import { useEffect } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useQueryClient } from "@tanstack/react-query";
import { Lock } from "lucide-react";
import { useLiveParticle } from "@/hooks/use-particle";
import { particlePath } from "@/lib/particle-path";
import { Button } from "@/components/ui/button";
import { StreamView } from "@/features/particles/stream-view";
import { FolderView } from "@/features/particles/folder-view";
@@ -26,22 +30,11 @@ export default function ParticleViewResolver() {
);
}
if (error) {
return (
<div className="flex h-full items-center justify-center">
<p className="text-destructive text-sm">Failed to load particle</p>
</div>
);
}
if (!particle) {
return (
<div className="flex h-full items-center justify-center">
<p className="text-muted-foreground text-sm">
Particle: {segments.join(" / ")}
</p>
</div>
);
if (error || !particle) {
// Errors here are almost always Firestore permission-denied — the user lost
// access to the network or to a custom-visibility particle. The React Router
// stays on the dead route, so without an explicit escape the user is stuck.
return <InaccessibleParticle />;
}
switch (particle.type) {
@@ -59,3 +52,28 @@ export default function ParticleViewResolver() {
);
}
}
function InaccessibleParticle() {
const navigate = useNavigate();
const queryClient = useQueryClient();
useEffect(() => {
// Refresh the networks list so the home page reflects current access.
queryClient.invalidateQueries({ queryKey: ["networks"] });
}, [queryClient]);
return (
<div className="flex h-full flex-col items-center justify-center gap-4 p-8 text-center">
<Lock className="text-muted-foreground size-8" />
<div className="flex max-w-sm flex-col gap-1">
<p className="text-sm font-medium">This particle isn't available</p>
<p className="text-muted-foreground text-xs">
It may have been deleted, or your access was removed.
</p>
</div>
<Button size="sm" onClick={() => navigate("/", { replace: true })}>
Go home
</Button>
</div>
);
}
+2 -4
View File
@@ -3,6 +3,7 @@ import { Plus, X } from "lucide-react";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
import { REACTION_EMOJIS, type Reactions } from "@/api/types";
import { cn } from "@/lib/utils";
import { resolveHumanDisplay } from "@/lib/humans";
import type { Human } from "@/api/types";
interface ReactionBarProps {
@@ -17,10 +18,7 @@ function getReactorNames(
humans?: Human[],
): string {
return humanIds
.map((id) => {
const human = humans?.find((h) => h.id === id);
return human?.email_prefix ?? id;
})
.map((id) => resolveHumanDisplay(id, humans).displayName)
.join(", ");
}
@@ -12,6 +12,7 @@ import { updateParticleVisibleTo } from "@/lib/firestore-particles";
import { particlePath, toFirestoreDocPath } from "@/lib/particle-path";
import { useNetwork } from "@/hooks/use-networks";
import { cn, getInitials } from "@/lib/utils";
import { resolveHumanDisplay } from "@/lib/humans";
import type { Particle } from "@/api/types";
import { usePlaybackSuspenderStore } from "@/stores/playback-suspender-store";
@@ -158,7 +159,7 @@ export function StreamMembersOverlay({
<ScrollArea className="min-h-0 flex-1">
<ul className="flex flex-col gap-0.5 pr-2">
{memberIds.map((id) => {
const human = humans.find((h) => h.id === id);
const display = resolveHumanDisplay(id, humans);
const isCreatorRow = id === creatorId;
const canRemove =
isCreator && visibility.mode === "custom" && !isCreatorRow;
@@ -169,11 +170,16 @@ export function StreamMembersOverlay({
>
<Avatar size="sm">
<AvatarFallback className="text-[10px]">
{human ? getInitials(human.email) : "?"}
{display.initials}
</AvatarFallback>
</Avatar>
<span className="flex-1 truncate">
{human?.email_prefix ?? id}
<span
className={cn(
"flex-1 truncate",
!display.exists && "italic text-white/40",
)}
>
{display.displayName}
</span>
{isCreatorRow && (
<span className="text-[10px] uppercase tracking-wider text-white/30">
@@ -185,7 +191,7 @@ export function StreamMembersOverlay({
type="button"
onClick={() => removeMember(id)}
className="rounded p-1 text-white/30 opacity-0 transition-opacity hover:bg-white/10 hover:text-white/70 group-hover:opacity-100"
aria-label={`Remove ${human?.email_prefix ?? id}`}
aria-label={`Remove ${display.displayName}`}
>
<X className="size-3.5" />
</button>
+8 -11
View File
@@ -24,7 +24,7 @@ import { Breadcrumb, BreadcrumbItem, BreadcrumbList, BreadcrumbPage, BreadcrumbS
import { WindowControls } from "@/components/window-controls";
import { RelativeTimestamp } from "@/components/relative-timestamp";
import { useStreamPresence } from "@/features/particles/stream-presence-context";
import { getInitials } from "@/lib/utils";
import { resolveHumanDisplay } from "@/lib/humans";
function getParticleDisplayName(particle: Particle): string {
switch (particle.type) {
@@ -112,18 +112,17 @@ export function TopBar({ networkId, particle, streamParticle }: TopBarProps) {
</span>
<AvatarGroup>
{huddleParticipants.map((humanId) => {
const human = network?.humans?.find((h) => h.id === humanId);
const initials = human ? getInitials(human.email) : "?";
const display = resolveHumanDisplay(humanId, network?.humans);
return (
<Tooltip key={humanId}>
<TooltipTrigger asChild>
<Avatar size="sm">
<AvatarFallback className="bg-red-500/30 text-[8px] text-red-200">
{initials}
{display.initials}
</AvatarFallback>
</Avatar>
</TooltipTrigger>
<TooltipContent>{human?.email ?? humanId}</TooltipContent>
<TooltipContent>{display.email}</TooltipContent>
</Tooltip>
);
})}
@@ -267,7 +266,7 @@ function MembersIndicator({
{shownMembers.map((human) => (
<Avatar key={human.id} size="sm">
<AvatarFallback className="text-[8px]">
{getInitials(human.email)}
{resolveHumanDisplay(human.id, humans).initials}
</AvatarFallback>
</Avatar>
))}
@@ -289,19 +288,17 @@ function MembersIndicator({
function ParticleBreadcrumbContent({ particle, networkId }: { particle: Particle; networkId: string }) {
const network = useNetwork(networkId);
const { onlineHumanIds } = useStreamPresence();
const creator = network?.humans?.find((h) => h.id === particle.created_by_human_id);
const prefix = creator?.email_prefix ?? particle.created_by_human_id;
const initials = prefix.slice(0, 2).toUpperCase();
const display = resolveHumanDisplay(particle.created_by_human_id, network?.humans);
const isOnline = particle.created_by_human_id ? onlineHumanIds.has(particle.created_by_human_id) : false;
return (
<span className="flex items-center gap-1.5">
<Avatar size="sm" className={isOnline ? "ring-2 ring-green-500" : ""}>
<AvatarFallback>
{initials}
{display.initials}
</AvatarFallback>
</Avatar>
{prefix} - <RelativeTimestamp date={particle.created_at} />
{display.displayName} - <RelativeTimestamp date={particle.created_at} />
</span>
);
}
+1 -1
View File
@@ -405,7 +405,7 @@ function StreamViewInner({ path, streamParticle }: StreamViewProps) {
/>
);
default:
return <FallbackParticleView particle={particle} />;
return <FallbackParticleView particle={particle} networkId={networkId} />;
}
}
+3
View File
@@ -1,9 +1,12 @@
import { initializeApp } from 'firebase/app';
import { getAuth } from "firebase/auth";
import { getFirestore } from "firebase/firestore";
import { appConfig } from "@/config/env";
export const firebaseApp = initializeApp(appConfig.firebase);
export const firebaseAuth = getAuth(firebaseApp);
export const firestoreDb = getFirestore(firebaseApp);
// simplifying setup to debug production issues
// export const firestoreDb = initializeFirestore(firebaseApp,
@@ -50,3 +50,13 @@ export function useRevokeInvitation(networkId: string) {
},
});
}
export function useRemoveMember(networkId: string) {
const queryClient = useQueryClient();
return useMutation({
mutationFn: (humanId: string) => apiClient.removeMember(networkId, humanId),
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ["networks"] });
},
});
}
+7 -6
View File
@@ -4,7 +4,7 @@ import type { Network, Particle, StreamProperties } from "@/api/types";
import { apiClient } from "@/api/client";
import { useAuthStore } from "@/stores/auth-store";
import { useAutoplayStore } from "@/stores/autoplay-store";
import { getInitials } from "@/lib/utils";
import { resolveHumanDisplay } from "@/lib/humans";
/**
* Triggers autoplay when a stream's latest child changes to a new media particle.
@@ -44,9 +44,10 @@ export function useStreamAutoplay(
if (latestChild.type !== "media") return;
const particle = latestChild;
const creator = network?.humans?.find((h) => h.id === particle.created_by_human_id);
const senderName = creator?.email_prefix ?? particle.created_by_human_id;
const senderInitials = creator ? getInitials(creator.email) : particle.created_by_human_id.slice(0, 2).toUpperCase();
const { displayName, initials } = resolveHumanDisplay(
particle.created_by_human_id,
network?.humans,
);
apiClient.getParticleDownloadUrl(particle.properties.object_id).then((downloadUrl) => {
window.electronAutoplay.play({
@@ -56,8 +57,8 @@ export function useStreamAutoplay(
downloadUrl,
mimeType: particle.properties.mime_type,
durationMs: particle.properties.duration_ms,
senderName,
senderInitials,
senderName: displayName,
senderInitials: initials,
});
}).catch(() => {
// Failed to get download URL — skip autoplay silently
+43
View File
@@ -0,0 +1,43 @@
import type { Human } from "@/api/types";
import { getInitials } from "@/lib/utils";
export const REMOVED_MEMBER_LABEL = "Removed member";
export const REMOVED_MEMBER_INITIALS = "";
export interface HumanDisplay {
/** True when the human was found in the provided list. */
exists: boolean;
/** Short name for inline text (e.g. message sender). */
displayName: string;
/** Full email or fallback label for tooltips. */
email: string;
/** Initials for avatar fallback. */
initials: string;
}
/**
* Resolve a human's display info by id, falling back consistently when the
* human has been removed from the network. Member content (particles, reactions,
* etc.) is retained after removal, so every render path needs a graceful fallback
* instead of leaking raw ids into the UI.
*/
export function resolveHumanDisplay(
humanId: string | null | undefined,
humans: Human[] | undefined,
): HumanDisplay {
const human = humanId ? humans?.find((h) => h.id === humanId) : undefined;
if (!human) {
return {
exists: false,
displayName: REMOVED_MEMBER_LABEL,
email: REMOVED_MEMBER_LABEL,
initials: REMOVED_MEMBER_INITIALS,
};
}
return {
exists: true,
displayName: human.email_prefix,
email: human.email,
initials: getInitials(human.email),
};
}
+16
View File
@@ -1,8 +1,19 @@
import { create } from "zustand";
import { signInWithCustomToken, signOut as firebaseSignOut } from "firebase/auth";
import { apiClient, ApiError } from "@/api/client";
import type { Human } from "@/api/types";
import { firebaseAuth } from "@/firebase";
import { useSessionStore } from "./session-store";
async function signInToFirebase() {
try {
const { token } = await apiClient.getFirebaseToken();
await signInWithCustomToken(firebaseAuth, token);
} catch (e) {
console.error("Failed to sign in to Firebase", e);
}
}
type AuthStatus = "idle" | "restoring" | "unauthenticated" | "authenticated";
interface AuthState {
@@ -37,6 +48,7 @@ export const useAuthStore = create<AuthState>((set) => ({
set({ status: "restoring" });
try {
const user = await apiClient.me();
await signInToFirebase();
set({ status: "authenticated", user });
} catch {
useSessionStore.getState().clearToken();
@@ -63,6 +75,7 @@ export const useAuthStore = create<AuthState>((set) => ({
try {
const { human, token } = await apiClient.signIn({ email, code });
useSessionStore.getState().setToken(token);
await signInToFirebase();
set({ status: "authenticated", user: human });
} catch (e) {
const message =
@@ -81,6 +94,9 @@ export const useAuthStore = create<AuthState>((set) => ({
} catch {
// Best-effort — sign out locally regardless
} finally {
await firebaseSignOut(firebaseAuth).catch((e) =>
console.error("Firebase sign-out failed", e),
);
useSessionStore.getState().clearToken();
set({
status: "unauthenticated",