import type { Database } from 'bun:sqlite' import { error as logError } from '../../logger' import { getDb } from '../../db/sqlite' import { getMemoryRow, toMeta } from './store' import type { ListMemoriesFilter, MemoryMeta, MemoryRow } from './types' /** * Memory permissions — who can see and manage what. * * Single responsibility: authorization checks over the memories table and * team memberships. Two checks exist: * - visibility (read): personal = owner-only (strictly private — not even * system admins browse others' personal rows in listings), team = active * membership (admins bypass for team rows only). * - manage (edit/delete/promote): system admin, personal owner, team row * creator, or team owner/admin. * * listMemoriesForUser is the permission-filtered listing — filtering happens * BEFORE the row cap so results never leak cross-team rows. */ export function isTeamMember( db: Database, userId: string, teamId: string, ): boolean { const row = db .query( 'SELECT 1 FROM team_members WHERE team_id = $teamId AND user_id = $userId LIMIT 1', ) .get({ $teamId: teamId, $userId: userId }) return !!row } /** All team ids a user is an active member of — batch visibility input. */ function memberTeamIds(db: Database, userId: string): Set { const rows = db .query('SELECT team_id FROM team_members WHERE user_id = $userId') .all({ $userId: userId }) as unknown as { team_id: string }[] return new Set(rows.map(r => r.team_id)) } /** * Visibility check. Order (TDAM permission-checker pattern): * resource exists → personal: owner only (strictly private — admin listings * don't include others' personal rows, and the single-fetch path keeps the * same semantics for consistency) → team: active membership → deny. */ export function isMemoryVisibleToUser( id: string, userId: string, isAdmin = false, ): boolean { const db = getDb() const row = getMemoryRow(id) if (!row) return false if (row.scope_kind === 'personal') { return row.owner_user_id === userId } // Team scope — membership grants read; system admin too. if (isAdmin) return true return isTeamMember(db, userId, row.team_id!) } /** * Manage = edit/delete/promote. System admin, personal owner, * team row creator, or team owner/admin (managing other members' rows). */ export function canManageMemory( id: string, userId: string, isAdmin = false, ): boolean { const db = getDb() const row = getMemoryRow(id) if (!row) return false if (isAdmin) return true if (row.scope_kind === 'personal') { return row.owner_user_id === userId } if (row.created_by === userId) return true const member = db .query( `SELECT role FROM team_members WHERE team_id = $teamId AND user_id = $userId LIMIT 1`, ) .get({ $teamId: row.team_id!, $userId: userId }) as { role: string } | null return !!member && (member.role === 'owner' || member.role === 'admin') } /** * List memory ROWS (content included) visible to a user — the shared core * of listMemoriesForUser. Permission filtering happens BEFORE the row cap * so the result never leaks cross-team rows (caller-scoped lists, TDAM * lesson: filter first, then paginate). * * Admins see team rows across teams but never others' personal rows — * personal scope is owner-only by construction. */ export function listMemoryRowsForUser( userId: string, filter: ListMemoriesFilter = {}, isAdmin = false, ): MemoryRow[] { const db = getDb() const conditions: string[] = [`status != 'archived'`] const params: Record = {} if (filter.teamId) { conditions.push("scope_kind = 'team' AND team_id = $teamId") params.$teamId = filter.teamId } else if (filter.personalScope) { conditions.push("scope_kind = 'personal' AND owner_user_id = $userId") params.$userId = userId } if (filter.sessionId) { conditions.push('source_session_id = $sessionId') params.$sessionId = filter.sessionId } if (filter.type) { conditions.push('type = $type') params.$type = filter.type } let rows: MemoryRow[] = [] try { rows = db .query( `SELECT * FROM memories WHERE ${conditions.join(' AND ')} ORDER BY updated_at DESC LIMIT 500`, ) .all(params) as unknown as MemoryRow[] } catch (err) { logError('[memories] listMemoriesForUser failed:', err) return [] } if (isAdmin && !filter.personalScope) { return rows.filter(r => r.scope_kind === 'team') } // Batch visibility — same semantics as a per-row isMemoryVisibleToUser // (personal: owner-only; team: membership) with ONE membership query // instead of one SELECT per row. const teams = memberTeamIds(db, userId) return rows.filter(row => row.scope_kind === 'personal' ? row.owner_user_id === userId : teams.has(row.team_id!), ) } /** Meta-only variant of listMemoryRowsForUser (list UIs / pack filters). */ export function listMemoriesForUser( userId: string, filter: ListMemoriesFilter = {}, isAdmin = false, ): MemoryMeta[] { return listMemoryRowsForUser(userId, filter, isAdmin).map(toMeta) }