Prevent sharing a diagram with yourself

RLS is the real guard (diagram_collaborators_insert/update now reject
user_id = the diagram's owner, regardless of who's performing the write —
covers a Super Admin acting on someone else's diagram too, not just the
normal owner path); the client-side check in
SupabaseDiagramCollaboratorRepository.add is just there to surface a
friendly message instead of the raw 42501.

Verified: tsc -b and oxlint clean; supabase db reset + 53/53 pgTAP tests
pass (1 new test).
This commit is contained in:
2026-09-11 11:42:07 -05:00
parent dea26f7ee8
commit 4b757e89f5
5 changed files with 55 additions and 4 deletions
@@ -11,6 +11,11 @@ export interface DiagramCollaborator {
* not a system failure. */
export class UnknownUsernameError extends Error {}
/** Thrown by `add` when the resolved username is the diagram owner's own
* account — RLS blocks this at the database level too (the real
* enforcement), this is just a friendlier message than the raw 42501. */
export class SelfCollaboratorError extends Error {}
/** Storage abstraction for a diagram's collaborator list, per
* organized-ideas.md §8: the owner shares with specific people by
* username, choosing view or edit access per person. RLS restricts
@@ -3,7 +3,7 @@ import type {
DiagramCollaborator,
DiagramCollaboratorRepository,
} from './DiagramCollaboratorRepository'
import { UnknownUsernameError } from './DiagramCollaboratorRepository'
import { SelfCollaboratorError, UnknownUsernameError } from './DiagramCollaboratorRepository'
import { supabase } from './supabaseClient'
interface CollaboratorRow {
@@ -43,6 +43,12 @@ export class SupabaseDiagramCollaboratorRepository implements DiagramCollaborato
if (!userId) {
throw new UnknownUsernameError(`No account found for username "${username}".`)
}
const {
data: { user: currentUser },
} = await supabase.auth.getUser()
if (currentUser && userId === currentUser.id) {
throw new SelfCollaboratorError("You already have full access to your own diagram — you can't share it with yourself.")
}
const { error } = await supabase.from('diagram_collaborators').insert({ diagram_id: diagramId, user_id: userId, permission })
if (error) {
console.error('Failed to add collaborator in Supabase', error)