diff --git a/.impeccable/config.json b/.impeccable/config.json index 694b467c..89bc7700 100644 --- a/.impeccable/config.json +++ b/.impeccable/config.json @@ -146,6 +146,24 @@ ], "createdAt": "2026-09-16T16:56:10.062Z", "reason": "diagram-design skill editorial SVG system (matches docs/diagramas/fecha-limite-c4.html); static diagram annotations, not interactive UI; short zone labels (LEYENDA, GRP, USR, VAR, etc.), not body text" + }, + { + "rule": "undersized-ui-text", + "value": "*", + "files": [ + "docs/diagramas/compartir-tableros-c4.html" + ], + "createdAt": "2026-09-22T21:23:46.305Z", + "reason": "Claude: static SVG doc diagram copying the house style of the existing docs/diagramas/*-c4.html (e.g. limbo-c4.html, same 7-9px mono labels and caps zone titles)" + }, + { + "rule": "all-caps-body", + "value": "*", + "files": [ + "docs/diagramas/compartir-tableros-c4.html" + ], + "createdAt": "2026-09-22T21:23:46.682Z", + "reason": "Claude: static SVG doc diagram copying the house style of the existing docs/diagramas/*-c4.html (e.g. limbo-c4.html, same 7-9px mono labels and caps zone titles)" } ] } diff --git a/docs/arquitectura.md b/docs/arquitectura.md index a83ab377..61a68d67 100644 --- a/docs/arquitectura.md +++ b/docs/arquitectura.md @@ -41,7 +41,7 @@ Qué proceso corre dónde y cómo se hablan entre sí. sign-in, sign-up, sign-out, callback de GitHub, rate-limit nativo). - **Prisma ORM** — cliente generado en `web-app/generated/prisma`, adaptador `@prisma/adapter-pg` sobre `pg`. -- **PostgreSQL** — 10 modelos de dominio + `Account`/`Session`/`Verification`, +- **PostgreSQL** — 11 modelos de dominio + `Account`/`Session`/`Verification`, las tablas que exige Better Auth. ### Rutas (`web-app/app`) @@ -54,6 +54,7 @@ Qué proceso corre dónde y cómo se hablan entre sí. | `/time/[id]` | Registro de uso por sesiones | | `/settings`, `/settings/[id]` | Preferencias de usuario y de tablero | | `/auth/[[...id]]` | Login / registro | +| `/shared/[token]` | Tablero compartido en solo lectura para un Invitado (ver `features/compartir-tableros.md`) | | `/help` | Ayuda | --- diff --git a/docs/diagramas/compartir-tableros-c4.html b/docs/diagramas/compartir-tableros-c4.html new file mode 100644 index 00000000..3ba1dd22 --- /dev/null +++ b/docs/diagramas/compartir-tableros-c4.html @@ -0,0 +1,210 @@ + + + + + + Capo · Compartir tableros: componentes y funciones + + + + +
+

Arquitectura · C4 nivel 4 (código)

+

Compartir tableros: componentes y funciones

+ + + Código de la feature de compartir tableros con Invitados + SharedBoardView pide getSharedBoard por token; la server action resuelve el acceso con getShareAccess (público, o email que coincide con la sesión), aplica el rate limit por IP en modo público y devuelve el tablero sin notas (withoutNotes). El dueño gestiona los links desde ShareBoardDialog vía useBoardShares y las server actions de manageShares, que validan con assertCanAddEmailShare. SharedWithMe lista en el dashboard los tableros compartidos por email con la cuenta logueada. + + + + + + + + + + + + INVITADO: LECTURA POR TOKEN, SIN NOTAS + + + + DUEÑO: GESTIONAR LINKS (MENÚ → MODAL) + + + + DASHBOARD: COMPARTIDOS CONMIGO + + + + + + { token } + + + + + acceso · strip + + + + + usa + + + + + llama + + + + + assertCanAdd… + + + + + llama + + + + + + + UI + SharedBoardView + + /shared/[token] · tema del dueño + BlankTask + solo CopyTextButton + + + + + + API + getSharedBoard + + público: 60 vistas/IP/hora + readTaskBoard → withoutNotes + + + + + + MODEL + boardShare · rateLimit + + getShareAccess → ok|login|wrong|404 + withoutNotes · assertCanAddEmail… + createRateLimiter (Map en memoria) + + + + + + UI + ShareBoardDialog + + modal desde NavRail / HeaderNav + copiar · on/off · regenerar · quitar + + + + + + HOOK + useBoardShares + + key ['board-shares', boardId] + mutación → invalida la lista + + + + + + API + manageShares + + requireBoardAccess en cada acción + token = randomBytes(24) base64url + + + + + + UI + SharedWithMe + + BoardCard href=/shared/[token] + oculto si no hay compartidos + + + + + + API + getBoardsSharedWithMe + + EMAIL · active · email de sesión + excluye tableros propios + + + + LEYENDA + + + Entrada / lógica central + + + Componente · hook · API + + + Función de dominio + + + llama / produce + +
+ + diff --git a/docs/diagramas/compartir-tableros-c4.svg b/docs/diagramas/compartir-tableros-c4.svg new file mode 100644 index 00000000..a5dcc1c8 --- /dev/null +++ b/docs/diagramas/compartir-tableros-c4.svg @@ -0,0 +1,154 @@ + + + Código de la feature de compartir tableros con Invitados + SharedBoardView pide getSharedBoard por token; la server action resuelve el acceso con getShareAccess (público, o email que coincide con la sesión), aplica el rate limit por IP en modo público y devuelve el tablero sin notas (withoutNotes). El dueño gestiona los links desde ShareBoardDialog vía useBoardShares y las server actions de manageShares, que validan con assertCanAddEmailShare. SharedWithMe lista en el dashboard los tableros compartidos por email con la cuenta logueada. + + + + + + + + + + + + INVITADO: LECTURA POR TOKEN, SIN NOTAS + + + + DUEÑO: GESTIONAR LINKS (MENÚ → MODAL) + + + + DASHBOARD: COMPARTIDOS CONMIGO + + + + + + { token } + + + + + acceso · strip + + + + + usa + + + + + llama + + + + + assertCanAdd… + + + + + llama + + + + + + + UI + SharedBoardView + + /shared/[token] · tema del dueño + BlankTask + solo CopyTextButton + + + + + + API + getSharedBoard + + público: 60 vistas/IP/hora + readTaskBoard → withoutNotes + + + + + + MODEL + boardShare · rateLimit + + getShareAccess → ok|login|wrong|404 + withoutNotes · assertCanAddEmail… + createRateLimiter (Map en memoria) + + + + + + UI + ShareBoardDialog + + modal desde NavRail / HeaderNav + copiar · on/off · regenerar · quitar + + + + + + HOOK + useBoardShares + + key ['board-shares', boardId] + mutación → invalida la lista + + + + + + API + manageShares + + requireBoardAccess en cada acción + token = randomBytes(24) base64url + + + + + + UI + SharedWithMe + + BoardCard href=/shared/[token] + oculto si no hay compartidos + + + + + + API + getBoardsSharedWithMe + + EMAIL · active · email de sesión + excluye tableros propios + + + + LEYENDA + + + Entrada / lógica central + + + Componente · hook · API + + + Función de dominio + + + llama / produce + diff --git a/docs/diagramas/modelo-datos.html b/docs/diagramas/modelo-datos.html index f287230c..245205a5 100644 --- a/docs/diagramas/modelo-datos.html +++ b/docs/diagramas/modelo-datos.html @@ -54,7 +54,7 @@

Qué guarda Capo

Modelo de datos de Capo - Un usuario tiene varios tableros; cada tablero tiene columnas con tareas (que pueden tener sub-tareas, auto-relación por parentId) y, como accesorios uno a uno, una nota, un recordatorio, un archivo y un limbo; muchos tableros pueden apuntar al mismo grupo de etiquetas activo. Board y User referencian un Theme del catálogo de temas. TagVariant es un catálogo aparte: Tag.variant guarda su id dentro del Json de TagGroup.tags/Task.tags, sin FK real (línea punteada). + Un usuario tiene varios tableros; cada tablero tiene columnas con tareas (que pueden tener sub-tareas, auto-relación por parentId) y, como accesorios uno a uno, una nota, un recordatorio, un archivo y un limbo; muchos tableros pueden apuntar al mismo grupo de etiquetas activo. Board y User referencian un Theme del catálogo de temas. Un tablero tiene varios BoardShare, los links (por email o público) para compartirlo en solo lectura. TagVariant es un catálogo aparte: Tag.variant guarda su id dentro del Json de TagGroup.tags/Task.tags, sin FK real (línea punteada). @@ -114,6 +114,11 @@

Qué guarda Capo

1 0..1 + + + 1 + N + N @@ -249,6 +254,21 @@

Qué guarda Capo

text catálogo · Tag.variant lo referencia por id + + + + BoardShare + + SHR + + # id + mode : EMAIL | PUBLIC + token · unique + recipientEmail? + active · createdAt + → boardId + unique (boardId, recipientEmail) + diff --git a/docs/diagramas/modelo-datos.svg b/docs/diagramas/modelo-datos.svg index d3001131..3df17f29 100644 --- a/docs/diagramas/modelo-datos.svg +++ b/docs/diagramas/modelo-datos.svg @@ -1,7 +1,7 @@ Modelo de datos de Capo - Un usuario tiene varios tableros; cada tablero tiene columnas con tareas (que pueden tener sub-tareas, auto-relación por parentId) y, como accesorios uno a uno, una nota, un recordatorio, un archivo y un limbo; muchos tableros pueden apuntar al mismo grupo de etiquetas activo. Board y User referencian un Theme del catálogo de temas. TagVariant es un catálogo aparte: Tag.variant guarda su id dentro del Json de TagGroup.tags/Task.tags, sin FK real (línea punteada). + Un usuario tiene varios tableros; cada tablero tiene columnas con tareas (que pueden tener sub-tareas, auto-relación por parentId) y, como accesorios uno a uno, una nota, un recordatorio, un archivo y un limbo; muchos tableros pueden apuntar al mismo grupo de etiquetas activo. Board y User referencian un Theme del catálogo de temas. Un tablero tiene varios BoardShare, los links (por email o público) para compartirlo en solo lectura. TagVariant es un catálogo aparte: Tag.variant guarda su id dentro del Json de TagGroup.tags/Task.tags, sin FK real (línea punteada). @@ -62,6 +62,11 @@ 1 0..1 + + + 1 + N + N @@ -197,6 +202,21 @@ text catálogo · Tag.variant lo referencia por id + + + + BoardShare + + SHR + + # id + mode : EMAIL | PUBLIC + token · unique + recipientEmail? + active · createdAt + → boardId + unique (boardId, recipientEmail) + diff --git a/docs/features/compartir-tableros.md b/docs/features/compartir-tableros.md new file mode 100644 index 00000000..b5a913c5 --- /dev/null +++ b/docs/features/compartir-tableros.md @@ -0,0 +1,82 @@ +# Compartir tableros con Invitados + +## Resumen + +El dueño de un tablero lo comparte **completo y en solo lectura** con un **Invitado**: con un link público (cualquiera con el link) o con hasta 4 emails (solo quien inicie sesión con ese email). El Invitado ve todas las tareas en el mismo orden y columnas, **sin notas**, y solo puede copiar el texto de cada tarea. + +> **"Invitado" ≠ "modo invitado".** Acá "Invitado" es quien _ve_ un tablero ajeno. El "modo invitado" es el usuario sin cuenta, con datos en `localStorage` (`GUEST_CUSTOM_TAG_GROUP_ID`, repositorios `localStorage*`, `userId ?? 'guest'`). + +- **Código:** `web-app/src/features/board-share/` + `app/shared/[token]/`, `src/features/dashboard/ui/SharedWithMe.tsx`, `app/_components/` (item "Compartir tablero" en `NavRail` y `HeaderNav`, `getShareLink` en `navLinks.ts`), `src/features/tasks/api/readTaskBoard.ts`, `serverAuth.getSessionUser`. +- **Alcance:** link público, invitaciones por email, activar/desactivar, regenerar link, quitar invitado, "Compartidos conmigo" en el dashboard. +- **Fuera de alcance:** envío real de emails (sin SMTP), expiración automática, que el dueño elija si el Invitado ve las notas (hoy nunca las ve), escritura. + +## Diagrama C4 — código + +![Diagrama C4 (código) de compartir tableros](../diagramas/compartir-tableros-c4.svg) + +(fuente editable: `docs/diagramas/compartir-tableros-c4.html`; re-exportar el `.svg` tras editar el `.html`). + +- `SharedBoardView` — la página del Invitado. Pide el tablero por token, muestra el estado (login requerido, cuenta equivocada, link inexistente, rate limit) o el tablero con el tema del dueño. +- `ReadOnlyBoard` — el tablero de solo lectura que muestra `SharedBoardView`. Arma las `Column` y pinta cada tarea con `ReadOnlyTask`. +- `ReadOnlyTask` — una tarea de solo lectura: `BlankTask` cuya única acción es `CopyTextButton` dentro de un `KebabMenu`, igual que en el tablero. +- `getSharedBoard` — única puerta de lectura para el Invitado: resuelve el acceso, limita vistas públicas y nunca devuelve notas. +- `ShareBoardDialog` + `useBoardShares` + `manageShares` — gestión del dueño, en un modal que se abre desde el menú (NavRail en escritorio, dropdown de HeaderNav en mobile). El panel solo se monta con el modal abierto, así los links no se piden en cada página. +- `SharedWithMe` + `getBoardsSharedWithMe` — el tablero aparece solo en el dashboard de la cuenta invitada, sin necesitar el link. + +## Modelo / lógica + +`model/boardShare.ts` (test: `model/boardShare.test.ts`): + +- `getShareAccess(share, viewerEmail) → 'ok' | 'not-found' | 'login-required' | 'wrong-account'`. + Inexistente e inactivo dan igual `not-found` (no revela que el link existió). + Público → `ok` sin login. Email → compara con `normalizeEmail` (trim + lower). +- `assertCanAddEmailShare(shares, email)` — `BusinessError` si el email es + inválido, ya está invitado o ya hay `MAX_EMAIL_SHARES = 4` de modo email (el + público no cuenta). Corre en el cliente (para el toast) y en el server. +- `withoutNotes(taskBoard)` — saca `notesAndComments` de cada tarea. Se aplica + en el server: las notas nunca viajan al Invitado. + +`model/rateLimit.ts` (test: `model/rateLimit.test.ts`): +`createRateLimiter({ max, windowMs }) → (key, now?) => boolean`, ventana fija por clave en un `Map`. `getSharedBoard` lo usa con 60 vistas por IP por hora, solo en modo público. IP: ver Tips/historia. + +Server actions (`api/actions/`): + +- `getSharedBoard({ token })` → `{ status: 'ok', boardName, theme, taskBoard }` o `{ status }`. Test: `getSharedBoard.test.ts`. +- `manageShares.ts`: `getBoardShares`, `addEmailShare`, `enablePublicShare` (crea el único link público o lo reactiva), `setShareActive` (no toca el token → reactivar = mismo link), `regenerateShareToken` (token nuevo en la misma fila), `deleteShare`. Todas pasan por `requireBoardAccess(boardId)` y filtran por `{ id: shareId, boardId }`. +- `getBoardsSharedWithMe()` — shares `EMAIL` + activos del email de la sesión, excluyendo tableros propios. + +## Persistencia y modelo + +- Tipo TS: `BoardShare` en `model/boardShare.ts`. +- Prisma: `model BoardShare` (`boardId`, `mode: ShareMode` = `EMAIL | PUBLIC`, + `token @unique`, `recipientEmail?`, `active @default(true)`, `createdAt`), + `@@unique([boardId, recipientEmail])`, `@@index([recipientEmail])`, + cascada con `Board`. Migración: + `prisma/migrations/20260922120000_board_share/`. La corre el usuario. +- El límite 4 email + 1 público se valida en app (la DB solo impide emails + repetidos por tablero; en Postgres los `NULL` no chocan en el unique). +- Lectura del tablero: `readTaskBoard(boardId)` (sin chequeo de acceso, + `server-only`), compartido con `getTaskBoard` para que el Invitado vea + exactamente el mismo orden que el dueño. + +## i18next + +- `share.*` — modal de compartir (títulos, botones, toasts); `share.section_title` + es también el label del item del menú. + `share.email_title` interpola `{{count}}/{{max}}`. +- `shared_board.*` — estados de la vista del Invitado. +- `dashboard.shared_with_me`. +- Archivos: `src/shared/i18n/es.json` y `en.json`. + +## Tips / historia + +- **Riesgo conocido: emails sin verificar.** El registro por email/password no verifica el email (sin SMTP). Si la cuenta invitada todavía no existe, cualquiera que tenga el link puede registrarse con ese email y ver el tablero. + Aceptado en este corte; el arreglo es exigir `emailVerified` cuando haya envío de mails. +- El rate limit vive en memoria del proceso: en serverless cada instancia cuenta por su lado y se resetea con cada deploy. Pasar a tabla si hace falta un límite global. +- IP del rate limit: `x-nf-client-connection-ip` (Netlify) → `x-real-ip` (Vercel) → primer valor de `x-forwarded-for`. Ese último lo controla el cliente, así que fuera de esas plataformas el límite es burlable. +- Los límites (4 email / 1 público) son leer-y-crear sin transacción: dos requests simultáneos pueden pasarse del límite (p.ej. doble click en "crear link público"; la UI deshabilita el botón mientras hay una mutación en curso). + Un unique parcial (`WHERE mode = 'PUBLIC'`) no se puede expresar en el schema Prisma sin que `migrate dev` lo vea como drift; se aceptó el riesgo. +- "Quitar invitado" (`deleteShare`) no estaba en la spec: sin él, los 4 cupos de email quedarían ocupados para siempre. +- La vista del Invitado no hace polling ni refetch al enfocar: cada fetch cuenta para el rate limit del link público. +- Tras loguearse desde el link de email, el usuario cae en el dashboard (el middleware manda `/auth` → `/dashboard`), donde el tablero aparece en "Compartidos conmigo". No hay redirect de vuelta al link. +- `/shared/*` lleva `robots: noindex` (el token es la credencial). diff --git a/docs/modelo-datos.md b/docs/modelo-datos.md index 36051d1e..ce69bd20 100644 --- a/docs/modelo-datos.md +++ b/docs/modelo-datos.md @@ -27,6 +27,23 @@ Esquema Prisma (`web-app/prisma/schema.prisma`), provider `postgresql`. - Campos `Json` (`tags`, `timelineHistory`, `usageHistory`, `taskList`, …) guardan estructuras que no necesitan consultarse por separado. - **`Board.currentSession{Start,End,Duration,Day}`** (`BigInt?`/`Int?`, los 4 juntos: los 4 `null` o los 4 con valor) son la sesión de uso **abierta** del tablero — separada de `usageHistory` a propósito, para poder incrementarla de forma atómica (`{ increment }` de Prisma) sin reescribir el JSON en cada guardado. Se vuelca a `usageHistory` recién al cerrar (gap de actividad o cambio de día). Detalle en [`docs/features/usage-history.md`](./features/usage-history.md). +- **`BoardShare`** son los links para que un Invitado vea el tablero en solo + lectura. Campos: `boardId`, `mode` (enum `ShareMode` = `EMAIL | PUBLIC`), + `token` (`@unique`, es la credencial del link), `recipientEmail?` (solo en + modo `EMAIL`), `active` (`@default(true)`; desactivar no cambia el token, así + que reactivar devuelve el mismo link) y `createdAt`. Se borra en cascada con + el tablero. + - `@@unique([boardId, recipientEmail])`: no se repite un email por tablero. + En Postgres los `NULL` no chocan en el unique, así que la fila `PUBLIC` no + choca con ninguna. + - `@@index([recipientEmail])`: para "Compartidos conmigo", que busca las filas + `EMAIL` activas por el email de la sesión. + - El tope de 4 filas `EMAIL` + 1 `PUBLIC` por tablero se valida en la app + (`assertCanAddEmailShare`), no en la DB. + - Las notas (`notesAndComments`) nunca se le mandan al Invitado: el server las + saca antes de responder. + - Migración: `prisma/migrations/20260922120000_board_share/`. Detalle en + [`docs/features/compartir-tableros.md`](./features/compartir-tableros.md). - **`Task.dueDate`** (`String?`, `YYYY-MM-DD` sin hora) es la fecha límite opcional de la tarea; se setea solo al crearla. - `Account`, `Session` y `Verification` son las tablas que pide el @@ -34,7 +51,9 @@ Esquema Prisma (`web-app/prisma/schema.prisma`), provider `postgresql`. El modo invitado replica estas mismas formas en `localStorage`, una clave por feature. Excepción: el tema es uno solo y global (`capo-theme`), no hay tema por -tablero ni catálogo para invitados. +tablero ni catálogo para invitados. `BoardShare` tampoco tiene versión en +`localStorage`: compartir exige cuenta. (Ojo: el "modo invitado" es el usuario +sin cuenta; el "Invitado" de `BoardShare` es quien ve un tablero ajeno). --- diff --git a/web-app/app/_components/HeaderNav/HeaderNav.tsx b/web-app/app/_components/HeaderNav/HeaderNav.tsx index 6933c200..91efe25b 100644 --- a/web-app/app/_components/HeaderNav/HeaderNav.tsx +++ b/web-app/app/_components/HeaderNav/HeaderNav.tsx @@ -26,9 +26,11 @@ import { getLoginLink, getLogoutLink, getSettingsLink, + getShareLink, type LinkItem, } from '../navLinks' import { DropdownLink } from './DropdownLink' +import { ShareBoardDialog } from '@/features/board-share' interface HeaderNavItemsParams { t: TFunction @@ -40,6 +42,7 @@ interface HeaderNavItemsParams { session: boolean toggleLanguage: () => void onLogout: () => void + onShare: () => void } /** Lista completa de items del dropdown de HeaderNav, en orden de render. */ @@ -52,11 +55,13 @@ function getHeaderNavItems({ session, toggleLanguage, onLogout, + onShare, }: HeaderNavItemsParams): LinkItem[] { const [firstLink, ...restLinks] = showBoardLinks ? getCoreNavLinks({ t, boardId, whereUserIs, duration }) : [getSettingsLink(t, whereUserIs)] const mainLinks = [{ ...firstLink, group: true }, ...restLinks] + if (session && showBoardLinks) mainLinks.push(getShareLink(t, onShare)) const authItem: LinkItem = session ? getLogoutLink(t, onLogout) @@ -89,6 +94,7 @@ export function HeaderNav({ whereUserIs, showBoardLinks }: HeaderNavProps) { const logout = useLogout() const [isDropdownOpen, setIsDropdownOpen] = useState(false) + const [isShareOpen, setIsShareOpen] = useState(false) const documentVisible = useVisibilityChange() const isVisible = isDropdownOpen && documentVisible @@ -105,26 +111,37 @@ export function HeaderNav({ whereUserIs, showBoardLinks }: HeaderNavProps) { session: !!session, toggleLanguage, onLogout: logout, + onShare: () => setIsShareOpen(true), }) return ( - - - - - - {APP_NAME} - {items.map((item) => ( - - ))} - - + <> + + + + + + {APP_NAME} + {items.map((item) => ( + + ))} + + + + {session && ( + + )} + ) } diff --git a/web-app/app/_components/NavRail/NavRail.tsx b/web-app/app/_components/NavRail/NavRail.tsx index 55b95c21..c0244623 100644 --- a/web-app/app/_components/NavRail/NavRail.tsx +++ b/web-app/app/_components/NavRail/NavRail.tsx @@ -16,6 +16,7 @@ import { getNavRailItems } from './getNavRailItems' import { getNavRailStageClassName } from './navRailStageClassName' import { useNearEdge } from './useNearEdge' import { useNavRailDuration } from './useNavRailDuration' +import { ShareBoardDialog } from '@/features/board-share' interface NavRailProps { whereUserIs?: USER_IS_IN @@ -39,11 +40,12 @@ export function NavRail({ whereUserIs }: NavRailProps) { const near = useNearEdge(side) const [active, setActive] = useState(false) + const [isShareOpen, setIsShareOpen] = useState(false) const duration = useNavRailDuration(active) const toggleLanguage = useLanguageToggle() - const items = getNavRailItems({ t, boardId, whereUserIs, duration, session: !!session, toggleLanguage }) + const items = getNavRailItems({ t, boardId, whereUserIs, duration, session: !!session, toggleLanguage, onShare: () => setIsShareOpen(true) }) const isRight = side === 'right' @@ -76,6 +78,9 @@ export function NavRail({ whereUserIs }: NavRailProps) { ))} + {session && ( + + )} ) } diff --git a/web-app/app/_components/NavRail/getNavRailItems.ts b/web-app/app/_components/NavRail/getNavRailItems.ts index 2a3a69b3..4721c232 100644 --- a/web-app/app/_components/NavRail/getNavRailItems.ts +++ b/web-app/app/_components/NavRail/getNavRailItems.ts @@ -1,6 +1,6 @@ import type { TFunction } from 'i18next' import { USER_IS_IN } from '@/shared/ui/organisms/userIsIn' -import { getCoreNavLinks, getHomeLink, getLanguageLink, getLoginLink, type LinkItem } from '../navLinks' +import { getCoreNavLinks, getHomeLink, getLanguageLink, getLoginLink, getShareLink, type LinkItem } from '../navLinks' interface NavRailItemsParams { t: TFunction @@ -9,14 +9,16 @@ interface NavRailItemsParams { duration: string session: boolean toggleLanguage: () => void + onShare: () => void } /** Lista de items del NavRail, en orden de render. */ -export function getNavRailItems({ t, boardId, whereUserIs, duration, session, toggleLanguage }: NavRailItemsParams): LinkItem[] { +export function getNavRailItems({ t, boardId, whereUserIs, duration, session, toggleLanguage, onShare }: NavRailItemsParams): LinkItem[] { const [firstLink, ...restLinks] = getCoreNavLinks({ t, boardId, whereUserIs, duration }) const items: LinkItem[] = [{ ...firstLink, group: true }, ...restLinks] if (session) { + items.push(getShareLink(t, onShare)) items.unshift(getHomeLink(t)) } else { items.push(getLanguageLink(t, toggleLanguage)) diff --git a/web-app/app/_components/navLinks.ts b/web-app/app/_components/navLinks.ts index ed5915b2..1d93dc2e 100644 --- a/web-app/app/_components/navLinks.ts +++ b/web-app/app/_components/navLinks.ts @@ -7,6 +7,7 @@ import { HourglassIcon, IconProps, LanguagesIcon, + GlobeIcon, LogInIcon, LogOutIcon, SettingsIcon, @@ -137,3 +138,7 @@ export function getLogoutLink(t: TFunction, onClick: () => void): LinkItem { export function getLanguageLink(t: TFunction, onClick: () => void): LinkItem { return { key: 'language', icon: LanguagesIcon, label: t('menu.language'), onClick } } + +export function getShareLink(t: TFunction, onClick: () => void): LinkItem { + return { key: 'share', icon: GlobeIcon, label: t('share.section_title'), onClick } +} diff --git a/web-app/app/home/Home.tsx b/web-app/app/home/Home.tsx index 5b383ef2..03464678 100644 --- a/web-app/app/home/Home.tsx +++ b/web-app/app/home/Home.tsx @@ -308,9 +308,11 @@ export function Home({ stars }: { stars?: number } = {}) { return (
- - - +
+ + + +
diff --git a/web-app/app/shared/[token]/page.tsx b/web-app/app/shared/[token]/page.tsx new file mode 100644 index 00000000..2518a0df --- /dev/null +++ b/web-app/app/shared/[token]/page.tsx @@ -0,0 +1,13 @@ +import type { Metadata } from 'next' +import { SharedBoardView } from '@/features/board-share' + +export const metadata: Metadata = { robots: { index: false, follow: false } } + +interface Props { + params: Promise<{ token: string }> +} + +export default async function SharedBoardRoute({ params }: Props) { + const { token } = await params + return +} diff --git a/web-app/prisma/migrations/20260922120000_board_share/migration.sql b/web-app/prisma/migrations/20260922120000_board_share/migration.sql new file mode 100644 index 00000000..46540df8 --- /dev/null +++ b/web-app/prisma/migrations/20260922120000_board_share/migration.sql @@ -0,0 +1,27 @@ +-- CreateEnum +CREATE TYPE "ShareMode" AS ENUM ('EMAIL', 'PUBLIC'); + +-- CreateTable +CREATE TABLE "BoardShare" ( + "id" TEXT NOT NULL, + "boardId" TEXT NOT NULL, + "mode" "ShareMode" NOT NULL, + "token" TEXT NOT NULL, + "recipientEmail" TEXT, + "active" BOOLEAN NOT NULL DEFAULT true, + "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP, + + CONSTRAINT "BoardShare_pkey" PRIMARY KEY ("id") +); + +-- CreateIndex +CREATE UNIQUE INDEX "BoardShare_token_key" ON "BoardShare"("token"); + +-- CreateIndex +CREATE INDEX "BoardShare_recipientEmail_idx" ON "BoardShare"("recipientEmail"); + +-- CreateIndex +CREATE UNIQUE INDEX "BoardShare_boardId_recipientEmail_key" ON "BoardShare"("boardId", "recipientEmail"); + +-- AddForeignKey +ALTER TABLE "BoardShare" ADD CONSTRAINT "BoardShare_boardId_fkey" FOREIGN KEY ("boardId") REFERENCES "Board"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/web-app/prisma/schema.prisma b/web-app/prisma/schema.prisma index 2b3a125f..ccd7d884 100644 --- a/web-app/prisma/schema.prisma +++ b/web-app/prisma/schema.prisma @@ -39,6 +39,7 @@ model Board { reminders Reminder? archive Archive? limbo Limbo? + shares BoardShare[] usageHistory Json @default("[]") currentSessionStart BigInt? @@ -94,6 +95,27 @@ model Task { createdAt DateTime @default(now()) } +enum ShareMode { + EMAIL + PUBLIC +} + +// Link para que un "Invitado" vea el tablero en solo lectura. +// Hasta 4 filas EMAIL + 1 PUBLIC por tablero (se valida en app, ver features/board-share). +model BoardShare { + id String @id @default(cuid()) + boardId String + board Board @relation(fields: [boardId], references: [id], onDelete: Cascade) + mode ShareMode + token String @unique + recipientEmail String? + active Boolean @default(true) + createdAt DateTime @default(now()) + + @@unique([boardId, recipientEmail]) + @@index([recipientEmail]) +} + model Note { id String @id @default(cuid()) content String @default("") diff --git a/web-app/src/features/board-share/api/actions/getBoardsSharedWithMe.ts b/web-app/src/features/board-share/api/actions/getBoardsSharedWithMe.ts new file mode 100644 index 00000000..10afb2e4 --- /dev/null +++ b/web-app/src/features/board-share/api/actions/getBoardsSharedWithMe.ts @@ -0,0 +1,34 @@ +'use server' + +import { prisma } from '@/shared/lib/prisma' +import { getSessionUser } from '@/shared/lib/serverAuth' +import { normalizeEmail } from '../../model/boardShare' + +export interface SharedWithMeBoard { + token: string + name: string + cardCanvas: number + themeId: string +} + +/** Tableros compartidos por email con la cuenta logueada (aparecen sin necesitar el link). */ +export async function getBoardsSharedWithMe(): Promise { + const user = await getSessionUser() + if (!user?.email) return [] + + const shares = await prisma.boardShare.findMany({ + where: { + mode: 'EMAIL', + active: true, + recipientEmail: normalizeEmail(user.email), + board: { userId: { not: user.id } }, + }, + orderBy: { createdAt: 'asc' }, + select: { + token: true, + board: { select: { name: true, cardCanvas: true, themeId: true } }, + }, + }) + + return shares.map(({ token, board }) => ({ token, ...board })) +} diff --git a/web-app/src/features/board-share/api/actions/getSharedBoard.test.ts b/web-app/src/features/board-share/api/actions/getSharedBoard.test.ts new file mode 100644 index 00000000..87fe7243 --- /dev/null +++ b/web-app/src/features/board-share/api/actions/getSharedBoard.test.ts @@ -0,0 +1,66 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest' +import { getSharedBoard } from './getSharedBoard' +import { prisma } from '@/shared/lib/prisma' +import { getSessionUser } from '@/shared/lib/serverAuth' + +vi.mock('next/headers', () => ({ + headers: async () => new Headers({ 'x-forwarded-for': '1.1.1.1, 10.0.0.1' }), +})) +vi.mock('@/shared/lib/serverAuth', () => ({ getSessionUser: vi.fn() })) +vi.mock('@/shared/lib/prisma', () => ({ prisma: { boardShare: { findUnique: vi.fn() } } })) +vi.mock('@/features/tasks/api/readTaskBoard', () => ({ + readTaskBoard: vi.fn().mockResolvedValue([ + { + id: 'c1', + status: 'Todo', + tasks: [{ id: 't1', descriptionText: 'a', notesAndComments: 'secreto' }], + }, + ]), +})) + +const theme = { id: 'retro', bg: 'bg', task: 'task', column: 'col', text: 'txt' } +const row = (over = {}) => ({ + mode: 'EMAIL', + recipientEmail: 'ana@mail.com', + active: true, + board: { id: 'b1', name: 'Mi tablero', theme }, + ...over, +}) + +describe('getSharedBoard (server action)', () => { + beforeEach(() => { + vi.mocked(getSessionUser).mockReset() + vi.mocked(prisma.boardShare.findUnique).mockReset() + }) + + it('email: sin login no devuelve nada del tablero', async () => { + vi.mocked(prisma.boardShare.findUnique).mockResolvedValue(row() as never) + vi.mocked(getSessionUser).mockResolvedValue(null) + + expect(await getSharedBoard({ token: 'tok' })).toEqual({ status: 'login-required' }) + }) + + it('email: con la cuenta invitada devuelve el tablero sin notas', async () => { + vi.mocked(prisma.boardShare.findUnique).mockResolvedValue(row() as never) + vi.mocked(getSessionUser).mockResolvedValue({ email: 'ana@mail.com' } as never) + + expect(await getSharedBoard({ token: 'tok' })).toEqual({ + status: 'ok', + boardName: 'Mi tablero', + theme, + taskBoard: [{ id: 'c1', status: 'Todo', tasks: [{ id: 't1', descriptionText: 'a' }] }], + }) + }) + + it('público: corta en la vista 61 de la misma IP', async () => { + vi.mocked(prisma.boardShare.findUnique).mockResolvedValue( + row({ mode: 'PUBLIC', recipientEmail: null }) as never + ) + vi.mocked(getSessionUser).mockResolvedValue(null) + + for (let i = 0; i < 60; i++) { + expect((await getSharedBoard({ token: 'tok' })).status).toBe('ok') + } + expect(await getSharedBoard({ token: 'tok' })).toEqual({ status: 'rate-limited' }) + }) +}) diff --git a/web-app/src/features/board-share/api/actions/getSharedBoard.ts b/web-app/src/features/board-share/api/actions/getSharedBoard.ts new file mode 100644 index 00000000..51279cf1 --- /dev/null +++ b/web-app/src/features/board-share/api/actions/getSharedBoard.ts @@ -0,0 +1,76 @@ +'use server' + +import { headers } from 'next/headers' +import { prisma } from '@/shared/lib/prisma' +import { getSessionUser } from '@/shared/lib/serverAuth' +import { readTaskBoard } from '@/features/tasks/api/readTaskBoard' +import type { TaskBoard } from '@/features/tasks/model/taskBoard' +import type { Theme } from '@/shared/preferences/theme' +import { getShareAccess, withoutNotes, type ShareAccess } from '../../model/boardShare' +import { createRateLimiter } from '../../model/rateLimit' + +const hitPublicView = createRateLimiter({ max: 60, windowMs: 60 * 60 * 1000 }) + +export type SharedBoardResult = + | { status: Exclude | 'rate-limited' } + | { status: 'ok'; boardName: string; theme: Theme; taskBoard: TaskBoard } + +/** Vista de solo lectura para el Invitado. Público no requiere login; email sí. */ +export async function getSharedBoard({ token }: { token: string }): Promise { + const share = await prisma.boardShare.findUnique({ + where: { token }, + select: { + mode: true, + recipientEmail: true, + active: true, + board: { + select: { + id: true, + name: true, + theme: { + select: { + id: true, + bg: true, + task: true, + column: true, + text: true, + taskText: true, + columnText: true, + reminder: true, + }, + }, + }, + }, + }, + }) + + const viewer = share?.mode === 'EMAIL' ? await getSessionUser() : null + const access = getShareAccess(share, viewer?.email) + if (access !== 'ok') return { status: access } + if (!share) return { status: 'not-found' } // inalcanzable: solo narrowing para TS + + if (share.mode === 'PUBLIC') { + // IP que setea la plataforma (Netlify / Vercel), no falsificable por el cliente. + // El primer valor de x-forwarded-for sí lo controla el cliente: último recurso. + const h = await headers() + const ip = + h.get('x-nf-client-connection-ip') ?? + h.get('x-real-ip') ?? + (h.get('x-forwarded-for')?.split(',')[0].trim() || 'unknown') + if (!hitPublicView(ip)) return { status: 'rate-limited' } + } + + const { theme } = share.board + return { + status: 'ok', + boardName: share.board.name, + // Prisma devuelve `null` en los opcionales; `Theme` los quiere `undefined` (igual que getThemes). + theme: { + ...theme, + taskText: theme.taskText ?? undefined, + columnText: theme.columnText ?? undefined, + reminder: theme.reminder ?? undefined, + }, + taskBoard: withoutNotes(await readTaskBoard(share.board.id)), + } +} diff --git a/web-app/src/features/board-share/api/actions/manageShares.ts b/web-app/src/features/board-share/api/actions/manageShares.ts new file mode 100644 index 00000000..c99d9406 --- /dev/null +++ b/web-app/src/features/board-share/api/actions/manageShares.ts @@ -0,0 +1,72 @@ +'use server' + +import { randomBytes } from 'node:crypto' +import { prisma } from '@/shared/lib/prisma' +import { requireBoardAccess } from '@/shared/lib/serverAuth' +import { assertCanAddEmailShare, normalizeEmail, type BoardShare } from '../../model/boardShare' + +/* Acciones del dueño del tablero sobre sus links compartidos. */ + +const newToken = () => randomBytes(24).toString('base64url') + +const shareSelect = { id: true, mode: true, token: true, recipientEmail: true, active: true } + +export async function getBoardShares({ boardId }: { boardId: string }): Promise { + await requireBoardAccess(boardId) + return prisma.boardShare.findMany({ + where: { boardId }, + orderBy: { createdAt: 'asc' }, + select: shareSelect, + }) +} + +export async function addEmailShare({ boardId, email }: { boardId: string; email: string }) { + await requireBoardAccess(boardId) + const shares = await prisma.boardShare.findMany({ where: { boardId }, select: shareSelect }) + assertCanAddEmailShare(shares, email) + + await prisma.boardShare.create({ + data: { boardId, mode: 'EMAIL', recipientEmail: normalizeEmail(email), token: newToken() }, + }) +} + +/** Hay a lo sumo un link público por tablero: si ya existe, solo se reactiva (mismo token). */ +export async function enablePublicShare({ boardId }: { boardId: string }) { + await requireBoardAccess(boardId) + const existing = await prisma.boardShare.findFirst({ where: { boardId, mode: 'PUBLIC' } }) + if (existing) { + await prisma.boardShare.update({ where: { id: existing.id }, data: { active: true } }) + return + } + await prisma.boardShare.create({ data: { boardId, mode: 'PUBLIC', token: newToken() } }) +} + +export async function setShareActive({ + boardId, + shareId, + active, +}: { + boardId: string + shareId: string + active: boolean +}) { + await requireBoardAccess(boardId) + await prisma.boardShare.update({ where: { id: shareId, boardId }, data: { active } }) +} + +/** Para un link filtrado: el token viejo deja de funcionar. */ +export async function regenerateShareToken({ + boardId, + shareId, +}: { + boardId: string + shareId: string +}) { + await requireBoardAccess(boardId) + await prisma.boardShare.update({ where: { id: shareId, boardId }, data: { token: newToken() } }) +} + +export async function deleteShare({ boardId, shareId }: { boardId: string; shareId: string }) { + await requireBoardAccess(boardId) + await prisma.boardShare.delete({ where: { id: shareId, boardId } }) +} diff --git a/web-app/src/features/board-share/hooks/useBoardShares.ts b/web-app/src/features/board-share/hooks/useBoardShares.ts new file mode 100644 index 00000000..44130229 --- /dev/null +++ b/web-app/src/features/board-share/hooks/useBoardShares.ts @@ -0,0 +1,39 @@ +'use client' + +import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { toast } from 'sonner' +import { useSession } from '@/features/auth' +import getErrorMessageForTheUser from '@/shared/lib/getErrorMessageForTheUser' +import * as actions from '../api/actions/manageShares' + +/** Links compartidos de un tablero (solo el dueño, logueado). */ +export const useBoardShares = (boardId: string) => { + const { session } = useSession() + const queryClient = useQueryClient() + const queryKey = ['board-shares', boardId] + + const { data: shares = [], isLoading } = useQuery({ + queryKey, + queryFn: () => actions.getBoardShares({ boardId }), + enabled: !!session && !!boardId, + }) + + const { mutate: run, isPending } = useMutation({ + mutationFn: (action: () => Promise) => action(), + onError: (e) => toast.error(getErrorMessageForTheUser(e)), + onSettled: () => queryClient.invalidateQueries({ queryKey }), + }) + + return { + shares, + isLoading, + isPending, + addEmailShare: (email: string) => run(() => actions.addEmailShare({ boardId, email })), + enablePublicShare: () => run(() => actions.enablePublicShare({ boardId })), + setShareActive: (shareId: string, active: boolean) => + run(() => actions.setShareActive({ boardId, shareId, active })), + regenerateShareToken: (shareId: string) => + run(() => actions.regenerateShareToken({ boardId, shareId })), + deleteShare: (shareId: string) => run(() => actions.deleteShare({ boardId, shareId })), + } +} diff --git a/web-app/src/features/board-share/index.ts b/web-app/src/features/board-share/index.ts new file mode 100644 index 00000000..b761bbf3 --- /dev/null +++ b/web-app/src/features/board-share/index.ts @@ -0,0 +1,3 @@ +export { ShareBoardDialog } from './ui/ShareBoardDialog' +export { SharedBoardView } from './ui/SharedBoardView' +export { getBoardsSharedWithMe } from './api/actions/getBoardsSharedWithMe' diff --git a/web-app/src/features/board-share/model/boardShare.test.ts b/web-app/src/features/board-share/model/boardShare.test.ts new file mode 100644 index 00000000..291f3c11 --- /dev/null +++ b/web-app/src/features/board-share/model/boardShare.test.ts @@ -0,0 +1,91 @@ +import { describe, it, expect } from 'vitest' +import BusinessError from '@/shared/errors/businessError' +import { + assertCanAddEmailShare, + getShareAccess, + withoutNotes, + MAX_EMAIL_SHARES, + type BoardShare, +} from './boardShare' + +const share = (over: Partial = {}): BoardShare => ({ + id: 's1', + mode: 'EMAIL', + token: 'tok', + recipientEmail: 'ana@mail.com', + active: true, + ...over, +}) + +describe('getShareAccess', () => { + it('sin share o inactivo → not-found (no revela que existe)', () => { + expect(getShareAccess(null, 'ana@mail.com')).toBe('not-found') + expect(getShareAccess(share({ active: false }), 'ana@mail.com')).toBe('not-found') + }) + + it('público → ok sin login', () => { + expect(getShareAccess(share({ mode: 'PUBLIC', recipientEmail: null }), null)).toBe('ok') + }) + + it('email sin login → login-required', () => { + expect(getShareAccess(share(), null)).toBe('login-required') + }) + + it('email con otra cuenta → wrong-account', () => { + expect(getShareAccess(share(), 'otro@mail.com')).toBe('wrong-account') + }) + + it('email coincidente (sin importar mayúsculas) → ok', () => { + expect(getShareAccess(share(), ' Ana@Mail.com ')).toBe('ok') + }) +}) + +describe('assertCanAddEmailShare', () => { + it('rechaza un email inválido', () => { + expect(() => assertCanAddEmailShare([], 'no-es-email')).toThrow(BusinessError) + }) + + it('rechaza un email ya invitado', () => { + expect(() => assertCanAddEmailShare([share()], 'ANA@mail.com')).toThrow(BusinessError) + }) + + it(`rechaza más de ${MAX_EMAIL_SHARES} invitados por email (el público no cuenta)`, () => { + const shares = [ + ...Array.from({ length: MAX_EMAIL_SHARES }, (_, i) => + share({ id: `${i}`, recipientEmail: `u${i}@mail.com` }) + ), + ] + expect(() => assertCanAddEmailShare(shares, 'nuevo@mail.com')).toThrow(BusinessError) + + const withPublic = [ + ...shares.slice(1), + share({ id: 'p', mode: 'PUBLIC', recipientEmail: null }), + ] + expect(() => assertCanAddEmailShare(withPublic, 'nuevo@mail.com')).not.toThrow() + }) +}) + +describe('withoutNotes', () => { + it('saca notesAndComments de cada tarea y deja el resto igual', () => { + const board = [ + { + id: 'c1', + status: 'Todo', + tasks: [ + { id: 't1', descriptionText: 'a', notesAndComments: 'secreto' }, + { id: 't2', descriptionText: 'b', parentId: 't1' }, + ], + }, + ] + expect(withoutNotes(board)).toEqual([ + { + id: 'c1', + status: 'Todo', + tasks: [ + { id: 't1', descriptionText: 'a' }, + { id: 't2', descriptionText: 'b', parentId: 't1' }, + ], + }, + ]) + }) +}) diff --git a/web-app/src/features/board-share/model/boardShare.ts b/web-app/src/features/board-share/model/boardShare.ts new file mode 100644 index 00000000..175d6346 --- /dev/null +++ b/web-app/src/features/board-share/model/boardShare.ts @@ -0,0 +1,57 @@ +import BusinessError from '@/shared/errors/businessError' +import type { TaskBoard } from '@/features/tasks/model/taskBoard' + +/* + "Invitado" acá = quien VE un tablero compartido por otro usuario. + No confundir con el "modo invitado" (usuario sin cuenta, datos en localStorage). +*/ + +export type ShareMode = 'EMAIL' | 'PUBLIC' + +export interface BoardShare { + id: string + mode: ShareMode + token: string + /** Solo en modo `EMAIL`. */ + recipientEmail: string | null + active: boolean +} + +export const MAX_EMAIL_SHARES = 4 + +export const normalizeEmail = (email: string): string => email.trim().toLowerCase() + +const EMAIL_FORMAT = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ + +export const assertCanAddEmailShare = (shares: BoardShare[], email: string): void => { + const normalized = normalizeEmail(email) + if (!EMAIL_FORMAT.test(normalized)) throw new BusinessError('El email no es válido.') + + const emailShares = shares.filter((s) => s.mode === 'EMAIL') + if (emailShares.some((s) => s.recipientEmail === normalized)) + throw new BusinessError('Ese email ya está invitado.') + if (emailShares.length >= MAX_EMAIL_SHARES) + throw new BusinessError(`Solo se puede invitar hasta ${MAX_EMAIL_SHARES} emails.`) +} + +export type ShareAccess = 'ok' | 'not-found' | 'login-required' | 'wrong-account' + +/** Inactivo se reporta igual que inexistente, para no revelar que el link existió. */ +export const getShareAccess = ( + share: Pick | null, + viewerEmail: string | null | undefined +): ShareAccess => { + if (!share || !share.active) return 'not-found' + if (share.mode === 'PUBLIC') return 'ok' + if (!viewerEmail) return 'login-required' + if (normalizeEmail(viewerEmail) !== share.recipientEmail) return 'wrong-account' + return 'ok' +} + +/** El Invitado nunca ve las notas de las tareas. */ +export const withoutNotes = (taskBoard: TaskBoard): TaskBoard => + taskBoard.map((column) => ({ + ...column, + // eslint-disable-next-line @typescript-eslint/no-unused-vars + tasks: column.tasks.map(({ notesAndComments, ...task }) => task), + })) diff --git a/web-app/src/features/board-share/model/rateLimit.test.ts b/web-app/src/features/board-share/model/rateLimit.test.ts new file mode 100644 index 00000000..51159d37 --- /dev/null +++ b/web-app/src/features/board-share/model/rateLimit.test.ts @@ -0,0 +1,19 @@ +import { describe, it, expect } from 'vitest' +import { createRateLimiter } from './rateLimit' + +describe('createRateLimiter', () => { + it('deja pasar hasta `max` hits por clave dentro de la ventana', () => { + const hit = createRateLimiter({ max: 2, windowMs: 1000 }) + expect(hit('ip', 0)).toBe(true) + expect(hit('ip', 10)).toBe(true) + expect(hit('ip', 20)).toBe(false) + expect(hit('otra-ip', 20)).toBe(true) + }) + + it('resetea el contador al vencer la ventana', () => { + const hit = createRateLimiter({ max: 1, windowMs: 1000 }) + expect(hit('ip', 0)).toBe(true) + expect(hit('ip', 999)).toBe(false) + expect(hit('ip', 1000)).toBe(true) + }) +}) diff --git a/web-app/src/features/board-share/model/rateLimit.ts b/web-app/src/features/board-share/model/rateLimit.ts new file mode 100644 index 00000000..d3e25757 --- /dev/null +++ b/web-app/src/features/board-share/model/rateLimit.ts @@ -0,0 +1,22 @@ +/** + * Contador de ventana fija por clave. Devuelve `true` si el hit está permitido. + * ponytail: vive en memoria del proceso — en serverless cada instancia cuenta por + * su lado. Pasar a una tabla si hace falta un límite global. + */ +export const createRateLimiter = ({ max, windowMs }: { max: number; windowMs: number }) => { + const hits = new Map() + + return (key: string, now: number = Date.now()): boolean => { + const entry = hits.get(key) + if (!entry || now - entry.start >= windowMs) { + // Barrido perezoso para que el Map no crezca sin límite. + if (hits.size > 10_000) { + for (const [k, v] of hits) if (now - v.start >= windowMs) hits.delete(k) + } + hits.set(key, { count: 1, start: now }) + return true + } + entry.count++ + return entry.count <= max + } +} diff --git a/web-app/src/features/board-share/ui/ReadOnlyBoard.tsx b/web-app/src/features/board-share/ui/ReadOnlyBoard.tsx new file mode 100644 index 00000000..83876d2d --- /dev/null +++ b/web-app/src/features/board-share/ui/ReadOnlyBoard.tsx @@ -0,0 +1,39 @@ +'use client' + +import { useTranslation } from 'react-i18next' +import { useTheme } from '@/shared/hooks/useTheme' +import { cn } from '@/shared/lib/utils' +import { Column } from '@/features/tasks/ui/Columns/components/Column' +import type { TaskBoard } from '@/features/tasks/model/taskBoard' +import { ReadOnlyTask } from './ReadOnlyTask' + +export function ReadOnlyBoard({ name, taskBoard }: { name: string; taskBoard: TaskBoard }) { + const { t } = useTranslation() + const { bg, text } = useTheme() + const lists = taskBoard.map((column) => column.tasks) + + return ( +
+
+

{name}

+ {t('shared_board.read_only')} +
+
+ {taskBoard.map((column) => ( + +
+ {column.tasks.map((task) => ( + + ))} +
+
+ ))} +
+
+ ) +} diff --git a/web-app/src/features/board-share/ui/ReadOnlyTask.tsx b/web-app/src/features/board-share/ui/ReadOnlyTask.tsx new file mode 100644 index 00000000..1f022550 --- /dev/null +++ b/web-app/src/features/board-share/ui/ReadOnlyTask.tsx @@ -0,0 +1,39 @@ +'use client' + +import { KebabMenu } from '@/shared/ui/molecules/kebab' +import { BlankTask } from '@/features/tasks/ui/BlankTask' +import { CopyTextButton } from '@/features/tasks/ui/taskList/components/CopyTextButton' +import { + getChildrenOfTaskInBoard, + type TaskListInEachColumn, +} from '@/features/tasks/ui/taskList/models/taskListInEachColumn' +import type { TaskList } from '@/features/tasks/model/TaskList' + +interface ReadOnlyTaskProps { + task: TaskList[number] + lists: TaskListInEachColumn + isLastColumn: boolean +} + +export function ReadOnlyTask({ task, lists, isLastColumn }: ReadOnlyTaskProps) { + return ( + p.id === task.parentId)?.descriptionText + : undefined + } + childrenCount={ + task.parentId ? undefined : getChildrenOfTaskInBoard(lists, task.id).length + } + > + + + + + + + ) +} diff --git a/web-app/src/features/board-share/ui/ShareBoardDialog.tsx b/web-app/src/features/board-share/ui/ShareBoardDialog.tsx new file mode 100644 index 00000000..34ad5c79 --- /dev/null +++ b/web-app/src/features/board-share/ui/ShareBoardDialog.tsx @@ -0,0 +1,201 @@ +'use client' + +import { FormEvent, useState } from 'react' +import { useTranslation } from 'react-i18next' +import { toast } from 'sonner' +import { + Dialog, + DialogContent, + DialogDescription, + DialogHeader, + DialogTitle, +} from '@/shared/ui/molecules/dialog' +import { Button } from '@/shared/ui/atoms/button' +import { Input } from '@/shared/ui/atoms/input' +import { Label } from '@/shared/ui/atoms/label' +import { EyeIcon, EyeOffIcon, Link2Icon, RotateCcwIcon, TrashIcon } from '@/shared/ui/atoms/icons' +import { useTheme } from '@/shared/hooks/useTheme' +import { cn } from '@/shared/lib/utils' +import getErrorMessageForTheUser from '@/shared/lib/getErrorMessageForTheUser' +import { useBoardShares } from '../hooks/useBoardShares' +import { assertCanAddEmailShare, MAX_EMAIL_SHARES, type BoardShare } from '../model/boardShare' + +const shareUrl = (token: string) => `${window.location.origin}/shared/${token}` + +interface Props { + boardId: string + open: boolean + onOpenChange: (open: boolean) => void +} + +export function ShareBoardDialog({ boardId, open, onOpenChange }: Props) { + const color = useTheme() + return ( + + + + + + ) +} + +function SharePanel({ boardId }: { boardId: string }) { + const { t } = useTranslation() + const color = useTheme() + const [email, setEmail] = useState('') + const { shares, isPending, ...share } = useBoardShares(boardId) + + const publicShare = shares.find((s) => s.mode === 'PUBLIC') + const emailShares = shares.filter((s) => s.mode === 'EMAIL') + + const handleInvite = (e: FormEvent) => { + e.preventDefault() + try { + assertCanAddEmailShare(shares, email) + share.addEmailShare(email) + setEmail('') + } catch (error) { + toast.error(getErrorMessageForTheUser(error)) + } + } + + const row = (s: BoardShare, label: string) => ( +
  • + + {label} + +
    + + + + {s.mode === 'EMAIL' && ( + + )} +
    +
  • + ) + + return ( + <> + + {t('share.section_title')} + {t('share.section_description')} + + +
    +

    {t('share.public_title')}

    + {publicShare ? ( +
      + {row( + publicShare, + publicShare.active + ? t('share.public_label') + : t('share.public_label_inactive') + )} +
    + ) : ( + + )} +
    + +
    +

    + {t('share.email_title', { + count: emailShares.length, + max: MAX_EMAIL_SHARES, + })} +

    +

    {t('share.email_description')}

    + {emailShares.length > 0 && ( +
      + {emailShares.map((s) => row(s, s.recipientEmail ?? ''))} +
    + )} + {emailShares.length < MAX_EMAIL_SHARES && ( +
    +
    + + setEmail(e.target.value)} + placeholder='nombre@mail.com' + /> +
    + +
    + )} +
    + + ) +} diff --git a/web-app/src/features/board-share/ui/SharedBoardView.tsx b/web-app/src/features/board-share/ui/SharedBoardView.tsx new file mode 100644 index 00000000..9f7d97ab --- /dev/null +++ b/web-app/src/features/board-share/ui/SharedBoardView.tsx @@ -0,0 +1,98 @@ +'use client' + +import { useQuery } from '@tanstack/react-query' +import { useTranslation } from 'react-i18next' +import { useDocumentTitle } from '@uidotdev/usehooks' +import { ThemeProvider } from '@/shared/preferences/theme' +import { useTheme } from '@/shared/hooks/useTheme' +import { cn } from '@/shared/lib/utils' +import { Spinner } from '@/shared/ui/atoms/spinner' +import { TransitionLink } from '@/shared/ui/atoms/TransitionLink' +import { Button } from '@/shared/ui/atoms/button' +import { useLogout } from '@/features/auth' +import { isDefaultBoardName } from '@/features/boards' +import { getSharedBoard } from '../api/actions/getSharedBoard' +import { ReadOnlyBoard } from './ReadOnlyBoard' + +export function SharedBoardView({ token }: { token: string }) { + const { t } = useTranslation() + const logout = useLogout() + + // Sin polling ni refetch al enfocar + // Cada fetch cuenta para el rate limit del link público. + const { data, isLoading } = useQuery({ + queryKey: ['shared-board', token], + queryFn: () => getSharedBoard({ token }), + staleTime: Infinity, + refetchOnWindowFocus: false, + retry: false, + }) + + const boardName = + data?.status === 'ok' + ? isDefaultBoardName(data.boardName) + ? t('board_name') + : data.boardName + : 'Capo' + + useDocumentTitle(`${boardName} - Capo`) + + if (isLoading) { + return ( + + + + ) + } + + if (data?.status === 'ok') { + return ( + {}}> + + + ) + } + + if (data?.status === 'rate-limited') { + return {t('shared_board.rate_limited')} + } + + if (data?.status === 'login-required') { + return ( + +

    {t('shared_board.login_required')}

    + + {t('shared_board.login_button')} + +
    + ) + } + + if (data?.status === 'wrong-account') { + return ( + +

    {t('shared_board.wrong_account')}

    + +
    + ) + } + + return {t('shared_board.not_found')} +} + +function Message({ children }: { children: React.ReactNode }) { + const { bg, text } = useTheme() + return ( +
    + {children} +
    + ) +} diff --git a/web-app/src/features/dashboard/ui/BoardCard.tsx b/web-app/src/features/dashboard/ui/BoardCard.tsx index a6be1378..efff54e2 100644 --- a/web-app/src/features/dashboard/ui/BoardCard.tsx +++ b/web-app/src/features/dashboard/ui/BoardCard.tsx @@ -12,13 +12,18 @@ interface Board { themeId?: string } -function BoardCard({ board }: { board: Board }) { +interface Props { + board: Board + href?: string +} + +function BoardCard({ board, href }: Props) { const { t } = useTranslation() const { themes } = useThemesQuery() const color = resolveTheme(board.themeId, themes) const hero = heros[board.cardCanvas ?? 0] ?? heros[0] - const boardUrl = `/board/${board.id}` + const boardUrl = href ?? `/board/${board.id}` return (
  • diff --git a/web-app/src/features/dashboard/ui/Dashboard.tsx b/web-app/src/features/dashboard/ui/Dashboard.tsx index f1f06e74..f6fb285b 100644 --- a/web-app/src/features/dashboard/ui/Dashboard.tsx +++ b/web-app/src/features/dashboard/ui/Dashboard.tsx @@ -1,6 +1,7 @@ import BoardCard from './BoardCard' import { useDashboardQuery } from '../hooks/useDashboardQuery' import CreateBoardDialog from './CreateBoardDialog' +import { SharedWithMe } from './SharedWithMe' import { Spinner } from '@/shared/ui/atoms/spinner' import { LayoutIcon } from '@/shared/ui/atoms/icons' import { useTheme } from '@/shared/hooks/useTheme' @@ -53,6 +54,8 @@ function Dashboard() {
  • )} + + ) } diff --git a/web-app/src/features/dashboard/ui/SharedWithMe.tsx b/web-app/src/features/dashboard/ui/SharedWithMe.tsx new file mode 100644 index 00000000..82528c29 --- /dev/null +++ b/web-app/src/features/dashboard/ui/SharedWithMe.tsx @@ -0,0 +1,34 @@ +import { useQuery } from '@tanstack/react-query' +import { useTranslation } from 'react-i18next' +import { useSession } from '@/features/auth' +import { getBoardsSharedWithMe } from '@/features/board-share' +import BoardCard from './BoardCard' + +export function SharedWithMe() { + const { t } = useTranslation() + const { session } = useSession() + const { data: boards = [] } = useQuery({ + queryKey: ['boards-shared-with-me', session?.user.id], + queryFn: () => getBoardsSharedWithMe(), + enabled: !!session, + }) + + if (boards.length === 0) return null + + return ( +
    +

    + {t('dashboard.shared_with_me')} +

    +
      + {boards.map((board) => ( + + ))} +
    +
    + ) +} diff --git a/web-app/src/features/tasks/api/actions/getTaskBoard.ts b/web-app/src/features/tasks/api/actions/getTaskBoard.ts index d18dcf4c..f33e103f 100644 --- a/web-app/src/features/tasks/api/actions/getTaskBoard.ts +++ b/web-app/src/features/tasks/api/actions/getTaskBoard.ts @@ -1,37 +1,10 @@ 'use server' -import { prisma } from '@/shared/lib/prisma' import type { TaskBoard } from '@/features/tasks/model/taskBoard' -import type { taskModel } from '@/features/tasks/model/task' import { requireBoardAccess } from '@/shared/lib/serverAuth' +import { readTaskBoard } from '../readTaskBoard' -/** - * Returns the board as a TaskBoard (TaskColumn[]) shape expected by the client. - * Columns are ordered by `order`; tasks by `order` (persisted position), then `createdAt`. - */ export async function getTaskBoard({ boardId }: { boardId: string }): Promise { await requireBoardAccess(boardId) - - const columns = await prisma.column.findMany({ - where: { boardId }, - orderBy: { order: 'asc' }, - include: { - tasks: { orderBy: [{ order: 'asc' }, { createdAt: 'asc' }] }, - }, - }) - - return columns.map((col) => ({ - id: col.id, - status: col.name, - tasks: col.tasks.map((t) => ({ - id: t.id, - descriptionText: t.descriptionText, - dueDate: t.dueDate ?? undefined, - tags: (t.tags as unknown as taskModel['tags']) ?? undefined, - notesAndComments: t.notesAndComments ?? undefined, - timelineHistory: - (t.timelineHistory as unknown as taskModel['timelineHistory']) ?? undefined, - parentId: t.parentId ?? undefined, - })), - })) + return readTaskBoard(boardId) } diff --git a/web-app/src/features/tasks/api/readTaskBoard.ts b/web-app/src/features/tasks/api/readTaskBoard.ts new file mode 100644 index 00000000..71564fcb --- /dev/null +++ b/web-app/src/features/tasks/api/readTaskBoard.ts @@ -0,0 +1,33 @@ +import 'server-only' +import { prisma } from '@/shared/lib/prisma' +import type { TaskBoard } from '@/features/tasks/model/taskBoard' +import type { taskModel } from '@/features/tasks/model/task' + +/** + * Lee el tablero como TaskBoard (TaskColumn[]), SIN chequear acceso: el caller lo hace. + * Columns are ordered by `order`; tasks by `order` (persisted position), then `createdAt`. + */ +export async function readTaskBoard(boardId: string): Promise { + const columns = await prisma.column.findMany({ + where: { boardId }, + orderBy: { order: 'asc' }, + include: { + tasks: { orderBy: [{ order: 'asc' }, { createdAt: 'asc' }] }, + }, + }) + + return columns.map((col) => ({ + id: col.id, + status: col.name, + tasks: col.tasks.map((t) => ({ + id: t.id, + descriptionText: t.descriptionText, + dueDate: t.dueDate ?? undefined, + tags: (t.tags as unknown as taskModel['tags']) ?? undefined, + notesAndComments: t.notesAndComments ?? undefined, + timelineHistory: + (t.timelineHistory as unknown as taskModel['timelineHistory']) ?? undefined, + parentId: t.parentId ?? undefined, + })), + })) +} diff --git a/web-app/src/shared/i18n/en.json b/web-app/src/shared/i18n/en.json index 3ebe7b71..e49ec032 100644 --- a/web-app/src/shared/i18n/en.json +++ b/web-app/src/shared/i18n/en.json @@ -346,6 +346,7 @@ "today": "today" }, "dashboard": { + "shared_with_me": "Shared with me", "title": "This is where your projects are born", "description": "Your workspace is ready. Create boards to organize ideas, projects, and everything you can imagine.", "delete_warning": "Are you sure you want to delete this board? This action cannot be undone.", @@ -398,5 +399,35 @@ "verdict_late_one": "finished {{count}} day late", "verdict_late_other": "finished {{count}} days late" } + }, + + "share": { + "section_title": "Share board", + "section_description": "Guests see the board read-only, without task notes.", + "public_title": "Public link", + "public_label": "Anyone with the link", + "public_label_inactive": "No one can view the board with the link", + "create_public": "Create public link", + "email_title": "Invited by email ({{count}}/{{max}})", + "email_description": "No email is sent: copy the link and share it yourself. Only someone signed in with that email can open it.", + "email_input_label": "Guest email", + "invite": "Invite", + "copy_link": "Copy link", + "link_copied": "Link copied to clipboard.", + "activate": "Enable link", + "deactivate": "Disable link", + "regenerate": "Regenerate link", + "regenerate_warning": "The current link will stop working. Regenerate it?", + "remove": "Remove guest" + }, + + "shared_board": { + "read_only": "Read only", + "not_found": "This link does not exist or was disabled.", + "rate_limited": "Too many visits from your connection. Try again later.", + "login_required": "This board was shared with an email. Sign in or sign up with that email to see it.", + "login_button": "Sign in", + "wrong_account": "This board was shared with a different email. Sign out and sign in with the invited email.", + "logout_button": "Sign out" } } diff --git a/web-app/src/shared/i18n/es.json b/web-app/src/shared/i18n/es.json index 06464491..bb373b1e 100644 --- a/web-app/src/shared/i18n/es.json +++ b/web-app/src/shared/i18n/es.json @@ -342,6 +342,7 @@ "today": "hoy" }, "dashboard": { + "shared_with_me": "Compartidos conmigo", "title": "Aquí nacen tus proyectos", "description": "Tu espacio de trabajo está listo. Crea tableros para organizar ideas, proyectos y todo lo que imagines.", "delete_warning": "¿Deseas eliminar este tablero? Esta acción no se podrá deshacer.", @@ -394,5 +395,35 @@ "verdict_late_one": "terminada {{count}} día tarde", "verdict_late_other": "terminada {{count}} días tarde" } + }, + + "share": { + "section_title": "Compartir tablero", + "section_description": "Los Invitados ven el tablero en solo lectura, sin las notas de las tareas.", + "public_title": "Link público", + "public_label": "Cualquier usuario de Internet con el enlace puede verlo", + "public_label_inactive": "Nadie puede visualizar el tablero con el enlace", + "create_public": "Crear link público", + "email_title": "Invitados por email ({{count}}/{{max}})", + "email_description": "No se envía ningún email: copiá el link y compartilo vos. Solo lo abre quien inicie sesión con ese email.", + "email_input_label": "Email del Invitado", + "invite": "Invitar", + "copy_link": "Copiar enlace", + "link_copied": "Link copiado al portapapeles.", + "activate": "Activar enlace", + "deactivate": "Desactivar enlace", + "regenerate": "Regenerar link", + "regenerate_warning": "El link actual va a dejar de funcionar. ¿Regenerarlo?", + "remove": "Quitar invitado" + }, + + "shared_board": { + "read_only": "Solo lectura", + "not_found": "Este link no existe o fue desactivado.", + "rate_limited": "Demasiadas visitas desde tu conexión. Probá de nuevo en un rato.", + "login_required": "Este tablero se compartió con un email. Iniciá sesión o registrate con ese email para verlo.", + "login_button": "Iniciar sesión", + "wrong_account": "Este tablero se compartió con otro email. Cerrá sesión y entrá con el email invitado.", + "logout_button": "Cerrar sesión" } } diff --git a/web-app/src/shared/lib/serverAuth.ts b/web-app/src/shared/lib/serverAuth.ts index 13e73adb..875bb19c 100644 --- a/web-app/src/shared/lib/serverAuth.ts +++ b/web-app/src/shared/lib/serverAuth.ts @@ -8,10 +8,16 @@ import { prisma } from '@/shared/lib/prisma' El cliente solo distingue el prefijo. */ -export async function requireAuth() { +/** Usuario logueado o `null` (no tira). */ +export async function getSessionUser() { const session = await auth.api.getSession({ headers: await headers() }).catch(() => null) - if (!session?.user?.id) throw new Error('No autorizado') - return session.user.id + return session?.user ?? null +} + +export async function requireAuth() { + const user = await getSessionUser() + if (!user?.id) throw new Error('No autorizado') + return user.id } export async function requireBoardAccess(boardId: string) { diff --git a/web-app/src/shared/ui/atoms/icons.tsx b/web-app/src/shared/ui/atoms/icons.tsx index 7a435edb..8c680b52 100644 --- a/web-app/src/shared/ui/atoms/icons.tsx +++ b/web-app/src/shared/ui/atoms/icons.tsx @@ -21,6 +21,7 @@ import { EyeOff, ExternalLink, Github, + Globe, Highlighter, History, Home, @@ -29,6 +30,7 @@ import { Languages, Layout, Link, + Link2, List, ListChecks, ListOrdered, @@ -44,6 +46,7 @@ import { Plus, Quote, Redo, + RotateCcw, Send, Settings, Shield, @@ -107,6 +110,8 @@ export const CircleIcon = icon(Circle) export const UserIcon = icon(User) export const CloseIcon = icon(X) export const LinkIcon = icon(Link) +export const Link2Icon = icon(Link2) +export const GlobeIcon = icon(Globe) export const ExternalLinkIcon = icon(ExternalLink) export const LayoutIcon = icon(Layout) export const BoldIcon = icon(Bold) @@ -124,6 +129,7 @@ export const AlignRightIcon = icon(AlignRight) export const AlignJustifyIcon = icon(AlignJustify) export const UndoIcon = icon(Undo) export const RedoIcon = icon(Redo) +export const RotateCcwIcon = icon(RotateCcw) export const MoreHorizontalIcon = icon(MoreHorizontal) export const EllipsisVerticalIcon = icon(EllipsisVertical) export const TagIcon = icon(Tag)