diff --git a/.env.example b/.env.example index f6b17af..4c005af 100644 --- a/.env.example +++ b/.env.example @@ -34,6 +34,17 @@ CORS_ORIGIN=http://localhost # MEDIA_QUOTA_PER_TREE_MB=5120 # MEDIA_PENDING_QUOTA_PER_TREE_MB=500 +# ── Immich (reconnaissance des visages, désactivé par défaut) ──────────────── +# Instances Immich autorisées sur ce serveur, séparées par des virgules. Chaque entrée +# peut recevoir un libellé, « Libellé=https://adresse » ; sans libellé, c'est le nom +# d'hôte qui sert (un même nom d'hôte ne peut pas servir à deux instances : donnez-leur +# un libellé). Les administrateurs de chaque arbre choisissent l'instance par son nom +# et donnent leur propre clé d'API (créée dans Immich, Paramètres > Clés d'API) ; la +# clé est chiffrée en base. L'adresse n'est jamais montrée aux administrateurs : seul +# le libellé l'est. Sans cette liste, la fonction reste éteinte, et une adresse retirée +# de la liste coupe aussitôt les arbres qui l'utilisent. +# IMMICH_ALLOWED_API_URLS=Maison=http://immich.maison.lan:2283,https://immich.example.org + # ── Images ──────────────────────────────────────────────────────────────────── # Version des images ghcr.io/iliesallali/parenthese-api et parenthese-web : latest (dernière # version de main), ou une version figée, par exemple 1.0. diff --git a/backend/.env.example b/backend/.env.example index b6d997d..02584f4 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -6,3 +6,8 @@ JWT_EXPIRES_IN="7d" JWT_TREE_ACCESS_EXPIRES_IN="24h" CORS_ORIGIN="http://localhost:5173,http://localhost:5174,http://localhost:5175,http://localhost:5176" MEDIA_STORAGE_PATH="./storage/media" +# Reconnaissance des visages : instances Immich autorisées sur ce serveur, séparées par des +# virgules. Entrée « Libellé=https://adresse » ou « https://adresse » (nom d'hôte comme libellé, +# donc un libellé si deux instances partagent un nom). Les administrateurs de chaque arbre choisissent +# l'instance par son nom et donnent leur propre clé d'API. Sans cette liste, la fonction reste éteinte. +IMMICH_ALLOWED_API_URLS="" diff --git a/backend/.env.production.example b/backend/.env.production.example index 75296d2..239b528 100644 --- a/backend/.env.production.example +++ b/backend/.env.production.example @@ -23,3 +23,9 @@ CORS_ORIGIN="https://arbre.example.org" # Dossier des médias envoyés. Un chemin relatif part du dossier backend/. MEDIA_STORAGE_PATH="/var/lib/parenthese/media" + +# Reconnaissance des visages : instances Immich autorisées sur ce serveur, séparées par des +# virgules. Entrée « Libellé=https://adresse » ou « https://adresse » (nom d'hôte comme libellé, +# donc un libellé si deux instances partagent un nom). Les administrateurs de chaque arbre choisissent +# l'instance par son nom et donnent leur propre clé d'API. Sans cette liste, la fonction reste éteinte. +IMMICH_ALLOWED_API_URLS="" diff --git a/backend/prisma/migrations/20261012_001_add_immich_person_id/migration.sql b/backend/prisma/migrations/20261012_001_add_immich_person_id/migration.sql new file mode 100644 index 0000000..8eab9cb --- /dev/null +++ b/backend/prisma/migrations/20261012_001_add_immich_person_id/migration.sql @@ -0,0 +1,2 @@ +-- Association d'une personne à une personne Immich (reconnaissance des visages). +ALTER TABLE "persons" ADD COLUMN "immichPersonId" TEXT; diff --git a/backend/prisma/migrations/20261013_001_tree_immich_config/migration.sql b/backend/prisma/migrations/20261013_001_tree_immich_config/migration.sql new file mode 100644 index 0000000..1e94ae6 --- /dev/null +++ b/backend/prisma/migrations/20261013_001_tree_immich_config/migration.sql @@ -0,0 +1,13 @@ +-- Connexion Immich propre à chaque arbre : adresse de l'instance et clé d'API chiffrée. +-- Aucune ligne n'est créée pour les arbres existants : ils restent sans accès Immich +-- jusqu'à ce que leurs administrateurs configurent la connexion. +CREATE TABLE "tree_immich_configs" ( + "treeId" TEXT NOT NULL, + "apiUrl" TEXT NOT NULL, + "apiKeyEnc" TEXT NOT NULL, + "updatedAt" TIMESTAMP(3) NOT NULL, + CONSTRAINT "tree_immich_configs_pkey" PRIMARY KEY ("treeId") +); + +ALTER TABLE "tree_immich_configs" ADD CONSTRAINT "tree_immich_configs_treeId_fkey" + FOREIGN KEY ("treeId") REFERENCES "trees"("id") ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index a80a8d5..3176006 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -114,6 +114,7 @@ model Tree { memberships TreeMembership[] sharedUserAccesses UserTreeAccess[] settings TreeSettings? + immichConfig TreeImmichConfig? persons Person[] unions Union[] parentChildLinks ParentChildLink[] @@ -190,6 +191,19 @@ model TreeSettings { @@map("tree_settings") } +// Connexion Immich propre à chaque arbre (reconnaissance des visages) : l'adresse et la clé de +// l'instance sont choisies par ses administrateurs, jamais héritées du serveur. La clé est +// chiffrée au repos ; une ligne absente signifie « aucun accès Immich » pour cet arbre. +model TreeImmichConfig { + treeId String @id + apiUrl String + apiKeyEnc String + updatedAt DateTime @updatedAt + tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade) + + @@map("tree_immich_configs") +} + model Person { id String @id @default(cuid()) treeId String @@ -208,6 +222,8 @@ model Person { notes String? createdBy String? updatedBy String? + // Personne Immich associée (reconnaissance des visages) : identifiant côté Immich, ou null. + immichPersonId String? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt deletedAt DateTime? diff --git a/backend/src/app.ts b/backend/src/app.ts index db855e0..61272f1 100644 --- a/backend/src/app.ts +++ b/backend/src/app.ts @@ -10,6 +10,7 @@ import { isUserTokenRevoked } from './lib/token-revocation.js' import { authRoutes } from './routes/auth.js' import { contributionRoutes } from './routes/contributions.js' import { graphRoutes } from './routes/graph.js' +import { immichRoutes } from './routes/immich.js' import { mediaRoutes } from './routes/media.js' import { publicRoutes } from './routes/public.js' import { annotationRoutes } from './routes/annotations.js' @@ -147,6 +148,7 @@ export function createApp() { app.register(annotationRoutes) app.register(gedcomRoutes) app.register(visitRoutes) + app.register(immichRoutes) app.setErrorHandler((error: FastifyError | Error, request, reply) => { if (error instanceof Prisma.PrismaClientInitializationError) { diff --git a/backend/src/config/env.ts b/backend/src/config/env.ts index c14eab7..1419f0d 100644 --- a/backend/src/config/env.ts +++ b/backend/src/config/env.ts @@ -50,6 +50,10 @@ const envSchema = z.object({ // Place disque par arbre, et part réservée aux envois de la famille en attente de relecture MEDIA_QUOTA_PER_TREE_MB: z.coerce.number().int().positive().default(5120), MEDIA_PENDING_QUOTA_PER_TREE_MB: z.coerce.number().int().positive().default(500), + // Instances Immich autorisées sur ce serveur, séparées par des virgules. Les administrateurs + // d'un arbre choisissent leur connexion parmi cette liste : sans elle, la reconnaissance + // des visages reste éteinte et le serveur ne peut pas servir de proxy vers un service interne. + IMMICH_ALLOWED_API_URLS: z.string().default(''), }) export const env = envSchema.parse(process.env) diff --git a/backend/src/lib/entity-deletion.ts b/backend/src/lib/entity-deletion.ts index 89d347b..eb41427 100644 --- a/backend/src/lib/entity-deletion.ts +++ b/backend/src/lib/entity-deletion.ts @@ -32,7 +32,7 @@ export async function softDeletePersonCascade( await db.person.updateMany({ where: { id: personId, treeId, deletedAt: null }, - data: { deletedAt: now, updatedBy: actorUserId, avatarPath: null, avatarMimeType: null }, + data: { deletedAt: now, updatedBy: actorUserId, avatarPath: null, avatarMimeType: null, immichPersonId: null }, }) const unions = await db.union.findMany({ diff --git a/backend/src/lib/immich-secret.ts b/backend/src/lib/immich-secret.ts new file mode 100644 index 0000000..5a9d181 --- /dev/null +++ b/backend/src/lib/immich-secret.ts @@ -0,0 +1,37 @@ +import { createCipheriv, createDecipheriv, hkdfSync, randomBytes } from 'node:crypto' + +import { env } from '../config/env.js' + +// Clé d'API Immich d'un arbre : secrète au repos, jamais renvoyée au front ni écrite dans les +// journaux. Même mécanisme que le mot de passe de partage (share-password.ts) : AES-256-GCM, +// clé dérivée de JWT_SECRET. Changer ce secret rend les clés illisibles ; chaque arbre +// repasse alors en « à configurer », sans rien casser d'autre. +const VERSION = 'v1' + +function getKey(): Buffer { + return Buffer.from(hkdfSync('sha256', env.JWT_SECRET, 'parenthese', 'immich-api-key-v1', 32)) +} + +export function encryptImmichApiKey(value: string): string { + const iv = randomBytes(12) + const cipher = createCipheriv('aes-256-gcm', getKey(), iv) + const encrypted = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]) + const tag = cipher.getAuthTag() + return `${VERSION}:${Buffer.concat([iv, tag, encrypted]).toString('base64')}` +} + +// null si la valeur stockée est absente, d'un autre format, ou illisible (JWT_SECRET changé). +export function decryptImmichApiKey(stored: string | null | undefined): string | null { + if (!stored || !stored.startsWith(`${VERSION}:`)) { + return null + } + + try { + const raw = Buffer.from(stored.slice(VERSION.length + 1), 'base64') + const decipher = createDecipheriv('aes-256-gcm', getKey(), raw.subarray(0, 12)) + decipher.setAuthTag(raw.subarray(12, 28)) + return Buffer.concat([decipher.update(raw.subarray(28)), decipher.final()]).toString('utf8') + } catch { + return null + } +} diff --git a/backend/src/lib/immich.ts b/backend/src/lib/immich.ts new file mode 100644 index 0000000..8645bde --- /dev/null +++ b/backend/src/lib/immich.ts @@ -0,0 +1,314 @@ +import { createHash } from 'node:crypto' + +import type { PrismaClient } from '@prisma/client' + +import { env } from '../config/env.js' +import { decryptImmichApiKey } from './immich-secret.js' + +// Client Immich : la reconnaissance des visages lit les personnes et leurs vignettes. +// Contrat vérifié sur la spécification OpenAPI officielle d'Immich v3.1.0 : +// GET /api/server/ping -> 200 {"res":"pong"} +// GET /api/people?page=N&size=M -> 200 { people: PersonResponseDto[], total, hasNextPage, hidden } (size <= 1000) +// GET /api/people/{id} -> 200 PersonResponseDto | 404 (id : UUID v4) +// GET /api/people/{id}/thumbnail -> 200 image binaire | 404 +// Authentification : en-tête x-api-key ; clé refusée -> 401. + +// Instance injoignable : réseau coupé, délai dépassé, réponse illisible. +export class ImmichUnavailableError extends Error { + constructor(message = 'Immich est injoignable') { + super(message) + this.name = 'ImmichUnavailableError' + } +} + +// Clé d'API refusée par Immich (401/403). +export class ImmichAuthError extends Error { + constructor(message = 'Clé d’API Immich refusée') { + super(message) + this.name = 'ImmichAuthError' + } +} + +// Personne ou vignette inexistante côté Immich (404). +export class ImmichNotFoundError extends Error { + constructor(message = 'Personne Immich introuvable') { + super(message) + this.name = 'ImmichNotFoundError' + } +} + +const IMMICH_PEOPLE_PAGE_SIZE = 1000 +const IMMICH_TIMEOUT_MS = 10_000 +// Délai global de la liste complète : chaque page a son propre délai, la liste entière aussi. +const IMMICH_LIST_DEADLINE_MS = 30_000 + +// Identifiants de personnes Immich : UUID v4 (spécification OpenAPI). +const IMMICH_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i + +export function isImmichPersonId(value: string): boolean { + return IMMICH_ID_RE.test(value) +} + +export type ImmichPersonSummary = { + id: string + name: string + hasThumbnail: boolean +} + +type ImmichPeoplePage = { + people?: unknown + hasNextPage?: unknown +} + +export class ImmichClient { + private readonly apiUrl: string + private readonly apiKey: string + + constructor(apiUrl: string, apiKey: string) { + this.apiUrl = apiUrl.replace(/\/$/, '') + this.apiKey = apiKey + } + + // Le chemin de l'instance (ex. /immich) reste devant les chemins de l'API : on concatène, + // on ne résout pas une URL relative (qui effacerait ce chemin). + // Corps JSON lu hors de toute gestion d'erreur : un corps illisible est une instance + // défaillante (503), pas une erreur serveur. + private async readJson(response: Response): Promise { + try { + return await response.json() + } catch { + throw new ImmichUnavailableError('Réponse Immich illisible') + } + } + + private buildUrl(path: string): string { + return `${this.apiUrl}${path}` + } + + private async fetch(path: string): Promise { + const url = this.buildUrl(path) + let response: Response + try { + response = await fetch(url, { + headers: { 'x-api-key': this.apiKey, Accept: 'application/json' }, + signal: AbortSignal.timeout(IMMICH_TIMEOUT_MS), + // Aucune redirection suivie : la clé ne doit jamais partir vers une autre adresse. + redirect: 'error', + }) + } catch (error) { + // L'URL ne contient aucun secret ; la clé voyage dans l'en-tête, jamais dans les journaux. + console.warn(`Immich injoignable : ${url} (${(error as Error).message})`) + throw new ImmichUnavailableError() + } + + if (response.ok) { + return response + } + + // Journal avec le statut et l'URL (sans secret), puis remontée d'une erreur distincte par cause. + console.warn(`Immich a répondu ${response.status} sur ${url}`) + if (response.status === 401 || response.status === 403) { + throw new ImmichAuthError() + } + if (response.status === 404) { + throw new ImmichNotFoundError() + } + throw new ImmichUnavailableError(`Immich a répondu ${response.status}`) + } + + async ping(): Promise { + try { + const response = await this.fetch('/api/server/ping') + const payload = (await response.json()) as { res?: unknown } + return payload?.res === 'pong' + } catch { + return false + } + } + + // Toutes les personnes (sans les masquées), en suivant la pagination d'Immich. + async listPeople(): Promise { + const people: ImmichPersonSummary[] = [] + let page = 1 + + const deadline = Date.now() + IMMICH_LIST_DEADLINE_MS + // Garde-fou : une instance qui répondrait toujours hasNextPage ne doit pas nous faire boucler. + for (let guard = 0; guard < 1000; guard += 1, page += 1) { + if (Date.now() > deadline) { + throw new ImmichUnavailableError('Liste des personnes Immich trop longue') + } + const response = await this.fetch(`/api/people?page=${page}&size=${IMMICH_PEOPLE_PAGE_SIZE}`) + const payload = (await this.readJson(response)) as ImmichPeoplePage + + if (!Array.isArray(payload.people)) { + throw new ImmichUnavailableError('Réponse Immich inattendue sur /api/people') + } + + for (const person of payload.people as Array<{ id?: unknown; name?: unknown; thumbnailPath?: unknown }>) { + if (typeof person?.id !== 'string' || typeof person?.name !== 'string') { + throw new ImmichUnavailableError('Réponse Immich inattendue sur /api/people') + } + people.push({ id: person.id, name: person.name, hasThumbnail: typeof person.thumbnailPath === 'string' && person.thumbnailPath.length > 0 }) + } + + if (payload.hasNextPage !== true || (payload.people as unknown[]).length === 0) { + break + } + } + + return people + } + + // Une personne précise : 200 avec ses données, 404 si elle n'existe pas. Le 404 de la + // vignette ne prouve rien (personne absente ou simple vignette manquante), l'existence + // se vérifie donc ici. + async getPerson(personId: string): Promise { + const response = await this.fetch(`/api/people/${encodeURIComponent(personId)}`) + const person = (await this.readJson(response)) as { id?: unknown; name?: unknown; thumbnailPath?: unknown } + if (typeof person?.id !== 'string' || typeof person?.name !== 'string') { + throw new ImmichUnavailableError('Réponse Immich inattendue sur /api/people/{id}') + } + return { + id: person.id, + name: person.name, + hasThumbnail: typeof person.thumbnailPath === 'string' && person.thumbnailPath.length > 0, + } + } + + // Vignette d'une personne, en octets bruts (JPEG côté Immich). Absente -> ImmichNotFoundError. + // Lue en flux : au-delà de maxBytes, la lecture s'arrête et renvoie null sans charger le reste. + async getPersonThumbnail(personId: string, maxBytes: number): Promise { + const response = await this.fetch(`/api/people/${encodeURIComponent(personId)}/thumbnail`) + const declared = Number(response.headers.get('content-length')) + if (Number.isFinite(declared) && declared > maxBytes) { + await response.body?.cancel().catch(() => {}) + return null + } + if (!response.body) { + return Buffer.alloc(0) + } + + const reader = response.body.getReader() + const chunks: Buffer[] = [] + let total = 0 + try { + for (;;) { + const { done, value } = await reader.read() + if (done) break + total += value.byteLength + if (total > maxBytes) { + await reader.cancel().catch(() => {}) + return null + } + chunks.push(Buffer.from(value)) + } + } catch { + throw new ImmichUnavailableError('Lecture de la vignette Immich interrompue') + } + return Buffer.concat(chunks, total) + } +} + +// Instance Immich normalisée pour comparaison : origine + chemin, sans slash final. Null si l'URL +// est mal formée ou d'un autre protocole que http(s). +export function normalizeImmichApiUrl(value: string): string | null { + try { + const url = new URL(value) + if (url.protocol !== 'http:' && url.protocol !== 'https:') { + return null + } + // Ni identifiants, ni requête, ni fragment : une adresse d'instance n'en porte pas, et + // « https://instance@autre-hote » ne doit jamais passer pour l'instance. + if (url.username || url.password || url.search || url.hash) { + return null + } + return `${url.origin}${url.pathname.replace(/\/+$/, '')}` + } catch { + return null + } +} + +export type ImmichInstance = { + // Identifiant opaque, dérivé de l'adresse (stable même si l'opérateur réordonne la liste). + id: string + label: string + apiUrl: string +} + +let instancesCache: ImmichInstance[] | undefined + +export function immichInstanceId(apiUrl: string): string { + return createHash('sha256').update(apiUrl).digest('hex').slice(0, 16) +} + +// Instances Immich autorisées par l'opérateur du serveur (IMMICH_ALLOWED_API_URLS). C'est la seule +// liste d'adresses possibles : les administrateurs d'un arbre y choisissent la leur, le serveur +// ne devient jamais un proxy vers un service interne choisi librement. Format d'une entrée : +// « Libellé=https://adresse » ou « https://adresse ». Sans libellé, le nom d'hôte sert de nom. +// Entrées invalides, doublons et libellés en conflit sont ignorés avec un avertissement. +export function getImmichInstances(): ImmichInstance[] { + if (instancesCache !== undefined) { + return instancesCache + } + + const instances: ImmichInstance[] = [] + for (const entry of env.IMMICH_ALLOWED_API_URLS.split(',')) { + const trimmed = entry.trim() + if (!trimmed) { + continue + } + const named = /^(.*?)\s*=\s*(https?:\/\/.+)$/i.exec(trimmed) + const rawUrl = named ? named[2] : trimmed + const apiUrl = normalizeImmichApiUrl(rawUrl) + if (!apiUrl) { + console.warn(`IMMICH_ALLOWED_API_URLS : entrée ignorée (URL http(s) invalide) : ${trimmed}`) + continue + } + if (instances.some((instance) => instance.apiUrl === apiUrl)) { + continue + } + const label = (named?.[1] ?? '').trim() || new URL(apiUrl).hostname + if (instances.some((instance) => instance.label.toLowerCase() === label.toLowerCase())) { + console.warn(`IMMICH_ALLOWED_API_URLS : entrée ignorée, le nom « ${label} » est déjà pris : donnez-lui un libellé (Libellé=https://…)`) + continue + } + instances.push({ id: immichInstanceId(apiUrl), label, apiUrl }) + } + instancesCache = instances + return instances +} + +export function getImmichInstanceByApiUrl(value: string): ImmichInstance | undefined { + const normalized = normalizeImmichApiUrl(value) + return normalized === null ? undefined : getImmichInstances().find((instance) => instance.apiUrl === normalized) +} + +export function isImmichApiUrlAllowed(value: string): boolean { + return getImmichInstanceByApiUrl(value) !== undefined +} + +// Connexion Immich d'un arbre : résolue par arbre, côté serveur, à chaque requête. Pas de client +// global qui garderait les identifiants d'un arbre et pourrait servir un autre ; pas d'héritage +// de configuration du serveur. Une clé illisible (JWT_SECRET changé) vaut « non configuré », et +// une adresse retirée de la liste de l'opérateur aussi : la connexion existante cesse de marcher. +export async function getTreeImmichClient(prisma: PrismaClient, treeId: string): Promise { + const config = await prisma.treeImmichConfig.findUnique({ + where: { treeId }, + select: { apiUrl: true, apiKeyEnc: true }, + }) + if (!config) { + return null + } + + const apiKey = decryptImmichApiKey(config.apiKeyEnc) + if (!apiKey) { + return null + } + + if (!isImmichApiUrlAllowed(config.apiUrl)) { + return null + } + + // Le client reçoit l'adresse autorisée, normalisée : pas celle, brute, de la base. + return new ImmichClient(getImmichInstanceByApiUrl(config.apiUrl)!.apiUrl, apiKey) +} diff --git a/backend/src/lib/media-files.ts b/backend/src/lib/media-files.ts index ced93aa..70ce049 100644 --- a/backend/src/lib/media-files.ts +++ b/backend/src/lib/media-files.ts @@ -211,6 +211,12 @@ export function applyMediaResponseHeaders(reply: FastifyReply, storedMimeType: s reply.header('Content-Disposition', `attachment; filename="${safeName}"`) } +// Portrait venu d'une association Immich : son fichier porte le préfixe « immich- ». Le graphe +// ne publie jamais l'identifiant Immich, seulement cette origine du portrait. +export function isImmichAvatarPath(avatarPath: string | null | undefined): boolean { + return avatarPath != null && path.basename(avatarPath).startsWith('immich-') +} + // Efface un fichier du stockage, sans jamais sortir du dossier racine export async function removeStoredFile(storageRoot: string, relativePath: string | null | undefined): Promise { if (!relativePath || /^https?:\/\//.test(relativePath)) return diff --git a/backend/src/routes/immich.ts b/backend/src/routes/immich.ts new file mode 100644 index 0000000..9e11849 --- /dev/null +++ b/backend/src/routes/immich.ts @@ -0,0 +1,587 @@ +import type { FastifyPluginAsync, FastifyReply, FastifyRequest } from 'fastify' +import path from 'node:path' +import { randomUUID } from 'node:crypto' +import { mkdir, writeFile } from 'node:fs/promises' +import { z } from 'zod' + +import { + getImmichInstanceByApiUrl, + getImmichInstances, + getTreeImmichClient, + isImmichPersonId, + normalizeImmichApiUrl, + ImmichAuthError, + ImmichNotFoundError, + ImmichUnavailableError, + type ImmichPersonSummary, +} from '../lib/immich.js' +import { decryptImmichApiKey, encryptImmichApiKey } from '../lib/immich-secret.js' +import { InvalidMediaError, isImmichAvatarPath, removeStoredFile, sniffMimeType } from '../lib/media-files.js' +import { exceedsStorageQuota, getStorageRoot, prepareUploadedFile, requireAdminMembership } from './media.js' + +// Reconnaissance des visages : associer une personne de l'arbre à une personne Immich, dont la +// vignette devient son portrait. Chaque arbre porte sa propre connexion Immich : une adresse +// choisie parmi celles autorisées par l'opérateur du serveur (IMMICH_ALLOWED_API_URLS), et une +// clé chiffrée en base. Toutes les routes sont rattachées à un arbre, réservées à ses +// administrateurs, et ne parlent jamais à l'instance d'un autre arbre. + +const treeParamSchema = z.object({ id: z.string().min(1) }) +const treePersonParamsSchema = z.object({ id: z.string().min(1), personId: z.string().min(1) }) + +const assignSchema = z.object({ + personId: z.string().min(1), + immichPersonId: z.string().refine(isImmichPersonId, 'invalid_immich_person_id'), + // Remplacer un portrait déjà en place demande un accord explicite, quelle que soit son + // origine (posé à la main ou venu d'une association Immich précédente). + replaceAvatar: z.boolean().optional(), +}) + +const unassignSchema = z.object({ + personId: z.string().min(1), +}) + +const thumbnailParamSchema = z.object({ + id: z.string().min(1), + immichPersonId: z.string().refine(isImmichPersonId, 'invalid_immich_person_id'), +}) + +// Connexion Immich d'un arbre : instance choisie parmi celles autorisées par l'opérateur du +// serveur (IMMICH_ALLOWED_API_URLS), désignée par son identifiant opaque. L'adresse ne circule +// jamais vers le front. La clé se joint à la mise à jour ou, si le champ reste vide, celle en +// place est conservée — jamais relue par le front. +const configPayloadSchema = z.object({ + instanceId: z.string().regex(/^[0-9a-f]{16}$/, 'invalid_instance_id'), + apiKey: z.string().min(1).max(512).optional(), +}) + +const MAX_THUMBNAIL_BYTES = 5 * 1024 * 1024 + +function replyImmichError(request: FastifyRequest, reply: FastifyReply, error: unknown): FastifyReply { + if (error instanceof ImmichNotFoundError) { + return reply.code(404).send({ error: 'immich_person_not_found' }) + } + if (error instanceof ImmichAuthError) { + return reply.code(502).send({ error: 'immich_auth_failed' }) + } + if (error instanceof ImmichUnavailableError) { + return reply.code(503).send({ error: 'immich_unreachable' }) + } + request.log.error({ err: error }, 'Erreur inattendue pendant un appel à Immich') + return reply.code(500).send({ error: 'immich_api_error' }) +} + +// Métadonnées sûres d'une connexion Immich d'arbre : jamais la clé, jamais son chiffré, jamais +// l'adresse (l'instance se nomme par son libellé). Une adresse sortie de la liste de l'opérateur +// vaut « non configuré » : la connexion est inerte. Une clé qui ne se déchiffre plus (JWT_SECRET +// changé) vaut aussi « non configuré », avec keyNeedsReentry : l'administrateur doit la ressaisir. +function immichConfigSummary(config: { apiUrl: string; apiKeyEnc: string; updatedAt: Date } | null) { + const instance = config ? getImmichInstanceByApiUrl(config.apiUrl) : undefined + if (!config || !instance) { + return { configured: false, keyNeedsReentry: false, instanceId: null, label: null, updatedAt: null } + } + const keyReadable = decryptImmichApiKey(config.apiKeyEnc) !== null + return { + configured: keyReadable, + keyNeedsReentry: !keyReadable, + instanceId: instance.id, + label: instance.label, + updatedAt: config.updatedAt, + } +} + +// Portraits venus d'Immich : même nommage que les envois manuels (« avatar- »), avec le +// préfixe « immich- » qui dit au désassignement que le fichier nous appartient. Un portrait +// envoyé à la main n'est jamais touché par le désassignement. +function buildAvatarRelativePath(treeId: string, personId: string, extension: string): string { + return path.posix.join(treeId, personId, `immich-${randomUUID()}${extension}`) +} + +export const immichRoutes: FastifyPluginAsync = async (app) => { + // ── Connexion Immich de l'arbre : lecture, écriture, suppression. Réservées aux + // administrateurs de l'arbre ; la clé d'API ne quitte jamais le serveur. + + app.get('/trees/:id/immich/config', async (request, reply) => { + if (!request.actor || request.actor.kind !== 'user') { + return reply.code(401).send({ error: 'authentication_required' }) + } + + const params = treeParamSchema.safeParse(request.params) + if (!params.success) { + return reply.code(400).send({ error: 'invalid_params' }) + } + + if (!(await requireAdminMembership(app, request.actor.userId, params.data.id))) { + return reply.code(403).send({ error: 'forbidden' }) + } + + const config = await app.prisma.treeImmichConfig.findUnique({ + where: { treeId: params.data.id }, + select: { apiUrl: true, apiKeyEnc: true, updatedAt: true }, + }) + + return reply.send({ + config: immichConfigSummary(config), + // Les administrateurs choisissent parmi ces instances : le front en fait un menu, pas un champ libre. + instances: getImmichInstances().map(({ id, label }) => ({ id, label })), + }) + }) + + app.put('/trees/:id/immich/config', async (request, reply) => { + if (!request.actor || request.actor.kind !== 'user') { + return reply.code(401).send({ error: 'authentication_required' }) + } + + const params = treeParamSchema.safeParse(request.params) + const payload = configPayloadSchema.safeParse(request.body) + if (!params.success) { + return reply.code(400).send({ error: 'invalid_params' }) + } + if (!payload.success) { + return reply.code(400).send({ error: 'invalid_payload', details: payload.error.flatten() }) + } + + if (!(await requireAdminMembership(app, request.actor.userId, params.data.id))) { + return reply.code(403).send({ error: 'forbidden' }) + } + + // L'instance doit faire partie de la liste de l'opérateur : le serveur ne devient jamais + // un proxy vers un service interne choisi librement (SSRF). L'adresse vient de la liste, + // jamais de la requête. + const instance = getImmichInstances().find((candidate) => candidate.id === payload.data.instanceId) + if (!instance) { + return reply.code(400).send({ error: 'instance_not_allowed' }) + } + + const treeId = params.data.id + const existing = await app.prisma.treeImmichConfig.findUnique({ + where: { treeId }, + select: { apiUrl: true, apiKeyEnc: true }, + }) + + // Sans nouvelle clé, la clé en place est conservée — mais il en faut une pour une + // première configuration, et quand celle en place ne se déchiffre plus : on ne devine + // jamais d'identifiants ailleurs. + if (!payload.data.apiKey && (!existing || !decryptImmichApiKey(existing.apiKeyEnc))) { + return reply.code(400).send({ error: 'api_key_required' }) + } + + // Changer d'instance n'emmène jamais la clé de l'ancienne : elle ne vaut rien pour la + // nouvelle, et on ne l'envoie pas à un serveur qui n'est pas le sien. + if (existing && !payload.data.apiKey + && normalizeImmichApiUrl(existing.apiUrl) !== instance.apiUrl) { + return reply.code(400).send({ error: 'api_key_required' }) + } + + const apiKeyEnc = payload.data.apiKey + ? encryptImmichApiKey(payload.data.apiKey) + : existing!.apiKeyEnc + + const config = await app.prisma.treeImmichConfig.upsert({ + where: { treeId }, + create: { treeId, apiUrl: instance.apiUrl, apiKeyEnc }, + update: { apiUrl: instance.apiUrl, apiKeyEnc }, + select: { apiUrl: true, apiKeyEnc: true, updatedAt: true }, + }) + + // Journal d'audit : jamais la clé, seulement le fait qu'elle a changé. + await app.prisma.auditLog.create({ + data: { + treeId, + actorType: 'user', + actorId: request.actor.userId, + action: 'immich_config_updated', + entityType: 'tree_immich_config', + entityId: treeId, + payloadJson: { instanceId: instance.id, apiKeyChanged: Boolean(payload.data.apiKey) }, + }, + }) + + return reply.send({ config: immichConfigSummary(config) }) + }) + + app.delete('/trees/:id/immich/config', async (request, reply) => { + if (!request.actor || request.actor.kind !== 'user') { + return reply.code(401).send({ error: 'authentication_required' }) + } + + const params = treeParamSchema.safeParse(request.params) + if (!params.success) { + return reply.code(400).send({ error: 'invalid_params' }) + } + + if (!(await requireAdminMembership(app, request.actor.userId, params.data.id))) { + return reply.code(403).send({ error: 'forbidden' }) + } + + const treeId = params.data.id + const removed = await app.prisma.treeImmichConfig.deleteMany({ where: { treeId } }) + + if (removed.count > 0) { + await app.prisma.auditLog.create({ + data: { + treeId, + actorType: 'user', + actorId: request.actor.userId, + action: 'immich_config_removed', + entityType: 'tree_immich_config', + entityId: treeId, + payloadJson: {}, + }, + }) + } + + return reply.send({ config: { configured: false, keyNeedsReentry: false, instanceId: null, label: null, updatedAt: null } }) + }) + + app.get('/trees/:id/immich/status', async (request, reply) => { + if (!request.actor || request.actor.kind !== 'user') { + return reply.code(401).send({ error: 'authentication_required' }) + } + + const params = treeParamSchema.safeParse(request.params) + if (!params.success) { + return reply.code(400).send({ error: 'invalid_params' }) + } + + if (!(await requireAdminMembership(app, request.actor.userId, params.data.id))) { + return reply.code(403).send({ error: 'forbidden' }) + } + + const client = await getTreeImmichClient(app.prisma, params.data.id) + if (!client) { + return reply.send({ available: false, reason: 'not_configured' }) + } + + const available = await client.ping() + return reply.send({ available, reason: available ? null : 'unreachable' }) + }) + + app.get('/trees/:id/immich/people', async (request, reply) => { + if (!request.actor || request.actor.kind !== 'user') { + return reply.code(401).send({ error: 'authentication_required' }) + } + + const params = treeParamSchema.safeParse(request.params) + if (!params.success) { + return reply.code(400).send({ error: 'invalid_params' }) + } + + if (!(await requireAdminMembership(app, request.actor.userId, params.data.id))) { + return reply.code(403).send({ error: 'forbidden' }) + } + + const client = await getTreeImmichClient(app.prisma, params.data.id) + if (!client) { + return reply.code(503).send({ error: 'immich_not_configured' }) + } + + try { + const people = await client.listPeople() + return reply.send({ people }) + } catch (error) { + return replyImmichError(request, reply, error) + } + }) + + // Vignette d'une personne Immich, montrée dans le sélecteur. Passée par l'API : l'adresse + // d'Immich et sa clé ne quittent jamais le serveur. + app.get('/trees/:id/immich/thumbnail/:immichPersonId', async (request, reply) => { + if (!request.actor || request.actor.kind !== 'user') { + return reply.code(401).send({ error: 'authentication_required' }) + } + + const params = thumbnailParamSchema.safeParse(request.params) + if (!params.success) { + return reply.code(400).send({ error: 'invalid_immich_person_id' }) + } + + if (!(await requireAdminMembership(app, request.actor.userId, params.data.id))) { + return reply.code(403).send({ error: 'forbidden' }) + } + + const client = await getTreeImmichClient(app.prisma, params.data.id) + if (!client) { + return reply.code(503).send({ error: 'immich_not_configured' }) + } + + let thumbnail: Buffer | null + try { + thumbnail = await client.getPersonThumbnail(params.data.immichPersonId, MAX_THUMBNAIL_BYTES) + } catch (error) { + return replyImmichError(request, reply, error) + } + + // Le type se lit dans les octets, pas dans ce qu'Immich déclare : la vignette finit dans une + // balise . Vide, trop grande ou pas une image : rien à montrer. + const mimeType = thumbnail?.length ? sniffMimeType(thumbnail, 'photo') : null + if (!thumbnail || !mimeType?.startsWith('image/')) { + request.log.warn('Vignette Immich vide, trop grande ou qui n’est pas une image') + return reply.code(404).send({ error: 'thumbnail_not_found' }) + } + + reply.header('Content-Type', mimeType) + reply.header('X-Content-Type-Options', 'nosniff') + reply.header('Cache-Control', 'private, max-age=3600') + return reply.send(thumbnail) + }) + + // Personne Immich déjà associée à une fiche, pour la marquer dans le sélecteur. Réservé aux + // administrateurs : l'identifiant n'entre jamais dans le graphe public. + app.get('/trees/:id/immich/links/:personId', async (request, reply) => { + if (!request.actor || request.actor.kind !== 'user') { + return reply.code(401).send({ error: 'authentication_required' }) + } + + const params = treePersonParamsSchema.safeParse(request.params) + if (!params.success) { + return reply.code(400).send({ error: 'invalid_params' }) + } + + if (!(await requireAdminMembership(app, request.actor.userId, params.data.id))) { + return reply.code(403).send({ error: 'forbidden' }) + } + + const person = await app.prisma.person.findFirst({ + where: { id: params.data.personId, treeId: params.data.id, deletedAt: null }, + select: { immichPersonId: true }, + }) + if (!person) { + return reply.code(404).send({ error: 'person_not_found' }) + } + + return reply.send({ immichPersonId: person.immichPersonId }) + }) + + app.post('/trees/:id/immich/assign', async (request, reply) => { + if (!request.actor || request.actor.kind !== 'user') { + return reply.code(401).send({ error: 'authentication_required' }) + } + + const params = treeParamSchema.safeParse(request.params) + const payload = assignSchema.safeParse(request.body) + if (!params.success || !payload.success) { + return reply.code(400).send({ error: payload.success ? 'invalid_params' : 'invalid_immich_person_id' }) + } + + if (!(await requireAdminMembership(app, request.actor.userId, params.data.id))) { + return reply.code(403).send({ error: 'forbidden' }) + } + + const client = await getTreeImmichClient(app.prisma, params.data.id) + if (!client) { + return reply.code(503).send({ error: 'immich_not_configured' }) + } + + const { personId, immichPersonId } = payload.data + const treeId = params.data.id + + const person = await app.prisma.person.findFirst({ + where: { id: personId, treeId, deletedAt: null }, + select: { id: true, avatarPath: true }, + }) + if (!person) { + return reply.code(404).send({ error: 'person_not_found' }) + } + + // La personne Immich doit exister : le 404 de la vignette ne le prouve pas (personne + // absente ou simple vignette manquante), on la vérifie donc explicitement. Un refus + // d'authentification ou une erreur serveur ne sont jamais pris pour une absence. + let immichPerson: ImmichPersonSummary + try { + immichPerson = await client.getPerson(immichPersonId) + } catch (error) { + return replyImmichError(request, reply, error) + } + + // Vignette de la personne Immich : absente -> on associe sans toucher au portrait existant. + // Demandée seulement si Immich en annonce une : sans vignette, l'appel est inutile. + let thumbnail: Buffer | null = null + if (immichPerson.hasThumbnail) { + try { + thumbnail = await client.getPersonThumbnail(immichPersonId, MAX_THUMBNAIL_BYTES) + } catch (error) { + if (!(error instanceof ImmichNotFoundError)) { + return replyImmichError(request, reply, error) + } + // Vignette absente : l'association se fait sans portrait. + } + } + + if (!thumbnail) { + await app.prisma.$transaction([ + app.prisma.person.update({ + where: { id: personId }, + data: { immichPersonId, updatedBy: request.actor.userId }, + }), + app.prisma.auditLog.create({ + data: { + treeId, + actorType: 'user', + actorId: request.actor.userId, + action: 'immich_assign', + entityType: 'person', + entityId: personId, + payloadJson: { immichPersonId, avatarUpdated: false }, + }, + }), + ]) + + return reply.send({ ok: true, avatarUpdated: false, immichPersonId }) + } + + // Un portrait déjà en place ne se remplace jamais en silence : sans accord explicite, + // l'association s'arrête avant d'écrire quoi que ce soit. Le front transforme ce refus + // en demande de confirmation puis rejoue la requête avec replaceAvatar. + if (person.avatarPath && !payload.data.replaceAvatar) { + return reply.code(409).send({ error: 'avatar_exists' }) + } + + // La vignette passe par le même traitement qu'un portrait envoyé : type lu dans les octets, + // métadonnées retirées, quota de l'arbre respecté. + let prepared: Awaited> + try { + prepared = await prepareUploadedFile(thumbnail, 'photo', `immich-${immichPersonId}.jpg`) + } catch (error) { + if (error instanceof InvalidMediaError) { + return reply.code(400).send({ error: 'invalid_avatar_image' }) + } + throw error + } + + if (await exceedsStorageQuota(app, treeId, prepared.buffer.length, false)) { + return reply.code(413).send({ error: 'storage_quota_exceeded' }) + } + + const relativePath = buildAvatarRelativePath(treeId, personId, prepared.extension) + const storageRoot = getStorageRoot() + const absolutePath = path.resolve(storageRoot, relativePath) + + // Chemin hors du stockage : refusé, jamais écrit. + if (!absolutePath.startsWith(storageRoot + path.sep)) { + return reply.code(400).send({ error: 'invalid_media_path' }) + } + + // Fichier écrit avant la base : si la transaction échoue, on l'efface et rien n'a changé. + await mkdir(path.dirname(absolutePath), { recursive: true }) + await writeFile(absolutePath, prepared.buffer) + + try { + await app.prisma.$transaction([ + app.prisma.person.update({ + where: { id: personId }, + data: { + avatarPath: relativePath, + avatarMimeType: prepared.mimeType, + immichPersonId, + updatedBy: request.actor.userId, + }, + }), + app.prisma.auditLog.create({ + data: { + treeId, + actorType: 'user', + actorId: request.actor.userId, + action: 'immich_assign', + entityType: 'person', + entityId: personId, + payloadJson: { immichPersonId, avatarUpdated: true, avatarPath: relativePath }, + }, + }), + ]) + } catch (error) { + await removeStoredFile(storageRoot, relativePath).catch(() => {}) + request.log.error({ err: error }, 'Échec de l’association Immich : fichier de portrait retiré, base inchangée') + throw error + } + + // L'ancien portrait ne reste pas sur le disque. Un échec du nettoyage n'invalide pas + // l'association, qui a déjà réussi : il est journalisé, rien de plus. + if (person.avatarPath && person.avatarPath !== relativePath) { + await removeStoredFile(storageRoot, person.avatarPath).catch((cleanupError) => { + request.log.error( + { err: cleanupError, oldAvatar: person.avatarPath }, + 'Ancien portrait non supprimé après une association Immich', + ) + }) + } + + return reply.send({ ok: true, avatarUpdated: true, immichPersonId }) + }) + + app.post('/trees/:id/immich/unassign', async (request, reply) => { + if (!request.actor || request.actor.kind !== 'user') { + return reply.code(401).send({ error: 'authentication_required' }) + } + + const params = treeParamSchema.safeParse(request.params) + const payload = unassignSchema.safeParse(request.body) + if (!params.success || !payload.success) { + return reply.code(400).send({ error: 'invalid_params' }) + } + + if (!(await requireAdminMembership(app, request.actor.userId, params.data.id))) { + return reply.code(403).send({ error: 'forbidden' }) + } + + // Pas de garde « non configuré » ici : le retrait d'association ne parle jamais à Immich, + // et c'est le seul moyen de nettoyer des associations passées après une déconnexion. + const { personId } = payload.data + const treeId = params.data.id + + const person = await app.prisma.person.findFirst({ + where: { id: personId, treeId, deletedAt: null }, + select: { id: true, avatarPath: true, immichPersonId: true }, + }) + if (!person) { + return reply.code(404).send({ error: 'person_not_found' }) + } + + // Le graphe ne dit plus qui est associé : le retrait se propose toujours côté front. Sans + // association en place, il ne fait rien — pas d'écriture, pas d'entrée d'audit. + if (!person.immichPersonId) { + return reply.send({ ok: true, avatarRemoved: false }) + } + + // Le portrait vient d'Immich uniquement si son fichier porte notre préfixe. Un portrait + // envoyé à la main reste en place : seule l'association est retirée. + const avatarFromImmich = isImmichAvatarPath(person.avatarPath) + + const updateData: { + immichPersonId: null + updatedBy: string + avatarPath?: null + avatarMimeType?: null + } = { immichPersonId: null, updatedBy: request.actor.userId } + if (avatarFromImmich) { + updateData.avatarPath = null + updateData.avatarMimeType = null + } + + // Base d'abord, fichier ensuite : le portrait disparaît seulement une fois la base à jour. + await app.prisma.$transaction([ + app.prisma.person.update({ where: { id: personId }, data: updateData }), + app.prisma.auditLog.create({ + data: { + treeId, + actorType: 'user', + actorId: request.actor.userId, + action: 'immich_unassign', + entityType: 'person', + entityId: personId, + payloadJson: { previousImmichPersonId: person.immichPersonId, avatarRemoved: avatarFromImmich }, + }, + }), + ]) + + if (avatarFromImmich) { + await removeStoredFile(getStorageRoot(), person.avatarPath).catch((cleanupError) => { + request.log.error( + { err: cleanupError, avatarPath: person.avatarPath }, + 'Portrait Immich non supprimé après un désassignement (base à jour)', + ) + }) + } + + return reply.send({ ok: true, avatarRemoved: avatarFromImmich }) + }) +} diff --git a/backend/src/routes/media.ts b/backend/src/routes/media.ts index e77c0d8..335d7e6 100644 --- a/backend/src/routes/media.ts +++ b/backend/src/routes/media.ts @@ -92,7 +92,8 @@ function hasAdminRight(role: MembershipRole): boolean { return role === 'owner' || role === 'admin' } -function getStorageRoot(): string { +// Racine du stockage des médias : partagée avec les portraits venus d'Immich (routes/immich.ts). +export function getStorageRoot(): string { return path.resolve(env.MEDIA_STORAGE_PATH) } @@ -116,7 +117,7 @@ function normalizeOptionalText(value: string | null | undefined): string | null // Fichier décodé, reconnu à ses octets et nettoyé (photos sans métadonnées, vidéos sans position). // Le type déclaré par le navigateur n'est plus qu'un indice pour les conteneurs ambigus. -async function prepareUploadedFile( +export async function prepareUploadedFile( buffer: Buffer, type: BinaryMediaType, fileName: string, @@ -167,7 +168,7 @@ async function treeDiskUsage(treeId: string): Promise { } // Place disque d'un arbre : total, et part des envois en attente de relecture (limite l'envoi en boucle) -async function exceedsStorageQuota(app: FastifyRequest['server'], treeId: string, incomingBytes: number, isPending: boolean): Promise { +export async function exceedsStorageQuota(app: FastifyRequest['server'], treeId: string, incomingBytes: number, isPending: boolean): Promise { const MB = 1024 * 1024 if ((await treeDiskUsage(treeId)) + incomingBytes > env.MEDIA_QUOTA_PER_TREE_MB * MB) { return true @@ -190,7 +191,7 @@ const UPLOAD_RATE_LIMIT = { bodyLimit: UPLOAD_BODY_LIMIT, config: { rateLimit: { // retrouvées après un import GEDCOM), envoyées une par une. Le quota de stockage de l'arbre s'applique. const AVATAR_RATE_LIMIT = { bodyLimit: UPLOAD_BODY_LIMIT, config: { rateLimit: { max: 120, timeWindow: '1 minute' } } } -async function requireAdminMembership(app: FastifyRequest['server'], userId: string, treeId: string) { +export async function requireAdminMembership(app: FastifyRequest['server'], userId: string, treeId: string) { const membership = await app.prisma.treeMembership.findUnique({ where: { treeId_userId: { @@ -493,6 +494,7 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => { select: { id: true, avatarPath: true, + immichPersonId: true, }, }) @@ -553,6 +555,10 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => { avatarPath: relativePath, avatarMimeType: prepared.mimeType, updatedBy: request.actor.userId, + // Un portrait déposé à la main remplace aussi le lien Immich : sans cela, l'association + // survivrait invisible en base (le graphe ne publie que l'origine du portrait) et ne + // pourrait plus être retirée depuis l'interface. + ...(person.immichPersonId ? { immichPersonId: null } : {}), }, }) @@ -567,6 +573,7 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => { action: 'person_avatar_updated', entityType: 'person', entityId: params.data.personId, + ...(person.immichPersonId ? { payloadJson: { immichLinkRemoved: true } } : {}), }, }) @@ -602,6 +609,8 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => { data: { avatarPath: null, avatarMimeType: null, + // Retirer le portrait retire aussi le lien Immich : l'association ne survit pas au portrait. + immichPersonId: null, updatedBy: request.actor.userId, }, }) diff --git a/backend/src/utils/graph-payload.ts b/backend/src/utils/graph-payload.ts index ea847dc..4ae8370 100644 --- a/backend/src/utils/graph-payload.ts +++ b/backend/src/utils/graph-payload.ts @@ -1,6 +1,7 @@ import type { Annotation, MediaItem, ParentChildLink, Person, Union } from '@prisma/client' import { sanitizeAnnotationContentForRead } from '../lib/annotation-content.js' +import { isImmichAvatarPath } from '../lib/media-files.js' export type GraphPayload = { persons: Array<{ @@ -17,6 +18,7 @@ export type GraphPayload = { avatarUrlPath: string | null sex: string | null notes: string | null + avatarFromImmich: boolean }> unions: Array<{ id: string @@ -90,6 +92,7 @@ export function buildGraphPayload( avatarUrlPath: person.avatarPath ? `/trees/${treeId}/persons/${person.id}/avatar` : null, sex: person.sex, notes: person.notes, + avatarFromImmich: isImmichAvatarPath(person.avatarPath), })), unions: unions.map((union) => ({ id: union.id, diff --git a/backend/test/graph-payload.test.ts b/backend/test/graph-payload.test.ts index 2211b80..bb18e36 100644 --- a/backend/test/graph-payload.test.ts +++ b/backend/test/graph-payload.test.ts @@ -18,6 +18,7 @@ describe('buildGraphPayload', () => { sex: null, notes: null, avatarPath: 't-1/p-2/avatar.jpg', + immichPersonId: '123e4567-e89b-42d3-a456-426614174000', createdBy: null, updatedBy: null, createdAt: new Date(), @@ -41,6 +42,24 @@ describe('buildGraphPayload', () => { updatedAt: new Date(), deletedAt: null, }, + { + id: 'p-3', + treeId: 't-1', + firstName: 'Paul', + lastName: 'Durand', + birthName: null, + birthDate: null, + deathDate: null, + sex: 'male', + notes: null, + avatarPath: 't-1/p-3/immich-abc.jpg', + immichPersonId: '123e4567-e89b-42d3-a456-426614174999', + createdBy: null, + updatedBy: null, + createdAt: new Date(), + updatedAt: new Date(), + deletedAt: null, + }, ] as any, [ { @@ -97,6 +116,14 @@ describe('buildGraphPayload', () => { expect(graph.persons[0].birthDate).toBe('1994-06-02') expect(graph.persons[0].birthName).toBe('Durand') expect(graph.persons[0].avatarUrlPath).toBe('/trees/t-1/persons/p-2/avatar') + // L'identifiant Immich ne part jamais dans le graphe : il ne sert qu'aux administrateurs. + // Seule l'origine du portrait (fichier préfixé « immich- ») est publiée. + expect(graph.persons[0]).not.toHaveProperty('immichPersonId') + expect(graph.persons[1]).not.toHaveProperty('immichPersonId') + expect(graph.persons[2]).not.toHaveProperty('immichPersonId') + expect(graph.persons[0].avatarFromImmich).toBe(false) + expect(graph.persons[1].avatarFromImmich).toBe(false) + expect(graph.persons[2].avatarFromImmich).toBe(true) expect(graph.persons[1].avatarUrlPath).toBeNull() expect(graph.unions[0].id).toBe('u-1') expect(graph.filiations[0].viaUnionId).toBe('u-1') diff --git a/backend/test/immich-config.test.ts b/backend/test/immich-config.test.ts new file mode 100644 index 0000000..46b7175 --- /dev/null +++ b/backend/test/immich-config.test.ts @@ -0,0 +1,560 @@ +import { randomUUID } from 'node:crypto' +import type { FastifyInstance } from 'fastify' +import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' + +// Connexion Immich par arbre : chaque arbre porte ses identifiants en base, seuls ses +// administrateurs les configurent, et la clé d'API ne ressort jamais du serveur. + +const { prismaMock } = vi.hoisted(() => ({ + prismaMock: { + user: { + count: vi.fn(), + }, + person: { + findFirst: vi.fn(), + update: vi.fn(), + }, + treeMembership: { + findUnique: vi.fn(), + }, + treeImmichConfig: { + findUnique: vi.fn(), + upsert: vi.fn(), + deleteMany: vi.fn(), + }, + mediaItem: { + aggregate: vi.fn(), + }, + auditLog: { + create: vi.fn(), + }, + $transaction: vi.fn(), + $disconnect: vi.fn(), + }, +})) + +vi.mock('../src/lib/prisma.js', () => ({ + prisma: prismaMock, +})) + +let createApp: () => FastifyInstance +let encryptImmichApiKey: (value: string) => string +let TREE_1_ENC = '' +let TREE_2_ENC = '' +const fetchMock = vi.fn() + +async function createUserToken(app: FastifyInstance, userId = 'user-1'): Promise { + await app.ready() + return (app as any).jwt.sign( + { kind: 'user', sub: userId, jti: randomUUID(), userId, email: 'user@example.com' }, + { expiresIn: '1h' }, + ) +} + +beforeAll(async () => { + process.env.NODE_ENV = 'test' + process.env.PORT = '4000' + process.env.DATABASE_URL = 'postgresql://postgres:postgres@localhost:5432/genealogy' + process.env.JWT_SECRET = 'test-secret-with-sufficient-length' + process.env.JWT_EXPIRES_IN = '7d' + process.env.JWT_TREE_ACCESS_EXPIRES_IN = '24h' + process.env.CORS_ORIGIN = 'http://localhost:5173' + // Instances autorisées par l'opérateur du serveur : les administrateurs d'un arbre + // choisissent parmi elles, jamais en champ libre. + process.env.IMMICH_ALLOWED_API_URLS = 'http://immich-tree-1.test,http://immich-tree-2.test,Maison=http://immich.example.org:2283,http://immich.example.org,http://immich-moved.example.org' + + // Les clés chiffrées se calculent après la mise en place de JWT_SECRET, comme en production. + const secret = await import('../src/lib/immich-secret.js') + encryptImmichApiKey = secret.encryptImmichApiKey + TREE_1_ENC = encryptImmichApiKey('secret-key-tree-1') + TREE_2_ENC = encryptImmichApiKey('secret-key-tree-2') + + const module = await import('../src/app.js') + createApp = module.createApp + + vi.stubGlobal('fetch', fetchMock) +}) + +beforeEach(async () => { + vi.clearAllMocks() + + prismaMock.user.count.mockResolvedValue(1) + + // user-1 administre tree-1 ; user-2 administre tree-2. Jamais l'arbre de l'autre. + prismaMock.treeMembership.findUnique.mockImplementation(async ({ where }: { where: { treeId_userId?: { treeId: string; userId: string } } }) => { + const { treeId, userId } = where.treeId_userId ?? ({} as { treeId: string; userId: string }) + if (treeId === 'tree-1' && userId === 'user-1') { + return { treeId, userId, role: 'owner', tree: { deletedAt: null } } + } + if (treeId === 'tree-2' && userId === 'user-2') { + return { treeId, userId, role: 'owner', tree: { deletedAt: null } } + } + if (treeId === 'tree-1' && userId === 'user-member') { + return { treeId, userId, role: 'member', tree: { deletedAt: null } } + } + return null + }) + + prismaMock.treeImmichConfig.findUnique.mockImplementation(async ({ where }: { where: { treeId: string } }) => { + if (where.treeId === 'tree-1') { + return { apiUrl: 'http://immich-tree-1.test', apiKeyEnc: TREE_1_ENC, updatedAt: new Date('2026-10-01T00:00:00Z') } + } + if (where.treeId === 'tree-2') { + return { apiUrl: 'http://immich-tree-2.test', apiKeyEnc: TREE_2_ENC, updatedAt: new Date('2026-10-02T00:00:00Z') } + } + return null + }) + + prismaMock.treeImmichConfig.upsert.mockImplementation(async (args: { + create?: { apiUrl: string } + update?: { apiUrl: string } + }) => ({ + apiUrl: args.create?.apiUrl ?? args.update?.apiUrl, + apiKeyEnc: args.create?.apiKeyEnc ?? args.update?.apiKeyEnc, + updatedAt: new Date(), + })) + prismaMock.treeImmichConfig.deleteMany.mockResolvedValue({ count: 1 }) + prismaMock.auditLog.create.mockResolvedValue({ id: 'audit-1' }) + + fetchMock.mockReset() + fetchMock.mockResolvedValue(new Response(JSON.stringify({ res: 'pong' }), { status: 200, headers: { 'content-type': 'application/json' } })) +}) + +describe('Immich configuration: read', () => { + it('exposes only safe metadata, never the API key', async () => { + const app = createApp() + const token = await createUserToken(app) + + const response = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/config', + headers: { authorization: `Bearer ${token}` }, + }) + + expect(response.statusCode).toBe(200) + const body = response.json() + expect(body.config).toMatchObject({ configured: true, instanceId: 'c2ec51abd0edebf3', label: 'immich-tree-1.test' }) + const serialized = JSON.stringify(body) + // Aucune adresse brute : ni l'instance, ni la liste ne laissent voir une URL. + expect(serialized).not.toContain('http://') + expect(serialized).not.toContain('secret-key-tree-1') + expect(serialized).not.toContain('apiKey') + expect(serialized).not.toContain(TREE_1_ENC) + await app.close() + }) + + it('asks for the key again when it no longer decrypts, instead of reporting it configured', async () => { + const app = createApp() + const token = await createUserToken(app) + // Clé chiffrée avec un autre secret (JWT_SECRET changé) : illisible. + prismaMock.treeImmichConfig.findUnique.mockResolvedValue({ + apiUrl: 'http://immich-tree-1.test', + // Octets aléatoires au bon format : le déchiffrement échoue (authentification GCM). + apiKeyEnc: `v1:${Buffer.alloc(64, 7).toString('base64')}`, + updatedAt: new Date('2026-10-01T00:00:00Z'), + }) + + const response = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/config', + headers: { authorization: `Bearer ${token}` }, + }) + + expect(response.json().config).toEqual({ + configured: false, + keyNeedsReentry: true, + instanceId: 'c2ec51abd0edebf3', + label: 'immich-tree-1.test', + updatedAt: '2026-10-01T00:00:00.000Z', + }) + + // La connexion ne sert à rien tant que la clé n'est pas ressaisie. + const status = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/status', + headers: { authorization: `Bearer ${token}` }, + }) + expect(status.json()).toEqual({ available: false, reason: 'not_configured' }) + await app.close() + }) + + it('refuses to keep an unreadable key when the address is saved again', async () => { + const app = createApp() + const token = await createUserToken(app) + prismaMock.treeImmichConfig.findUnique.mockResolvedValueOnce({ + apiUrl: 'http://immich-tree-1.test', + apiKeyEnc: 'v1:ce-texte-ne-se-dechiffre-pas', + updatedAt: new Date('2026-10-01T00:00:00Z'), + }) + + const response = await app.inject({ + method: 'PUT', + url: '/trees/tree-1/immich/config', + headers: { authorization: `Bearer ${token}` }, + payload: { instanceId: 'c2ec51abd0edebf3' }, + }) + + expect(response.statusCode).toBe(400) + expect(response.json()).toEqual({ error: 'api_key_required' }) + expect(prismaMock.treeImmichConfig.upsert).not.toHaveBeenCalled() + await app.close() + }) + + it('reports a tree without a configuration row as not configured', async () => { + const app = createApp() + const token = await createUserToken(app) + prismaMock.treeImmichConfig.findUnique.mockResolvedValue(null) + + const response = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/config', + headers: { authorization: `Bearer ${token}` }, + }) + + // Un arbre fraîchement créé n'a pas de ligne : rien de configuré, rien d'hérité. + expect(response.statusCode).toBe(200) + expect(response.json().config).toEqual({ configured: false, keyNeedsReentry: false, instanceId: null, label: null, updatedAt: null }) + expect(response.json().instances).toEqual([ + { id: 'c2ec51abd0edebf3', label: 'immich-tree-1.test' }, + { id: '0715d0c35f2b0405', label: 'immich-tree-2.test' }, + { id: '6fc8e421ad9b5371', label: 'Maison' }, + { id: '2c47e4ca85342f88', label: 'immich.example.org' }, + { id: '2d46a51941003fcd', label: 'immich-moved.example.org' }, + ]) + expect(JSON.stringify(response.json())).not.toContain('http://') + await app.close() + }) +}) + +describe('Immich configuration: write', () => { + it('lets a tree administrator configure their tree, key encrypted and audited without secret', async () => { + const app = createApp() + const token = await createUserToken(app) + prismaMock.treeImmichConfig.findUnique.mockResolvedValue(null) + + const response = await app.inject({ + method: 'PUT', + url: '/trees/tree-1/immich/config', + headers: { authorization: `Bearer ${token}` }, + payload: { instanceId: '6fc8e421ad9b5371', apiKey: 'my-new-key' }, + }) + + expect(response.statusCode).toBe(200) + expect(response.json().config).toMatchObject({ configured: true, instanceId: '6fc8e421ad9b5371', label: 'Maison' }) + // L'adresse stockée est celle de la liste de l'opérateur, jamais une valeur envoyée par le client. + expect(prismaMock.treeImmichConfig.upsert.mock.calls[0][0].create.apiUrl).toBe('http://immich.example.org:2283') + + const upsertArgs = prismaMock.treeImmichConfig.upsert.mock.calls[0][0] + expect(upsertArgs.where).toEqual({ treeId: 'tree-1' }) + expect(upsertArgs.create.apiKeyEnc).not.toContain('my-new-key') + expect(upsertArgs.create.apiKeyEnc).toMatch(/^v1:/) + expect(upsertArgs.update.apiKeyEnc).toBe(upsertArgs.create.apiKeyEnc) + + expect(prismaMock.auditLog.create).toHaveBeenCalledWith({ + data: { + treeId: 'tree-1', + actorType: 'user', + actorId: 'user-1', + action: 'immich_config_updated', + entityType: 'tree_immich_config', + entityId: 'tree-1', + payloadJson: { instanceId: '6fc8e421ad9b5371', apiKeyChanged: true }, + }, + }) + + expect(JSON.stringify(response.json())).not.toContain('my-new-key') + await app.close() + }) + + it('keeps the existing key when the same address is saved again', async () => { + const app = createApp() + const token = await createUserToken(app) + + const response = await app.inject({ + method: 'PUT', + url: '/trees/tree-1/immich/config', + headers: { authorization: `Bearer ${token}` }, + payload: { instanceId: 'c2ec51abd0edebf3' }, + }) + + expect(response.statusCode).toBe(200) + expect(response.json().config.instanceId).toBe('c2ec51abd0edebf3') + + const upsertArgs = prismaMock.treeImmichConfig.upsert.mock.calls[0][0] + // La clé en place est conservée telle quelle : pas de nouvelle clé, pas de déchiffrage. + expect(upsertArgs.create.apiKeyEnc).toBe(TREE_1_ENC) + expect(upsertArgs.update.apiKeyEnc).toBe(TREE_1_ENC) + expect(prismaMock.auditLog.create.mock.calls[0][0].data.payloadJson).toEqual({ + instanceId: 'c2ec51abd0edebf3', + apiKeyChanged: false, + }) + await app.close() + }) + + it('requires a new key when the address changes: the old key never travels', async () => { + const app = createApp() + const token = await createUserToken(app) + + const response = await app.inject({ + method: 'PUT', + url: '/trees/tree-1/immich/config', + headers: { authorization: `Bearer ${token}` }, + payload: { instanceId: '2d46a51941003fcd' }, + }) + + // La clé de l'ancienne instance ne vaut rien pour la nouvelle, et ne lui est jamais + // envoyée : il faut une nouvelle clé, rien n'est écrit sans elle. + expect(response.statusCode).toBe(400) + expect(response.json()).toEqual({ error: 'api_key_required' }) + expect(prismaMock.treeImmichConfig.upsert).not.toHaveBeenCalled() + await app.close() + }) + + it('requires a key for a first configuration', async () => { + const app = createApp() + const token = await createUserToken(app) + prismaMock.treeImmichConfig.findUnique.mockResolvedValue(null) + + const response = await app.inject({ + method: 'PUT', + url: '/trees/tree-1/immich/config', + headers: { authorization: `Bearer ${token}` }, + payload: { instanceId: '2c47e4ca85342f88' }, + }) + + expect(response.statusCode).toBe(400) + expect(response.json()).toEqual({ error: 'api_key_required' }) + expect(prismaMock.treeImmichConfig.upsert).not.toHaveBeenCalled() + await app.close() + }) + + it('rejects an identifier that is not an instance id', async () => { + const app = createApp() + const token = await createUserToken(app) + + const response = await app.inject({ + method: 'PUT', + url: '/trees/tree-1/immich/config', + headers: { authorization: `Bearer ${token}` }, + payload: { instanceId: 'ftp://immich.example.org', apiKey: 'my-new-key' }, + }) + + expect(response.statusCode).toBe(400) + expect(response.json().error).toBe('invalid_payload') + expect(prismaMock.treeImmichConfig.upsert).not.toHaveBeenCalled() + await app.close() + }) + + it('refuses non-administrators and other trees', async () => { + const app = createApp() + const ownerToken = await createUserToken(app) + const memberToken = await createUserToken(app, 'user-member') + + const member = await app.inject({ + method: 'PUT', + url: '/trees/tree-1/immich/config', + headers: { authorization: `Bearer ${memberToken}` }, + payload: { instanceId: '2c47e4ca85342f88', apiKey: 'stolen-key' }, + }) + expect(member.statusCode).toBe(403) + + // L'administrateur de tree-1 ne touche pas la configuration de tree-2. + const otherTree = await app.inject({ + method: 'PUT', + url: '/trees/tree-2/immich/config', + headers: { authorization: `Bearer ${ownerToken}` }, + payload: { instanceId: '2c47e4ca85342f88', apiKey: 'evil-key' }, + }) + expect(otherTree.statusCode).toBe(403) + + const anonymous = await app.inject({ + method: 'PUT', + url: '/trees/tree-1/immich/config', + payload: { instanceId: '2c47e4ca85342f88', apiKey: 'key' }, + }) + expect(anonymous.statusCode).toBe(401) + + expect(prismaMock.treeImmichConfig.upsert).not.toHaveBeenCalled() + expect(prismaMock.auditLog.create).not.toHaveBeenCalled() + await app.close() + }) +}) + +describe('Immich configuration: removal', () => { + it('revokes the tree access and audits the removal', async () => { + const app = createApp() + const token = await createUserToken(app) + + const response = await app.inject({ + method: 'DELETE', + url: '/trees/tree-1/immich/config', + headers: { authorization: `Bearer ${token}` }, + }) + + expect(response.statusCode).toBe(200) + expect(response.json().config).toEqual({ configured: false, keyNeedsReentry: false, instanceId: null, label: null, updatedAt: null }) + expect(prismaMock.treeImmichConfig.deleteMany).toHaveBeenCalledWith({ where: { treeId: 'tree-1' } }) + expect(prismaMock.auditLog.create).toHaveBeenCalledWith({ + data: { + treeId: 'tree-1', + actorType: 'user', + actorId: 'user-1', + action: 'immich_config_removed', + entityType: 'tree_immich_config', + entityId: 'tree-1', + payloadJson: {}, + }, + }) + + // Une fois la configuration retirée, plus aucun appel vers l'instance ne part. + prismaMock.treeImmichConfig.findUnique.mockResolvedValue(null) + fetchMock.mockClear() + const people = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/people', + headers: { authorization: `Bearer ${token}` }, + }) + expect(people.statusCode).toBe(503) + expect(people.json()).toEqual({ error: 'immich_not_configured' }) + expect(fetchMock).not.toHaveBeenCalled() + await app.close() + }) + + it('refuses removal by a non-administrator or on another tree', async () => { + const app = createApp() + const ownerToken = await createUserToken(app) + const memberToken = await createUserToken(app, 'user-member') + + const member = await app.inject({ + method: 'DELETE', + url: '/trees/tree-1/immich/config', + headers: { authorization: `Bearer ${memberToken}` }, + }) + expect(member.statusCode).toBe(403) + + const otherTree = await app.inject({ + method: 'DELETE', + url: '/trees/tree-2/immich/config', + headers: { authorization: `Bearer ${ownerToken}` }, + }) + expect(otherTree.statusCode).toBe(403) + + expect(prismaMock.treeImmichConfig.deleteMany).not.toHaveBeenCalled() + await app.close() + }) +}) + +describe('Immich credentials: tree isolation', () => { + it('uses tree 2 credentials for tree 2 requests, never tree 1 credentials', async () => { + const app = createApp() + const token2 = await createUserToken(app, 'user-2') + + fetchMock.mockImplementation(async () => new Response(JSON.stringify({ people: [], total: 0, hasNextPage: false }), { status: 200, headers: { 'content-type': 'application/json' } })) + + const response = await app.inject({ + method: 'GET', + url: '/trees/tree-2/immich/people', + headers: { authorization: `Bearer ${token2}` }, + }) + + expect(response.statusCode).toBe(200) + expect(String(fetchMock.mock.calls[0][0])).toBe('http://immich-tree-2.test/api/people?page=1&size=1000') + expect((fetchMock.mock.calls[0][1] as RequestInit).headers).toMatchObject({ 'x-api-key': 'secret-key-tree-2' }) + expect(prismaMock.treeImmichConfig.findUnique).toHaveBeenCalledWith({ + where: { treeId: 'tree-2' }, + select: { apiUrl: true, apiKeyEnc: true }, + }) + await app.close() + }) + + it('refuses tree 1 credentials to serve tree 2 requests', async () => { + const app = createApp() + const token1 = await createUserToken(app, 'user-1') + + // user-1 administre tree-1 mais pas tree-2 : refus avant toute résolution de configuration. + const response = await app.inject({ + method: 'GET', + url: '/trees/tree-2/immich/people', + headers: { authorization: `Bearer ${token1}` }, + }) + + expect(response.statusCode).toBe(403) + expect(response.json()).toEqual({ error: 'forbidden' }) + expect(fetchMock).not.toHaveBeenCalled() + await app.close() + }) +}) + +describe('Immich configuration: operator allowlist', () => { + it('rejects an instance outside the list and changes nothing', async () => { + const app = createApp() + const token = await createUserToken(app) + + const response = await app.inject({ + method: 'PUT', + url: '/trees/tree-1/immich/config', + headers: { authorization: `Bearer ${token}` }, + payload: { instanceId: '1234567890abcdef', apiKey: 'stolen-key' }, + }) + + // Le serveur ne devient jamais un proxy vers un service interne choisi librement. + expect(response.statusCode).toBe(400) + expect(response.json()).toEqual({ error: 'instance_not_allowed' }) + expect(prismaMock.treeImmichConfig.upsert).not.toHaveBeenCalled() + expect(prismaMock.auditLog.create).not.toHaveBeenCalled() + await app.close() + }) + + it('stores the canonical address of the instance chosen by its identifier', async () => { + const app = createApp() + const token = await createUserToken(app) + + const response = await app.inject({ + method: 'PUT', + url: '/trees/tree-1/immich/config', + headers: { authorization: `Bearer ${token}` }, + payload: { instanceId: 'c2ec51abd0edebf3', apiKey: 'my-new-key' }, + }) + + expect(response.statusCode).toBe(200) + expect(response.json().config).toMatchObject({ configured: true, instanceId: 'c2ec51abd0edebf3', label: 'immich-tree-1.test' }) + expect(prismaMock.treeImmichConfig.upsert.mock.calls[0][0].create.apiUrl).toBe('http://immich-tree-1.test') + await app.close() + }) + + it('stops using a stored connection whose address left the list', async () => { + const app = createApp() + const token = await createUserToken(app) + prismaMock.treeImmichConfig.findUnique.mockResolvedValue({ + apiUrl: 'http://removed.example.org', + apiKeyEnc: TREE_1_ENC, + updatedAt: new Date('2026-10-01T00:00:00Z'), + }) + + // La connexion stockée devient « non configurée » : l'adresse n'est plus autorisée. + const config = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/config', + headers: { authorization: `Bearer ${token}` }, + }) + expect(config.statusCode).toBe(200) + expect(config.json().config).toEqual({ configured: false, keyNeedsReentry: false, instanceId: null, label: null, updatedAt: null }) + + const status = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/status', + headers: { authorization: `Bearer ${token}` }, + }) + expect(status.json()).toEqual({ available: false, reason: 'not_configured' }) + + const people = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/people', + headers: { authorization: `Bearer ${token}` }, + }) + expect(people.statusCode).toBe(503) + expect(people.json()).toEqual({ error: 'immich_not_configured' }) + expect(fetchMock).not.toHaveBeenCalled() + await app.close() + }) +}) diff --git a/backend/test/immich-unconfigured.test.ts b/backend/test/immich-unconfigured.test.ts new file mode 100644 index 0000000..5c0695f --- /dev/null +++ b/backend/test/immich-unconfigured.test.ts @@ -0,0 +1,174 @@ +import { randomUUID } from 'node:crypto' +import type { FastifyInstance } from 'fastify' +import { beforeAll, describe, expect, it, vi } from 'vitest' + +// Arbre sans connexion Immich : aucune requête vers une instance ne doit partir, chaque route +// qui parle à l'instance répond « non configuré » — sauf le retrait d'association, purement +// local. Les variables d'environnement du serveur, même renseignées, ne servent plus à rien : +// la configuration vit par arbre, en base. Fichier à part : on appelle l'application dans une +// session de test sans configuration Immich pour tree-1. + +const { prismaMock } = vi.hoisted(() => ({ + prismaMock: { + user: { + count: vi.fn().mockResolvedValue(1), + }, + person: { + findFirst: vi.fn(), + update: vi.fn(), + }, + treeMembership: { + findUnique: vi.fn(), + }, + treeImmichConfig: { + findUnique: vi.fn(), + }, + auditLog: { + create: vi.fn(), + }, + $transaction: vi.fn(), + $disconnect: vi.fn(), + }, +})) + +vi.mock('../src/lib/prisma.js', () => ({ + prisma: prismaMock, +})) + +let createApp: () => FastifyInstance + +beforeAll(async () => { + // Même renseignées, ces variables ne donnent accès à rien : elles ne sont plus lues. + process.env.IMMICH_ENABLED = 'true' + process.env.IMMICH_API_URL = 'http://immich.example.org' + process.env.IMMICH_API_KEY = 'global-key' + // Aucune instance autorisée : explicite, pour ne pas hériter de la liste d'un .env local. + process.env.IMMICH_ALLOWED_API_URLS = '' + + process.env.NODE_ENV = 'test' + process.env.PORT = '4000' + process.env.DATABASE_URL = 'postgresql://postgres:postgres@localhost:5432/genealogy' + process.env.JWT_SECRET = 'test-secret-with-sufficient-length' + process.env.JWT_EXPIRES_IN = '7d' + process.env.JWT_TREE_ACCESS_EXPIRES_IN = '24h' + process.env.CORS_ORIGIN = 'http://localhost:5173' + + const module = await import('../src/app.js') + createApp = module.createApp +}) + +describe('Immich integration: tree without configuration', () => { + it('reports not configured, never calls Immich, and never falls back to server credentials', async () => { + const app = createApp() + await app.ready() + const token = (app as any).jwt.sign( + { kind: 'user', sub: 'user-1', jti: randomUUID(), userId: 'user-1', email: 'user@example.com' }, + { expiresIn: '1h' }, + ) + + prismaMock.treeMembership.findUnique.mockResolvedValue({ + treeId: 'tree-1', + userId: 'user-1', + role: 'owner', + tree: { deletedAt: null }, + }) + // Aucune ligne de configuration pour cet arbre : il vient d'être créé. + prismaMock.treeImmichConfig.findUnique.mockResolvedValue(null) + + const fetchMock = vi.fn() + vi.stubGlobal('fetch', fetchMock) + + const status = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/status', + headers: { authorization: `Bearer ${token}` }, + }) + expect(status.statusCode).toBe(200) + expect(status.json()).toEqual({ available: false, reason: 'not_configured' }) + + const config = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/config', + headers: { authorization: `Bearer ${token}` }, + }) + expect(config.statusCode).toBe(200) + expect(config.json().config).toEqual({ configured: false, keyNeedsReentry: false, instanceId: null, label: null, updatedAt: null }) + // Aucune instance autorisée par l'opérateur : le menu des adresses est vide. + expect(config.json().instances).toEqual([]) + + const people = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/people', + headers: { authorization: `Bearer ${token}` }, + }) + expect(people.statusCode).toBe(503) + expect(people.json()).toEqual({ error: 'immich_not_configured' }) + + const thumbnail = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/thumbnail/123e4567-e89b-42d3-a456-426614174000', + headers: { authorization: `Bearer ${token}` }, + }) + expect(thumbnail.statusCode).toBe(503) + expect(thumbnail.json()).toEqual({ error: 'immich_not_configured' }) + + const assign = await app.inject({ + method: 'POST', + url: '/trees/tree-1/immich/assign', + headers: { authorization: `Bearer ${token}` }, + payload: { personId: 'person-1', immichPersonId: '123e4567-e89b-42d3-a456-426614174000' }, + }) + expect(assign.statusCode).toBe(503) + expect(assign.json()).toEqual({ error: 'immich_not_configured' }) + + // Le retrait d'association reste possible sans connexion : il nettoie des associations + // passées sans jamais parler à Immich. + prismaMock.person.findFirst.mockResolvedValue({ + id: 'person-1', + avatarPath: null, + immichPersonId: '123e4567-e89b-42d3-a456-426614174000', + }) + const unassign = await app.inject({ + method: 'POST', + url: '/trees/tree-1/immich/unassign', + headers: { authorization: `Bearer ${token}` }, + payload: { personId: 'person-1' }, + }) + expect(unassign.statusCode).toBe(200) + expect(unassign.json()).toEqual({ ok: true, avatarRemoved: false }) + + // Un arbre sans configuration ne parle jamais à Immich, ni à celle du serveur. + expect(fetchMock).not.toHaveBeenCalled() + vi.unstubAllGlobals() + await app.close() + }) + + it('refuses any address when the operator has authorized no instance', async () => { + const app = createApp() + await app.ready() + const token = (app as any).jwt.sign( + { kind: 'user', sub: 'user-1', jti: randomUUID(), userId: 'user-1', email: 'user@example.com' }, + { expiresIn: '1h' }, + ) + + prismaMock.treeMembership.findUnique.mockResolvedValue({ + treeId: 'tree-1', + userId: 'user-1', + role: 'owner', + tree: { deletedAt: null }, + }) + prismaMock.treeImmichConfig.findUnique.mockResolvedValue(null) + + // Liste vide côté opérateur : aucune adresse ne peut être configurée, la fonction reste éteinte. + const response = await app.inject({ + method: 'PUT', + url: '/trees/tree-1/immich/config', + headers: { authorization: `Bearer ${token}` }, + payload: { instanceId: '2c47e4ca85342f88', apiKey: 'some-key' }, + }) + + expect(response.statusCode).toBe(400) + expect(response.json()).toEqual({ error: 'instance_not_allowed' }) + await app.close() + }) +}) diff --git a/backend/test/immich.test.ts b/backend/test/immich.test.ts new file mode 100644 index 0000000..a715001 --- /dev/null +++ b/backend/test/immich.test.ts @@ -0,0 +1,1061 @@ +import { randomUUID } from 'node:crypto' +import { mkdtemp, mkdir, rm, writeFile, stat, readdir } from 'node:fs/promises' +import path from 'node:path' +import os from 'node:os' +import sharp from 'sharp' + +import type { FastifyInstance } from 'fastify' +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' + +const { prismaMock } = vi.hoisted(() => ({ + prismaMock: { + user: { + count: vi.fn(), + }, + person: { + findFirst: vi.fn(), + update: vi.fn(), + updateMany: vi.fn(), + }, + treeMembership: { + findUnique: vi.fn(), + }, + treeImmichConfig: { + findUnique: vi.fn(), + }, + mediaItem: { + aggregate: vi.fn(), + }, + auditLog: { + create: vi.fn(), + }, + $transaction: vi.fn(), + $disconnect: vi.fn(), + }, +})) + +vi.mock('../src/lib/prisma.js', () => ({ + prisma: prismaMock, +})) + +let createApp: () => FastifyInstance +let storageRoot: string +let jpegBytes: Buffer +let treeApiKeyEnc = '' +const immichPersonId = '123e4567-e89b-42d3-a456-426614174000' +const otherImmichId = '123e4567-e89b-42d3-a456-426614174111' + +const fetchMock = vi.fn() + +async function jsonResponse(payload: unknown, status = 200): Promise { + return new Response(JSON.stringify(payload), { status, headers: { 'content-type': 'application/json' } }) +} + +// Association : deux appels Immich possibles, la personne (JSON) puis sa vignette (image). +// Le 404 de /api/people/{id} dit que la personne n'existe pas ; celui de /thumbnail seul +// ne dit rien (personne absente ou vignette manquante). +function mockImmichPerson(options: { thumbnailPath?: string; thumbnailStatus?: number } = {}): void { + const { thumbnailPath = '/thumb/a.jpg', thumbnailStatus = 200 } = options + fetchMock.mockImplementation(async (input: RequestInfo | URL) => { + const url = String(input) + if (url.endsWith('/thumbnail')) { + return new Response(new Uint8Array(jpegBytes), { status: thumbnailStatus }) + } + return jsonResponse({ id: immichPersonId, name: 'Jean Dupont', thumbnailPath, isHidden: false, birthDate: null }) + }) +} + +async function createUserToken(app: FastifyInstance, userId = 'user-1'): Promise { + await app.ready() + return (app as any).jwt.sign( + { kind: 'user', sub: userId, jti: randomUUID(), userId, email: 'user@example.com' }, + { expiresIn: '1h' }, + ) +} + +async function absStoragePath(relativePath: string): Promise { + return path.resolve(storageRoot, relativePath) +} + +async function fsExists(absolutePath: string): Promise { + try { + await stat(absolutePath) + return true + } catch { + return false + } +} + +async function fsListDir(absolutePath: string): Promise { + try { + return await readdir(absolutePath) + } catch { + return [] + } +} + +beforeAll(async () => { + process.env.NODE_ENV = 'test' + process.env.PORT = '4000' + process.env.DATABASE_URL = 'postgresql://postgres:postgres@localhost:5432/genealogy' + process.env.JWT_SECRET = 'test-secret-with-sufficient-length' + process.env.JWT_EXPIRES_IN = '7d' + process.env.JWT_TREE_ACCESS_EXPIRES_IN = '24h' + process.env.CORS_ORIGIN = 'http://localhost:5173' + // Plus de variables d'environnement Immich : la connexion de l'arbre vit en base, + // un arbre sans ligne n'a jamais accès à l'instance d'un autre. + process.env.IMMICH_ENABLED = 'true' + process.env.IMMICH_API_URL = 'http://env-immich.example.org' + process.env.IMMICH_API_KEY = 'env-key' + // L'instance de l'arbre fait partie de la liste autorisée par l'opérateur. + process.env.IMMICH_ALLOWED_API_URLS = 'http://immich.test,Partage=http://immich.test/immich' + + storageRoot = await mkdtemp(path.join(os.tmpdir(), 'parenthese-immich-')) + process.env.MEDIA_STORAGE_PATH = storageRoot + // Quota serré pour le tester : le disque est mesuré en vrai (taille du dossier de l'arbre). + process.env.MEDIA_QUOTA_PER_TREE_MB = '1' + + jpegBytes = await sharp({ create: { width: 8, height: 8, channels: 3, background: '#aabbcc' } }).jpeg().toBuffer() + + // Clé chiffrée avec le secret effectif de l'application : import dynamique pour que + // la configuration d'environnement ci-dessus soit déjà en place. + const secret = await import('../src/lib/immich-secret.js') + treeApiKeyEnc = secret.encryptImmichApiKey('test-key') + + const module = await import('../src/app.js') + createApp = module.createApp + + vi.stubGlobal('fetch', fetchMock) +}) + +afterAll(async () => { + await rm(storageRoot, { recursive: true, force: true }) + vi.unstubAllGlobals() +}) + +beforeEach(async () => { + vi.clearAllMocks() + + prismaMock.user.count.mockResolvedValue(1) + + // La transaction de l'API prend un tableau d'opérations ; les autres tests du dépôt utilisent la forme callback. + prismaMock.$transaction.mockImplementation(async (input: unknown) => { + if (Array.isArray(input)) { + return Promise.all(input) + } + return (input as (tx: typeof prismaMock) => Promise)(prismaMock) + }) + + prismaMock.treeMembership.findUnique.mockResolvedValue({ + treeId: 'tree-1', + userId: 'user-1', + role: 'owner', + tree: { deletedAt: null }, + }) + + // Connexion Immich de l'arbre : résolue en base, clé chiffrée comme en production. + prismaMock.treeImmichConfig.findUnique.mockResolvedValue({ apiUrl: 'http://immich.test', apiKeyEnc: treeApiKeyEnc }) + + prismaMock.person.findFirst.mockResolvedValue(null) + prismaMock.person.update.mockResolvedValue({ id: 'person-1' }) + prismaMock.person.updateMany.mockResolvedValue({ count: 1 }) + prismaMock.auditLog.create.mockResolvedValue({ id: 'audit-1' }) + prismaMock.mediaItem.aggregate.mockResolvedValue({ _sum: { sizeBytes: 0 } }) + + fetchMock.mockReset() + fetchMock.mockResolvedValue(await jsonResponse({ res: 'pong' })) +}) + +describe('Immich integration: status and people', () => { + it('talks to the tree\'s own Immich instance, never to the server environment', async () => { + const app = createApp() + const token = await createUserToken(app) + fetchMock.mockResolvedValue(await jsonResponse({ res: 'pong' })) + + const response = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/status', + headers: { authorization: `Bearer ${token}` }, + }) + + expect(response.statusCode).toBe(200) + expect(response.json()).toEqual({ available: true, reason: null }) + + // La connexion vient de la base (http://immich.test), pas des variables d'environnement + // (http://env-immich.example.org), et la clé passe par l'en-tête, jamais dans l'URL. + expect(fetchMock).toHaveBeenCalledTimes(1) + expect(String(fetchMock.mock.calls[0][0])).toBe('http://immich.test/api/server/ping') + expect((fetchMock.mock.calls[0][1] as RequestInit).headers).toMatchObject({ 'x-api-key': 'test-key' }) + + // La clé est lue depuis l'arbre demandé, pas depuis un autre. + expect(prismaMock.treeImmichConfig.findUnique).toHaveBeenCalledWith({ + where: { treeId: 'tree-1' }, + select: { apiUrl: true, apiKeyEnc: true }, + }) + await app.close() + }) + + it('reports Immich available when ping answers pong', async () => { + const app = createApp() + const token = await createUserToken(app) + fetchMock.mockResolvedValue(await jsonResponse({ res: 'pong' })) + + const response = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/status', + headers: { authorization: `Bearer ${token}` }, + }) + + expect(response.statusCode).toBe(200) + expect(response.json()).toEqual({ available: true, reason: null }) + await app.close() + }) + + it('reports Immich unreachable when ping fails', async () => { + const app = createApp() + const token = await createUserToken(app) + fetchMock.mockRejectedValue(new Error('network down')) + + const response = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/status', + headers: { authorization: `Bearer ${token}` }, + }) + + expect(response.statusCode).toBe(200) + expect(response.json()).toEqual({ available: false, reason: 'unreachable' }) + await app.close() + }) + + it('rejects unauthenticated and non-admin requests on status', async () => { + const app = createApp() + + const anonymous = await app.inject({ method: 'GET', url: '/trees/tree-1/immich/status' }) + expect(anonymous.statusCode).toBe(401) + + const token = await createUserToken(app) + prismaMock.treeMembership.findUnique.mockResolvedValue({ + treeId: 'tree-1', + userId: 'user-1', + role: 'member', + tree: { deletedAt: null }, + }) + const member = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/status', + headers: { authorization: `Bearer ${token}` }, + }) + expect(member.statusCode).toBe(403) + await app.close() + }) + + it('lists people across Immich pages', async () => { + const app = createApp() + const token = await createUserToken(app) + fetchMock.mockImplementation(async (input: RequestInfo | URL) => { + const url = String(input) + if (url.includes('/api/people?')) { + const page = url.includes('page=2') ? 2 : 1 + if (page === 1) { + return jsonResponse({ + people: [{ id: immichPersonId, name: 'Jean Dupont', thumbnailPath: '/thumb/a.jpg', isHidden: false, birthDate: null }], + total: 2, + hasNextPage: true, + hidden: 0, + }) + } + return jsonResponse({ + people: [{ id: otherImmichId, name: 'Marie Martin', thumbnailPath: '', isHidden: false, birthDate: null }], + total: 2, + hasNextPage: false, + hidden: 0, + }) + } + return jsonResponse({ res: 'pong' }) + }) + + const response = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/people', + headers: { authorization: `Bearer ${token}` }, + }) + + expect(response.statusCode).toBe(200) + expect(response.json().people).toEqual([ + { id: immichPersonId, name: 'Jean Dupont', hasThumbnail: true }, + { id: otherImmichId, name: 'Marie Martin', hasThumbnail: false }, + ]) + await app.close() + }) + + it('maps an Immich auth failure to 502 and a malformed response to 503', async () => { + const app = createApp() + const token = await createUserToken(app) + fetchMock.mockResolvedValue(new Response(JSON.stringify({ message: 'Invalid API key' }), { status: 401 })) + + const authFailure = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/people', + headers: { authorization: `Bearer ${token}` }, + }) + expect(authFailure.statusCode).toBe(502) + expect(authFailure.json()).toEqual({ error: 'immich_auth_failed' }) + + fetchMock.mockResolvedValue(await jsonResponse({ total: 0, hasNextPage: false })) + const malformed = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/people', + headers: { authorization: `Bearer ${token}` }, + }) + expect(malformed.statusCode).toBe(503) + expect(malformed.json()).toEqual({ error: 'immich_unreachable' }) + await app.close() + }) +}) + +describe('Immich integration: thumbnail proxy', () => { + it('proxies a thumbnail with its sniffed content type', async () => { + const app = createApp() + const token = await createUserToken(app) + fetchMock.mockResolvedValue(new Response(new Uint8Array(jpegBytes), { status: 200 })) + + const response = await app.inject({ + method: 'GET', + url: `/trees/tree-1/immich/thumbnail/${immichPersonId}`, + headers: { authorization: `Bearer ${token}` }, + }) + + expect(response.statusCode).toBe(200) + expect(response.headers['content-type']).toContain('image/jpeg') + expect(Buffer.from(response.rawPayload).equals(jpegBytes)).toBe(true) + await app.close() + }) + + it('returns 404 when the thumbnail is missing and 400 for a malformed identifier', async () => { + const app = createApp() + const token = await createUserToken(app) + fetchMock.mockResolvedValue(new Response('', { status: 404 })) + + const missing = await app.inject({ + method: 'GET', + url: `/trees/tree-1/immich/thumbnail/${immichPersonId}`, + headers: { authorization: `Bearer ${token}` }, + }) + expect(missing.statusCode).toBe(404) + expect(missing.json()).toEqual({ error: 'immich_person_not_found' }) + + const invalid = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/thumbnail/not-a-uuid', + headers: { authorization: `Bearer ${token}` }, + }) + expect(invalid.statusCode).toBe(400) + await app.close() + }) +}) + +describe('Immich integration: assign', () => { + it('downloads the thumbnail, replaces the avatar and audits the change', async () => { + const app = createApp() + const token = await createUserToken(app) + + // Portrait manuel en place : l'administrateur a confirmé son remplacement, il doit + // être supprimé une fois la base à jour. + const oldAvatarRelative = 'tree-1/person-1/avatar-old.jpg' + await mkdir(path.dirname(await absStoragePath(oldAvatarRelative)), { recursive: true }) + await writeFile(await absStoragePath(oldAvatarRelative), 'old avatar') + + prismaMock.person.findFirst.mockResolvedValue({ id: 'person-1', avatarPath: oldAvatarRelative }) + mockImmichPerson() + + const response = await app.inject({ + method: 'POST', + url: '/trees/tree-1/immich/assign', + headers: { authorization: `Bearer ${token}` }, + payload: { personId: 'person-1', immichPersonId, replaceAvatar: true }, + }) + + expect(response.statusCode).toBe(200) + expect(response.json()).toEqual({ ok: true, avatarUpdated: true, immichPersonId }) + + const updateData = prismaMock.person.update.mock.calls[0][0].data + expect(updateData.immichPersonId).toBe(immichPersonId) + expect(updateData.avatarMimeType).toBe('image/jpeg') + expect(typeof updateData.avatarPath).toBe('string') + + // Le nouveau portrait existe sur le disque, l'ancien a été retiré. + const newAvatar = await absStoragePath(updateData.avatarPath) + await expect(fsExists(newAvatar)).resolves.toBe(true) + await expect(fsExists(await absStoragePath(oldAvatarRelative))).resolves.toBe(false) + + expect(prismaMock.auditLog.create).toHaveBeenCalledWith({ + data: { + treeId: 'tree-1', + actorType: 'user', + actorId: 'user-1', + action: 'immich_assign', + entityType: 'person', + entityId: 'person-1', + payloadJson: { immichPersonId, avatarUpdated: true, avatarPath: updateData.avatarPath }, + }, + }) + await app.close() + }) + + it('asks before replacing an existing portrait, whatever its origin', async () => { + const app = createApp() + const token = await createUserToken(app) + mockImmichPerson() + + // Portrait manuel en place : l'association ne le remplace pas sans accord explicite. + const manualAvatarRelative = 'tree-1/person-confirm/avatar-manuel.jpg' + await mkdir(path.dirname(await absStoragePath(manualAvatarRelative)), { recursive: true }) + await writeFile(await absStoragePath(manualAvatarRelative), 'portrait manuel') + + prismaMock.person.findFirst.mockResolvedValue({ id: 'person-confirm', avatarPath: manualAvatarRelative }) + + const manual = await app.inject({ + method: 'POST', + url: '/trees/tree-1/immich/assign', + headers: { authorization: `Bearer ${token}` }, + payload: { personId: 'person-confirm', immichPersonId }, + }) + + expect(manual.statusCode).toBe(409) + expect(manual.json()).toEqual({ error: 'avatar_exists' }) + + // Même garde pour un portrait venu d'une association Immich précédente. + prismaMock.person.findFirst.mockResolvedValue({ + id: 'person-confirm', + avatarPath: `tree-1/person-confirm/immich-${randomUUID()}.jpg`, + immichPersonId: otherImmichId, + }) + + const fromImmich = await app.inject({ + method: 'POST', + url: '/trees/tree-1/immich/assign', + headers: { authorization: `Bearer ${token}` }, + payload: { personId: 'person-confirm', immichPersonId }, + }) + + expect(fromImmich.statusCode).toBe(409) + expect(fromImmich.json()).toEqual({ error: 'avatar_exists' }) + + // Base, journal d'audit et fichiers : rien n'a bougé. + expect(prismaMock.person.update).not.toHaveBeenCalled() + expect(prismaMock.auditLog.create).not.toHaveBeenCalled() + expect(prismaMock.$transaction).not.toHaveBeenCalled() + await expect(fsExists(await absStoragePath(manualAvatarRelative))).resolves.toBe(true) + + const files = await fsListDir(path.join(storageRoot, 'tree-1', 'person-confirm')) + expect(files.filter((name) => name.startsWith('immich-'))).toEqual([]) + await app.close() + }) + + it('assigns without touching the avatar when Immich has no thumbnail', async () => { + const app = createApp() + const token = await createUserToken(app) + + // Portrait manuel conservé : sans vignette Immich, l'association ne le remplace pas, + // aucune confirmation n'est donc nécessaire. + prismaMock.person.findFirst.mockResolvedValue({ id: 'person-1', avatarPath: 'tree-1/person-1/avatar-keep.jpg' }) + mockImmichPerson({ thumbnailPath: '' }) + + const response = await app.inject({ + method: 'POST', + url: '/trees/tree-1/immich/assign', + headers: { authorization: `Bearer ${token}` }, + payload: { personId: 'person-1', immichPersonId }, + }) + + expect(response.statusCode).toBe(200) + expect(response.json()).toEqual({ ok: true, avatarUpdated: false, immichPersonId }) + + // Sans vignette annoncée, l'appel de vignette n'a même pas lieu. + expect(fetchMock).toHaveBeenCalledTimes(1) + + const updateData = prismaMock.person.update.mock.calls[0][0].data + expect(updateData.immichPersonId).toBe(immichPersonId) + expect(updateData).not.toHaveProperty('avatarPath') + expect(updateData).not.toHaveProperty('avatarMimeType') + await app.close() + }) + + it('still assigns without the avatar when the thumbnail vanishes after the person was found', async () => { + const app = createApp() + const token = await createUserToken(app) + + // Immich annonce une vignette qui répond pourtant 404 : la personne existe, + // l'association se fait sans portrait. + prismaMock.person.findFirst.mockResolvedValue({ id: 'person-1', avatarPath: null }) + mockImmichPerson({ thumbnailStatus: 404 }) + + const response = await app.inject({ + method: 'POST', + url: '/trees/tree-1/immich/assign', + headers: { authorization: `Bearer ${token}` }, + payload: { personId: 'person-1', immichPersonId }, + }) + + expect(response.statusCode).toBe(200) + expect(response.json()).toEqual({ ok: true, avatarUpdated: false, immichPersonId }) + + const updateData = prismaMock.person.update.mock.calls[0][0].data + expect(updateData.immichPersonId).toBe(immichPersonId) + expect(updateData).not.toHaveProperty('avatarPath') + expect(updateData).not.toHaveProperty('avatarMimeType') + await app.close() + }) + + it('refuses the assignment when the Immich person does not exist', async () => { + const app = createApp() + const token = await createUserToken(app) + + // Portrait en place : un refus ne doit rien changer. + // Dossier dédié : les autres tests laissent leurs portraits dans tree-1/person-1. + const avatarRelative = 'tree-1/person-missing/avatar-keep.jpg' + await mkdir(path.dirname(await absStoragePath(avatarRelative)), { recursive: true }) + await writeFile(await absStoragePath(avatarRelative), 'existing avatar') + + prismaMock.person.findFirst.mockResolvedValue({ id: 'person-missing', avatarPath: avatarRelative }) + // GET /api/people/{id} : la personne n'existe pas. Un 404 sur la vignette ne suffirait + // pas à le distinguer d'une simple vignette manquante. + fetchMock.mockResolvedValue(new Response('', { status: 404 })) + + const response = await app.inject({ + method: 'POST', + url: '/trees/tree-1/immich/assign', + headers: { authorization: `Bearer ${token}` }, + payload: { personId: 'person-missing', immichPersonId }, + }) + + expect(response.statusCode).toBe(404) + expect(response.json()).toEqual({ error: 'immich_person_not_found' }) + + // Base, journal d'audit et fichiers : rien n'a bougé. + expect(prismaMock.person.update).not.toHaveBeenCalled() + expect(prismaMock.auditLog.create).not.toHaveBeenCalled() + expect(prismaMock.$transaction).not.toHaveBeenCalled() + await expect(fsExists(await absStoragePath(avatarRelative))).resolves.toBe(true) + + const files = await fsListDir(path.join(storageRoot, 'tree-1', 'person-missing')) + expect(files.filter((name) => name.startsWith('immich-'))).toEqual([]) + await app.close() + }) + + it('maps an Immich auth failure during assignment to 502 without touching the database', async () => { + const app = createApp() + const token = await createUserToken(app) + + prismaMock.person.findFirst.mockResolvedValue({ id: 'person-1', avatarPath: null }) + fetchMock.mockResolvedValue(new Response(JSON.stringify({ message: 'Invalid API key' }), { status: 401 })) + + const response = await app.inject({ + method: 'POST', + url: '/trees/tree-1/immich/assign', + headers: { authorization: `Bearer ${token}` }, + payload: { personId: 'person-1', immichPersonId }, + }) + + // Un refus d'authentification n'est jamais pris pour une personne manquante. + expect(response.statusCode).toBe(502) + expect(response.json()).toEqual({ error: 'immich_auth_failed' }) + expect(prismaMock.person.update).not.toHaveBeenCalled() + expect(prismaMock.auditLog.create).not.toHaveBeenCalled() + await app.close() + }) + + it('rejects invalid identifiers, unauthenticated, non-admin and unknown person', async () => { + const app = createApp() + const token = await createUserToken(app) + + const invalidId = await app.inject({ + method: 'POST', + url: '/trees/tree-1/immich/assign', + headers: { authorization: `Bearer ${token}` }, + payload: { personId: 'person-1', immichPersonId: '../etc/passwd' }, + }) + expect(invalidId.statusCode).toBe(400) + expect(invalidId.json()).toEqual({ error: 'invalid_immich_person_id' }) + + const anonymous = await app.inject({ + method: 'POST', + url: '/trees/tree-1/immich/assign', + payload: { personId: 'person-1', immichPersonId }, + }) + expect(anonymous.statusCode).toBe(401) + + prismaMock.treeMembership.findUnique.mockResolvedValue({ + treeId: 'tree-1', + userId: 'user-1', + role: 'member', + tree: { deletedAt: null }, + }) + const member = await app.inject({ + method: 'POST', + url: '/trees/tree-1/immich/assign', + headers: { authorization: `Bearer ${token}` }, + payload: { personId: 'person-1', immichPersonId }, + }) + expect(member.statusCode).toBe(403) + + prismaMock.treeMembership.findUnique.mockResolvedValue({ + treeId: 'tree-1', + userId: 'user-1', + role: 'owner', + tree: { deletedAt: null }, + }) + prismaMock.person.findFirst.mockResolvedValue(null) + const unknown = await app.inject({ + method: 'POST', + url: '/trees/tree-1/immich/assign', + headers: { authorization: `Bearer ${token}` }, + payload: { personId: 'person-x', immichPersonId }, + }) + expect(unknown.statusCode).toBe(404) + expect(unknown.json()).toEqual({ error: 'person_not_found' }) + await app.close() + }) + + it('refuses the assignment when the tree quota is exceeded', async () => { + const app = createApp() + const token = await createUserToken(app) + + // L'arbre est déjà plein : 1 Mo sur le disque, un quota de 1 Mo. + await mkdir(path.join(storageRoot, 'tree-quota'), { recursive: true }) + await writeFile(path.join(storageRoot, 'tree-quota', 'big.bin'), Buffer.alloc(1024 * 1024)) + + prismaMock.person.findFirst.mockResolvedValue({ id: 'person-quota', avatarPath: null }) + mockImmichPerson() + + const response = await app.inject({ + method: 'POST', + url: '/trees/tree-quota/immich/assign', + headers: { authorization: `Bearer ${token}` }, + payload: { personId: 'person-quota', immichPersonId }, + }) + + expect(response.statusCode).toBe(413) + expect(response.json()).toEqual({ error: 'storage_quota_exceeded' }) + await app.close() + }) + + it('removes the new file and keeps the old avatar when the database update fails', async () => { + const app = createApp() + const token = await createUserToken(app) + + const oldAvatarRelative = 'tree-1/person-tx/avatar-kept.jpg' + await mkdir(path.dirname(await absStoragePath(oldAvatarRelative)), { recursive: true }) + await writeFile(await absStoragePath(oldAvatarRelative), 'old avatar') + + prismaMock.person.findFirst.mockResolvedValue({ id: 'person-tx', avatarPath: oldAvatarRelative }) + mockImmichPerson() + prismaMock.$transaction.mockRejectedValue(new Error('db down')) + + const response = await app.inject({ + method: 'POST', + url: '/trees/tree-1/immich/assign', + headers: { authorization: `Bearer ${token}` }, + payload: { personId: 'person-tx', immichPersonId, replaceAvatar: true }, + }) + + expect(response.statusCode).toBe(500) + + // La base n'a pas changé : l'ancien portrait est là, le nouveau a été nettoyé. + await expect(fsExists(await absStoragePath(oldAvatarRelative))).resolves.toBe(true) + + const writtenFiles = await fsListDir(path.join(storageRoot, 'tree-1', 'person-tx')) + expect(writtenFiles.filter((name) => name.startsWith('immich-'))).toEqual([]) + await app.close() + }) +}) + +describe('Immich integration: unassign', () => { + it('clears an Immich avatar after the database update', async () => { + const app = createApp() + const token = await createUserToken(app) + + const immichAvatarRelative = `tree-1/person-1/immich-${randomUUID()}.jpg` + await mkdir(path.dirname(await absStoragePath(immichAvatarRelative)), { recursive: true }) + await writeFile(await absStoragePath(immichAvatarRelative), 'immich avatar') + + prismaMock.person.findFirst.mockResolvedValue({ id: 'person-1', avatarPath: immichAvatarRelative, immichPersonId }) + + const response = await app.inject({ + method: 'POST', + url: '/trees/tree-1/immich/unassign', + headers: { authorization: `Bearer ${token}` }, + payload: { personId: 'person-1' }, + }) + + expect(response.statusCode).toBe(200) + expect(response.json()).toEqual({ ok: true, avatarRemoved: true }) + + const updateData = prismaMock.person.update.mock.calls[0][0].data + expect(updateData).toMatchObject({ immichPersonId: null, avatarPath: null, avatarMimeType: null }) + + expect(prismaMock.auditLog.create).toHaveBeenCalledWith({ + data: { + treeId: 'tree-1', + actorType: 'user', + actorId: 'user-1', + action: 'immich_unassign', + entityType: 'person', + entityId: 'person-1', + payloadJson: { previousImmichPersonId: immichPersonId, avatarRemoved: true }, + }, + }) + + await expect(fsExists(await absStoragePath(immichAvatarRelative))).resolves.toBe(false) + await app.close() + }) + + it('preserves a manually uploaded avatar when unassigning', async () => { + const app = createApp() + const token = await createUserToken(app) + + const manualAvatarRelative = `tree-1/person-1/avatar-${randomUUID()}.jpg` + await mkdir(path.dirname(await absStoragePath(manualAvatarRelative)), { recursive: true }) + await writeFile(await absStoragePath(manualAvatarRelative), 'manual avatar') + + prismaMock.person.findFirst.mockResolvedValue({ id: 'person-1', avatarPath: manualAvatarRelative, immichPersonId }) + + const response = await app.inject({ + method: 'POST', + url: '/trees/tree-1/immich/unassign', + headers: { authorization: `Bearer ${token}` }, + payload: { personId: 'person-1' }, + }) + + expect(response.statusCode).toBe(200) + expect(response.json()).toEqual({ ok: true, avatarRemoved: false }) + + const updateData = prismaMock.person.update.mock.calls[0][0].data + expect(updateData.immichPersonId).toBeNull() + expect(updateData).not.toHaveProperty('avatarPath') + expect(updateData).not.toHaveProperty('avatarMimeType') + + await expect(fsExists(await absStoragePath(manualAvatarRelative))).resolves.toBe(true) + await app.close() + }) + + it('does nothing when no association is in place', async () => { + const app = createApp() + const token = await createUserToken(app) + + prismaMock.person.findFirst.mockResolvedValue({ id: 'person-1', avatarPath: null, immichPersonId: null }) + + const response = await app.inject({ + method: 'POST', + url: '/trees/tree-1/immich/unassign', + headers: { authorization: `Bearer ${token}` }, + payload: { personId: 'person-1' }, + }) + + expect(response.statusCode).toBe(200) + expect(response.json()).toEqual({ ok: true, avatarRemoved: false }) + expect(prismaMock.person.update).not.toHaveBeenCalled() + expect(prismaMock.auditLog.create).not.toHaveBeenCalled() + await app.close() + }) + + it('rejects unknown persons and non-admin members', async () => { + const app = createApp() + const token = await createUserToken(app) + + prismaMock.person.findFirst.mockResolvedValue(null) + const unknown = await app.inject({ + method: 'POST', + url: '/trees/tree-1/immich/unassign', + headers: { authorization: `Bearer ${token}` }, + payload: { personId: 'person-x' }, + }) + expect(unknown.statusCode).toBe(404) + + prismaMock.treeMembership.findUnique.mockResolvedValue({ + treeId: 'tree-1', + userId: 'user-1', + role: 'member', + tree: { deletedAt: null }, + }) + prismaMock.person.findFirst.mockResolvedValue({ id: 'person-1', avatarPath: null, immichPersonId }) + const member = await app.inject({ + method: 'POST', + url: '/trees/tree-1/immich/unassign', + headers: { authorization: `Bearer ${token}` }, + payload: { personId: 'person-1' }, + }) + expect(member.statusCode).toBe(403) + await app.close() + }) +}) + +describe('Immich integration: manual avatar replacing an Immich portrait', () => { + it('clears the association when a manual file overwrites the Immich portrait', async () => { + const app = createApp() + const token = await createUserToken(app) + + const oldAvatarRelative = `tree-1/person-1/immich-${randomUUID()}.jpg` + await writeFile(await absStoragePath(oldAvatarRelative), jpegBytes) + prismaMock.person.findFirst.mockResolvedValue({ id: 'person-1', avatarPath: oldAvatarRelative, immichPersonId }) + + const response = await app.inject({ + method: 'POST', + url: '/trees/tree-1/persons/person-1/avatar', + headers: { authorization: `Bearer ${token}` }, + payload: { + fileName: 'portrait.jpg', + mimeType: 'image/jpeg', + sizeBytes: jpegBytes.length, + dataBase64: jpegBytes.toString('base64'), + }, + }) + + expect(response.statusCode).toBe(201) + expect(response.json()).toEqual({ ok: true }) + + // Le portrait manuel remplace le fichier Immich et son association : sinon l'association + // survivrait invisible en base, sans qu'aucune interface ne puisse la retirer. + const updateData = prismaMock.person.updateMany.mock.calls[0][0].data + expect(updateData.immichPersonId).toBe(null) + expect(updateData.avatarPath).toEqual(expect.any(String)) + expect(updateData.avatarPath).not.toContain('immich-') + + // Le retrait du lien apparaît dans le journal d'audit de l'envoi. + const auditData = prismaMock.auditLog.create.mock.calls[0][0].data + expect(auditData.action).toBe('person_avatar_updated') + expect(auditData.payloadJson).toEqual({ immichLinkRemoved: true }) + await app.close() + }) + + it('does not touch the association field when there is none', async () => { + const app = createApp() + const token = await createUserToken(app) + + prismaMock.person.findFirst.mockResolvedValue({ id: 'person-1', avatarPath: null, immichPersonId: null }) + + const response = await app.inject({ + method: 'POST', + url: '/trees/tree-1/persons/person-1/avatar', + headers: { authorization: `Bearer ${token}` }, + payload: { + fileName: 'portrait.jpg', + mimeType: 'image/jpeg', + sizeBytes: jpegBytes.length, + dataBase64: jpegBytes.toString('base64'), + }, + }) + + expect(response.statusCode).toBe(201) + const updateData = prismaMock.person.updateMany.mock.calls[0][0].data + expect(updateData).not.toHaveProperty('immichPersonId') + await app.close() + }) +}) + +describe('Immich integration: redirections', () => { + it('never follows a redirect and never sends the API key to another host', async () => { + const app = createApp() + const token = await createUserToken(app) + fetchMock.mockImplementation(async (input: RequestInfo | URL) => { + const url = String(input) + if (url.includes('/api/people')) { + return new Response(null, { status: 302, headers: { location: 'http://evil.test/collect' } }) + } + return jsonResponse({ res: 'pong' }) + }) + + const response = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/people', + headers: { authorization: `Bearer ${token}` }, + }) + + expect(response.statusCode).toBe(503) + expect(response.json()).toEqual({ error: 'immich_unreachable' }) + // Chaque appel part en mode « erreur » sur redirection, et aucun n'atteint l'hôte de la redirection. + expect(fetchMock.mock.calls.length).toBeGreaterThan(0) + for (const [input, init] of fetchMock.mock.calls) { + expect(init?.redirect).toBe('error') + expect(String(input)).not.toContain('evil.test') + } + await app.close() + }) +}) + +describe('Immich integration: adresse de l’instance', () => { + it('keeps the sub-path of the instance in front of the API paths', async () => { + const app = createApp() + const token = await createUserToken(app) + prismaMock.treeImmichConfig.findUnique.mockResolvedValueOnce({ apiUrl: 'http://immich.test/immich', apiKeyEnc: treeApiKeyEnc }) + fetchMock.mockResolvedValue(await jsonResponse({ people: [], total: 0, hasNextPage: false, hidden: 0 })) + + const response = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/people', + headers: { authorization: `Bearer ${token}` }, + }) + + expect(response.statusCode).toBe(200) + expect(String(fetchMock.mock.calls[0][0])).toMatch(/^http:\/\/immich\.test\/immich\/api\/people\?/) + await app.close() + }) + + it('compares origin and path, never a prefix of the host or user information', async () => { + const { isImmichApiUrlAllowed, normalizeImmichApiUrl } = await import('../src/lib/immich.js') + + expect(isImmichApiUrlAllowed('http://immich.test/')).toBe(true) + expect(isImmichApiUrlAllowed('http://immich.test/immich')).toBe(true) + // Domaine préfixe : le nom listé est le début d'un autre hôte. + expect(isImmichApiUrlAllowed('http://immich.test.evil.com')).toBe(false) + // Chemin différent sur le même hôte. + expect(isImmichApiUrlAllowed('http://immich.test/autre')).toBe(false) + // Informations d'utilisateur : l'hôte réel est evil.com. + expect(isImmichApiUrlAllowed('http://immich.test@evil.com')).toBe(false) + expect(isImmichApiUrlAllowed('http://immich.test:x@immich.test')).toBe(false) + // Requête et fragment ne sont pas une adresse d'instance. + expect(isImmichApiUrlAllowed('http://immich.test/?x=1')).toBe(false) + expect(normalizeImmichApiUrl('ftp://immich.test')).toBeNull() + }) +}) + +describe('Immich integration: durcissement des vignettes et des réponses', () => { + it('serves only images, with nosniff, and refuses bytes that are not an image', async () => { + const app = createApp() + const token = await createUserToken(app) + + fetchMock.mockResolvedValueOnce(new Response(new Uint8Array(jpegBytes), { status: 200 })) + const image = await app.inject({ + method: 'GET', + url: `/trees/tree-1/immich/thumbnail/${immichPersonId}`, + headers: { authorization: `Bearer ${token}` }, + }) + expect(image.statusCode).toBe(200) + expect(image.headers['content-type']).toBe('image/jpeg') + expect(image.headers['x-content-type-options']).toBe('nosniff') + + // Un corps HTML déclaré image n'est jamais servi comme tel. + fetchMock.mockResolvedValueOnce(new Response('', { status: 200, headers: { 'content-type': 'image/png' } })) + const notImage = await app.inject({ + method: 'GET', + url: `/trees/tree-1/immich/thumbnail/${immichPersonId}`, + headers: { authorization: `Bearer ${token}` }, + }) + expect(notImage.statusCode).toBe(404) + expect(notImage.json()).toEqual({ error: 'thumbnail_not_found' }) + await app.close() + }) + + it('stops reading a thumbnail above 5 MB without loading the rest of it', async () => { + const app = createApp() + const token = await createUserToken(app) + // Un flux sans taille annoncée, plus grand que la limite : la lecture doit s'arrêter en route. + const big = new Uint8Array(5 * 1024 * 1024 + 1024) + big.set(jpegBytes.subarray(0, Math.min(jpegBytes.length, big.length))) + fetchMock.mockResolvedValueOnce(new Response(big, { status: 200 })) + + const response = await app.inject({ + method: 'GET', + url: `/trees/tree-1/immich/thumbnail/${immichPersonId}`, + headers: { authorization: `Bearer ${token}` }, + }) + + expect(response.statusCode).toBe(404) + expect(response.json()).toEqual({ error: 'thumbnail_not_found' }) + await app.close() + }) + + it('answers 503 when an Immich response body cannot be read as JSON', async () => { + const app = createApp() + const token = await createUserToken(app) + fetchMock.mockResolvedValue(new Response('passerelle en panne', { status: 200 })) + + const response = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/people', + headers: { authorization: `Bearer ${token}` }, + }) + + expect(response.statusCode).toBe(503) + expect(response.json()).toEqual({ error: 'immich_unreachable' }) + await app.close() + }) + + it('clears the Immich link when the portrait is deleted by hand', async () => { + const app = createApp() + const token = await createUserToken(app) + prismaMock.person.findFirst.mockResolvedValue({ id: 'person-1', avatarPath: 'tree-1/person-1/avatar-a.jpg', immichPersonId }) + + const response = await app.inject({ + method: 'DELETE', + url: '/trees/tree-1/persons/person-1/avatar', + headers: { authorization: `Bearer ${token}` }, + }) + + expect(response.statusCode).toBe(200) + expect(prismaMock.person.updateMany.mock.calls[0][0].data).toMatchObject({ avatarPath: null, immichPersonId: null }) + await app.close() + }) +}) + +describe('Immich integration: lien d’une fiche', () => { + it('tells an administrator which Immich person a file is linked to, and refuses others', async () => { + const app = createApp() + const token = await createUserToken(app) + prismaMock.person.findFirst.mockResolvedValue({ immichPersonId }) + + const linked = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/links/person-1', + headers: { authorization: `Bearer ${token}` }, + }) + expect(linked.statusCode).toBe(200) + expect(linked.json()).toEqual({ immichPersonId }) + + const memberToken = await createUserToken(app, 'user-member') + prismaMock.treeMembership.findUnique.mockResolvedValueOnce({ treeId: 'tree-1', userId: 'user-member', role: 'member', tree: { deletedAt: null } }) + const member = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/links/person-1', + headers: { authorization: `Bearer ${memberToken}` }, + }) + expect(member.statusCode).toBe(403) + + prismaMock.person.findFirst.mockResolvedValue(null) + const missing = await app.inject({ + method: 'GET', + url: '/trees/tree-1/immich/links/person-unknown', + headers: { authorization: `Bearer ${token}` }, + }) + expect(missing.statusCode).toBe(404) + await app.close() + }) +}) + +describe('Immich integration: suppression logique d’une personne', () => { + it('clears the Immich link together with the portrait', async () => { + const { softDeletePersonCascade } = await import('../src/lib/entity-deletion.js') + const calls: Array<{ model: string; method: string; args: unknown }> = [] + const model = (name: string) => ({ + findFirst: async (args: unknown) => { + calls.push({ model: name, method: 'findFirst', args }) + return { avatarPath: 'tree-1/person-1/immich-a.jpg' } + }, + findMany: async () => [], + updateMany: async (args: unknown) => { + calls.push({ model: name, method: 'updateMany', args }) + return { count: 0 } + }, + }) + const db = new Proxy({} as Record, { + get: (_target, name: string) => model(name), + }) as never + + await softDeletePersonCascade(db, 'tree-1', 'person-1', 'user-1', new Date('2026-10-16T00:00:00Z')) + + const personUpdate = calls.find((call) => call.model === 'person' && call.method === 'updateMany') + expect(personUpdate?.args).toMatchObject({ + data: { deletedAt: new Date('2026-10-16T00:00:00Z'), avatarPath: null, immichPersonId: null }, + }) + }) +}) diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 57b551c..b2649a7 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -45,6 +45,7 @@ import { updatePerson, uploadAnnotationPhoto, } from './api/treeApi' +import { getImmichErrorMessage, unassignImmichPerson } from './api/immichApi.js' import { useAuth } from './hooks/useAuth' import { useTreeAccess, getTreeTokenStorageKey, getSlugFromPathname, readTreeAccessRole, TREE_ID_FROM_ENV } from './hooks/useTreeAccess' import { useMediaManager } from './hooks/useMediaManager' @@ -1535,18 +1536,33 @@ function App() { } }, [auth.userAuth.token, tree.treeContext.accessToken, tree.treeContext.treeId, refreshTreeAndKeepSelection]) - const handlePersonAvatarDelete = useCallback(async (personId) => { + // Visage venu d'Immich : recharger l'arbre pour montrer le nouveau portrait (ou le portrait restant) + const handleImmichChange = useCallback(async (personId) => { + await refreshTreeAndKeepSelection(personId, { relayout: false, avatarCacheBust: Date.now() }) + }, [refreshTreeAndKeepSelection]) + + const handlePersonAvatarDelete = useCallback(async (personId, avatarFromImmich = false) => { const accessToken = tree.treeContext.accessToken || auth.userAuth.token if (!accessToken || !tree.treeContext.treeId) return setAvatarActionState({ loading: true, error: '' }) try { - await deletePersonAvatar(tree.treeContext.treeId, personId, accessToken) - await refreshTreeAndKeepSelection(personId, { relayout: true }) + // Portrait venu d'Immich : le désassignement retire le portrait et l'association d'un + // coup ; la suppression seule laisserait une association pendante en base. + if (avatarFromImmich) { + await unassignImmichPerson(tree.treeContext.treeId, personId, accessToken) + await refreshTreeAndKeepSelection(personId, { relayout: false, avatarCacheBust: Date.now() }) + } else { + await deletePersonAvatar(tree.treeContext.treeId, personId, accessToken) + await refreshTreeAndKeepSelection(personId, { relayout: true }) + } setAvatarActionState({ loading: false, error: '' }) } catch (error) { - setAvatarActionState({ loading: false, error: getAccountErrorMessage(error) }) + setAvatarActionState({ + loading: false, + error: avatarFromImmich ? getImmichErrorMessage(error, t) : getAccountErrorMessage(error), + }) } }, [auth.userAuth.token, tree.treeContext.accessToken, tree.treeContext.treeId, refreshTreeAndKeepSelection]) @@ -2847,6 +2863,9 @@ function App() { onManageMedia={media.handleOpenMediaManager} onAvatarUpload={tree.canEditCurrentTree ? handlePersonAvatarUpload : undefined} onAvatarDelete={tree.canEditCurrentTree ? handlePersonAvatarDelete : undefined} + treeId={tree.treeContext.treeId || null} + immichToken={tree.treeContext.accessToken || auth.userAuth.token} + onImmichChange={tree.canEditCurrentTree ? handleImmichChange : undefined} avatarActionLoading={avatarActionState.loading} avatarActionError={avatarActionState.error} isAdmin={userRole.isAdmin} @@ -2913,6 +2932,7 @@ function App() { visible={adminPanelVisible} treeId={tree.treeContext.treeId} authToken={tree.treeContext.accessToken} + isAdmin={userRole.isAdmin} onTreeDeleted={handleTreeDeleted} onGedcomImported={handleGedcomImported} onOpenPhotoStart={() => { setAdminPanelVisible(false); openPhotoStart() }} diff --git a/frontend/src/api/immichApi.js b/frontend/src/api/immichApi.js new file mode 100644 index 0000000..9f8a9a2 --- /dev/null +++ b/frontend/src/api/immichApi.js @@ -0,0 +1,93 @@ +import { API_BASE_URL, apiRequest } from './client.js' + +// Reconnaissance des visages : la connexion Immich est propre à chaque arbre, configurée par +// ses administrateurs. L'adresse est choisie parmi celles autorisées par l'opérateur du +// serveur ; la clé d'API ne quitte jamais le backend. Les erreurs distinguent non configuré / +// injoignable / clé refusée. + +function withAuth(options = {}, token) { + if (!token) return options + return { ...options, headers: { ...(options.headers || {}), Authorization: `Bearer ${token}` } } +} + +export function getImmichErrorMessage(error, t) { + const code = error?.payload?.error || '' + if (code === 'immich_not_configured') return t('Immich n’est pas configuré pour cet arbre.') + if (code === 'immich_unreachable') return t('Immich est injoignable.') + if (code === 'immich_auth_failed') return t('La clé d’accès à Immich a été refusée.') + if (code === 'immich_person_not_found') return t('Personne introuvable dans Immich.') + if (code === 'invalid_immich_person_id') return t('Identifiant Immich invalide.') + if (code === 'invalid_avatar_image') return t('La vignette Immich n’est pas une image valide.') + if (code === 'storage_quota_exceeded') return t('Espace disque de l’arbre dépassé.') + if (code === 'api_key_required') return t('Indiquez la clé d’accès à Immich pour la première configuration.') + if (code === 'instance_not_allowed') return t('Cette instance Immich n’est pas autorisée par l’opérateur du serveur.') + if (code === 'forbidden') return t('Seuls les administrateurs de l’arbre peuvent associer un visage Immich.') + if (error?.status === 0 || error?.message === 'Failed to fetch') return t('Immich est injoignable.') + return error?.message || t('Erreur inattendue.') +} + +// Connexion Immich de l'arbre : métadonnées sûres (jamais la clé, jamais l'adresse) et instances +// autorisées par l'opérateur, nommées par leur libellé, dont le panneau d'administration fait un menu. +export async function fetchImmichConfig(treeId, token) { + const data = await apiRequest(`/trees/${encodeURIComponent(treeId)}/immich/config`, withAuth({}, token)) + return { + config: data?.config || { configured: false, instanceId: null, label: null, updatedAt: null }, + instances: Array.isArray(data?.instances) ? data.instances : [], + } +} + +export async function saveImmichConfig(treeId, { instanceId, apiKey }, token) { + const data = await apiRequest(`/trees/${encodeURIComponent(treeId)}/immich/config`, withAuth({ + method: 'PUT', + body: JSON.stringify({ instanceId, ...(apiKey ? { apiKey } : {}) }), + }, token)) + return data?.config || null +} + +export async function removeImmichConfig(treeId, token) { + return apiRequest(`/trees/${encodeURIComponent(treeId)}/immich/config`, withAuth({ + method: 'DELETE', + }, token)) +} + +export async function checkImmichStatus(treeId, token) { + return apiRequest(`/trees/${encodeURIComponent(treeId)}/immich/status`, withAuth({}, token)) +} + +export async function listImmichPeople(treeId, token) { + const data = await apiRequest(`/trees/${encodeURIComponent(treeId)}/immich/people`, withAuth({}, token)) + return Array.isArray(data?.people) ? data.people : [] +} + +// Personne Immich déjà associée à cette fiche (administrateurs seulement), ou null. +export async function fetchImmichLink(treeId, personId, token) { + const data = await apiRequest(`/trees/${encodeURIComponent(treeId)}/immich/links/${encodeURIComponent(personId)}`, withAuth({}, token)) + return data?.immichPersonId || null +} + +export async function fetchImmichThumbnail(treeId, immichPersonId, token) { + const path = `/trees/${encodeURIComponent(treeId)}/immich/thumbnail/${encodeURIComponent(immichPersonId)}` + const response = await fetch(`${API_BASE_URL}${path}`, { + headers: token ? { Authorization: `Bearer ${token}` } : {}, + }) + if (!response.ok) { + throw new Error(`immich_thumbnail_failed_${response.status}`) + } + return URL.createObjectURL(await response.blob()) +} + +export async function assignImmichPerson(treeId, personId, immichPersonId, token, { replaceAvatar = false } = {}) { + return apiRequest(`/trees/${encodeURIComponent(treeId)}/immich/assign`, withAuth({ + method: 'POST', + // replaceAvatar : accord explicite pour remplacer un portrait déjà en place — le serveur + // refuse sinon (409 avatar_exists), quelle que soit l'origine du portrait actuel. + body: JSON.stringify({ personId, immichPersonId, ...(replaceAvatar ? { replaceAvatar: true } : {}) }), + }, token)) +} + +export async function unassignImmichPerson(treeId, personId, token) { + return apiRequest(`/trees/${encodeURIComponent(treeId)}/immich/unassign`, withAuth({ + method: 'POST', + body: JSON.stringify({ personId }), + }, token)) +} diff --git a/frontend/src/components/AdminPanel.jsx b/frontend/src/components/AdminPanel.jsx index d4cab54..42d4158 100644 --- a/frontend/src/components/AdminPanel.jsx +++ b/frontend/src/components/AdminPanel.jsx @@ -1,5 +1,5 @@ import { useEffect, useRef, useState } from 'react' -import { Download, ImagePlus, Trash2, X } from 'lucide-react' +import { Download, ImagePlus, Trash2, Unplug, X } from 'lucide-react' import './SettingsPanels.css' import { deleteTree, @@ -10,6 +10,13 @@ import { updateTree, updateTreeSettings, } from '../api/treeApi' +import { + checkImmichStatus, + fetchImmichConfig, + getImmichErrorMessage, + removeImmichConfig, + saveImmichConfig, +} from '../api/immichApi.js' import PzBusy from './PzBusy.jsx' import TreeVisitsSection from './TreeVisitsSection.jsx' import { t } from '../i18n/index.js' @@ -27,6 +34,7 @@ const AdminPanel = ({ visible, treeId, authToken, + isAdmin = false, onClose, onTreeDeleted, onGedcomImported, @@ -51,6 +59,15 @@ const AdminPanel = ({ const [importingGedcom, setImportingGedcom] = useState(false) const gedcomInputRef = useRef(null) + // Connexion Immich propre à cet arbre : l'adresse se choisit parmi celles autorisées par + // l'opérateur du serveur, la clé n'est jamais relue et le champ vide la conserve. + const [immichConfig, setImmichConfig] = useState(null) + const [immichInstances, setImmichInstances] = useState([]) + const [immichInstanceId, setImmichInstanceId] = useState('') + const [immichApiKey, setImmichApiKey] = useState('') + const [immichStatus, setImmichStatus] = useState(null) // null : inconnu, 'ok', sinon le motif + const [immichBusy, setImmichBusy] = useState(false) + useEffect(() => { if (!visible || !treeId || !authToken) { return @@ -66,6 +83,26 @@ const AdminPanel = ({ setGedcomFile(null) setImportingGedcom(false) + setImmichConfig(null) + setImmichInstances([]) + setImmichInstanceId('') + setImmichApiKey('') + setImmichStatus(null) + // Réservé aux administrateurs de l'arbre. Le panneau attend cette réponse avant de s'afficher : + // la section Immich n'apparaît pas après coup et la zone de suppression ne bouge pas. + const immichLoad = isAdmin + ? fetchImmichConfig(treeId, authToken) + .then(({ config, instances }) => { + if (!active) return + setImmichConfig(config) + setImmichInstances(instances) + setImmichInstanceId(instances.some((instance) => instance.id === config?.instanceId) ? config.instanceId : '') + }) + .catch(() => { + // Configuration non chargée : la section Immich reste masquée + }) + : Promise.resolve() + fetchTreeSettings(treeId, authToken) .then((settings) => { if (!active || !settings) return @@ -75,7 +112,7 @@ const AdminPanel = ({ // Réglage non chargé : on laisse la valeur par défaut affichée }) - getTree(treeId, authToken) + const treeLoad = getTree(treeId, authToken) .then((result) => { if (!active) return const loadedTree = result?.tree || null @@ -87,14 +124,15 @@ const AdminPanel = ({ if (!active) return setErrorMessage(t('Impossible de charger les paramètres de cet arbre.')) }) - .finally(() => { - if (active) setLoading(false) - }) + + Promise.all([treeLoad, immichLoad]).finally(() => { + if (active) setLoading(false) + }) return () => { active = false } - }, [visible, treeId, authToken]) + }, [visible, treeId, authToken, isAdmin]) const handlePolicyChange = async (nextPolicy) => { if (!treeId || !authToken || savingPolicy || nextPolicy === contributionPolicy) return @@ -253,6 +291,81 @@ const AdminPanel = ({ } } + // ── Connexion Immich de l'arbre ────────────────────────────────────────────── + + const testImmichConnection = async () => { + if (!treeId || !authToken) return + setImmichStatus('testing') + try { + const status = await checkImmichStatus(treeId, authToken) + setImmichStatus(status?.available ? 'ok' : (status?.reason || 'unreachable')) + } catch (err) { + setImmichStatus('error') + setErrorMessage(getImmichErrorMessage(err, t)) + } + } + + const handleSaveImmichConfig = async (event) => { + event.preventDefault() + if (!treeId || !authToken || immichBusy) return + + const instanceId = immichInstanceId + if (!instanceId) { + setErrorMessage(t('Choisissez l’instance Immich.')) + return + } + const apiKey = immichApiKey.trim() + // Changer d'instance réclame une nouvelle clé : l'ancienne n'est ni conservée ni envoyée + // au nouveau serveur. + const changingInstance = Boolean(immichConfig?.configured && immichConfig.instanceId && immichConfig.instanceId !== instanceId) + if (changingInstance && !apiKey) { + setErrorMessage(t('L’instance Immich change : indiquez la clé d’accès de la nouvelle instance, l’ancienne n’est pas conservée.')) + return + } + if (!immichConfig?.configured && !apiKey) { + setErrorMessage(t('Indiquez la clé d’accès à Immich pour la première configuration.')) + return + } + + setImmichBusy(true) + setErrorMessage('') + setSuccessMessage('') + try { + const config = await saveImmichConfig(treeId, { instanceId, apiKey }, authToken) + setImmichConfig(config || { configured: true, instanceId, label: null, updatedAt: null }) + setImmichApiKey('') + setSuccessMessage(t('Connexion Immich enregistrée.')) + await testImmichConnection() + } catch (err) { + setErrorMessage(getImmichErrorMessage(err, t)) + } finally { + setImmichBusy(false) + } + } + + const handleRemoveImmichConfig = async () => { + if (!treeId || !authToken || immichBusy || !(immichConfig?.configured || immichConfig?.keyNeedsReentry)) return + if (!window.confirm(t('Supprimer la connexion Immich de cet arbre ? La reconnaissance des visages sera désactivée.'))) { + return + } + + setImmichBusy(true) + setErrorMessage('') + setSuccessMessage('') + try { + await removeImmichConfig(treeId, authToken) + setImmichConfig({ configured: false, instanceId: null, label: null, updatedAt: null }) + setImmichInstanceId('') + setImmichApiKey('') + setImmichStatus(null) + setSuccessMessage(t('Connexion Immich supprimée.')) + } catch (err) { + setErrorMessage(getImmichErrorMessage(err, t)) + } finally { + setImmichBusy(false) + } + } + if (!visible) return null return ( @@ -426,6 +539,92 @@ const AdminPanel = ({ )} + {section === 'danger' && immichInstances.length > 0 && ( +
+
+
+ {t('Reconnaissance des visages')} +

{t('La connexion Immich est propre à cet arbre : ses administrateurs choisissent une instance autorisée par l’opérateur du serveur et fournissent leur propre clé d’accès.')}

+ + {immichConfig.configured + ? t('Configurée') + : immichConfig.keyNeedsReentry + ? t('Clé à ressaisir') + : t('Non configurée')} + + {immichConfig?.keyNeedsReentry && ( + + {t('La clé enregistrée ne peut plus être lue (le secret du serveur a changé). Ressaisissez-la pour réactiver la connexion.')} + + )} + {immichConfig?.configured && ( + + {immichStatus === 'ok' && t('Instance joignable.')} + {immichStatus === 'testing' && t('Test en cours…')} + {immichStatus === 'not_configured' && t('Immich n’est pas configuré pour cet arbre.')} + {immichStatus === 'unreachable' && t('Immich est injoignable.')} + {immichStatus === 'error' && t('Test impossible.')} + {(immichStatus === null || immichStatus === undefined) && t('Connexion non testée depuis l’ouverture.')} + + )} +
+ {immichConfig?.configured && ( +
+ +
+ )} +
+ +
+
+ + +
+ +
+ + setImmichApiKey(event.target.value)} + placeholder={immichConfig?.configured + ? (immichConfig.instanceId && immichInstanceId !== immichConfig.instanceId + ? t('Clé d’accès de la nouvelle instance requise') + : t('Laisser vide pour conserver la clé actuelle')) + : t('Clé créée dans Immich (Paramètres > Clés d’API)')} + /> +
+ +
+ + {(immichConfig?.configured || immichConfig?.keyNeedsReentry) && ( + + )} +
+
+
+ )} + {section === 'danger' && (
diff --git a/frontend/src/components/ImmichFacePanel.css b/frontend/src/components/ImmichFacePanel.css new file mode 100644 index 0000000..762f132 --- /dev/null +++ b/frontend/src/components/ImmichFacePanel.css @@ -0,0 +1,102 @@ +/* Association d'un visage Immich : sélecteur de personne avec aperçu du portrait. La fenêtre vient de pz.css */ +.immich-modal-overlay { z-index: 2200; } +.immich-modal-card { max-width: 520px; } + +.immich-body { display: grid; gap: 16px; } + +.immich-current { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + flex-wrap: wrap; + padding: 12px 14px; + border: 1px solid var(--pz-a300); + border-radius: var(--pz-r-m); + background: var(--pz-a50); + font: 500 13px var(--pz-sans); + color: var(--pz-ink-2); +} + +.immich-search { + display: flex; + align-items: center; + gap: 8px; + padding: 10px 12px; + border: 1px solid var(--pz-line); + border-radius: var(--pz-r-m); + background: var(--pz-surface); + color: var(--pz-faint); +} +.immich-search input { + flex: 1; + border: none; + background: transparent; + font: 500 13.5px var(--pz-sans); + color: var(--pz-ink); + outline: none; +} + +.immich-list { + display: grid; + gap: 6px; + max-height: 220px; + overflow-y: auto; + border: 1px solid var(--pz-line); + border-radius: var(--pz-r-m); + padding: 6px; +} +.immich-person { + display: flex; + align-items: center; + gap: 10px; + padding: 7px 10px; + border: 1px solid transparent; + border-radius: calc(var(--pz-r-m) - 3px); + background: var(--pz-surface); + color: var(--pz-ink-2); + font: 500 13px var(--pz-sans); + text-align: left; + cursor: pointer; + transition: background-color 140ms ease, color 140ms ease; +} +.immich-person.is-active { border-color: var(--pz-a500); background: var(--pz-a50); color: var(--pz-a700); } +.immich-person.is-linked:not(.is-active) { border-color: var(--pz-a300); } +.immich-person-name { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.immich-person-tag { margin-left: auto; flex: none; } +@media (hover: hover) and (pointer: fine) { .immich-person:hover:not(.is-active) { background: var(--pz-a50); } } + +/* Miniature ronde d'un visage ; en attente ou sans vignette, un rond neutre avec l'icône. */ +.immich-face { + width: 34px; height: 34px; flex: none; display: grid; place-items: center; overflow: hidden; + border-radius: 50%; border: 1px solid var(--pz-line); background: var(--pz-bg); color: var(--pz-faint); +} +.immich-face img { width: 100%; height: 100%; object-fit: cover; display: block; } + +/* Aperçu du visage choisi : même photo que les fiches (carré arrondi), n'apparaît qu'après un choix. */ +.immich-preview { + display: flex; align-items: center; gap: 14px; padding: 12px 14px; + border-radius: var(--pz-r-m); background: var(--pz-a50); +} +.immich-face--preview { + width: 64px; height: 64px; border-radius: 24%; border: 0; + background: var(--pz-a100); color: var(--pz-a700); + box-shadow: 0 0 0 1px rgba(42, 38, 34, .06), var(--pz-shadow); +} +.immich-preview-name { font: 500 14px var(--pz-sans); color: var(--pz-ink-2); } + +.immich-empty { font: 500 13px var(--pz-sans); color: var(--pz-faint); text-align: center; padding: 12px 0; } +.immich-error { margin: 0; } + +/* Demande de confirmation avant de remplacer un portrait déjà en place. */ +.immich-confirm { + margin: 0; + padding: 12px 14px; + border: 1px solid var(--pz-danger); + border-radius: var(--pz-r-m); + background: var(--pz-danger-bg); + color: var(--pz-danger); + font: 500 13px/1.5 var(--pz-sans); +} +.immich-spin { animation: immich-rotate 900ms linear infinite; } +@keyframes immich-rotate { to { transform: rotate(360deg); } } diff --git a/frontend/src/components/ImmichFacePanel.jsx b/frontend/src/components/ImmichFacePanel.jsx new file mode 100644 index 0000000..c3a1223 --- /dev/null +++ b/frontend/src/components/ImmichFacePanel.jsx @@ -0,0 +1,364 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { Loader2, Search, Unlink, UserRound, X } from 'lucide-react' +import { createPortal } from 'react-dom' + +import { + assignImmichPerson, + checkImmichStatus, + fetchImmichLink, + fetchImmichThumbnail, + getImmichErrorMessage, + listImmichPeople, + unassignImmichPerson, +} from '../api/immichApi.js' +import { t } from '../i18n/index.js' +import PzBusy from './PzBusy.jsx' +import './ImmichFacePanel.css' + +// Nombre de miniatures chargées en même temps : une liste peut compter beaucoup de visages. +const MAX_PARALLEL_THUMBNAILS = 3 + +// Miniatures du panneau : une requête par visage, mise en cache le temps du panneau. Les URL +// blob sont révoquées au démontage. Renvoie request(immichPersonId) -> URL blob, ou null. +function useFaceThumbnails(treeId, token) { + const cacheRef = useRef(new Map()) // immichPersonId -> URL blob, ou null (pas de vignette) + const inflightRef = useRef(new Map()) // immichPersonId -> promesse en attente + const queueRef = useRef([]) + const runningRef = useRef(0) + const mountedRef = useRef(true) + + const pump = useCallback(() => { + while (runningRef.current < MAX_PARALLEL_THUMBNAILS && queueRef.current.length > 0) { + const job = queueRef.current.shift() + runningRef.current += 1 + job().finally(() => { + runningRef.current -= 1 + pump() + }) + } + }, []) + + const request = useCallback((immichPersonId) => { + if (cacheRef.current.has(immichPersonId)) return Promise.resolve(cacheRef.current.get(immichPersonId)) + if (inflightRef.current.has(immichPersonId)) return inflightRef.current.get(immichPersonId) + + const promise = new Promise((resolve) => { + queueRef.current.push(async () => { + let url = null + if (mountedRef.current) { + try { + url = await fetchImmichThumbnail(treeId, immichPersonId, token) + } catch { + url = null + } + } + inflightRef.current.delete(immichPersonId) + if (!mountedRef.current) { + if (url) URL.revokeObjectURL(url) + resolve(null) + return + } + cacheRef.current.set(immichPersonId, url) + resolve(url) + }) + }) + inflightRef.current.set(immichPersonId, promise) + pump() + return promise + }, [treeId, token, pump]) + + useEffect(() => { + mountedRef.current = true + const cache = cacheRef.current + // La file et les promesses en attente ne sont pas vidées : elles se résolvent à vide dès + // qu'elles trouvent le panneau démonté, et restent valables si le montage reprend (StrictMode). + return () => { + mountedRef.current = false + cache.forEach((url) => { if (url) URL.revokeObjectURL(url) }) + cache.clear() + } + }, []) + + return request +} + +// Vrai une fois l'élément affiché (ou tout de suite si eager). Sans IntersectionObserver, vrai. +function useInView(ref, eager) { + const [inView, setInView] = useState(eager) + + useEffect(() => { + if (inView) return undefined + const element = ref.current + if (!element) return undefined + if (typeof IntersectionObserver === 'undefined') { + setInView(true) + return undefined + } + const observer = new IntersectionObserver((entries) => { + if (entries.some((entry) => entry.isIntersecting)) { + setInView(true) + observer.disconnect() + } + }, { rootMargin: '120px' }) + observer.observe(element) + return () => observer.disconnect() + }, [inView, ref]) + + return inView +} + +// Visage d'une personne Immich : sa miniature ronde, chargée à l'affichage. En attente, ou sans +// vignette, un rond neutre avec l'icône. +const FaceThumb = ({ immichPersonId, hasThumbnail, request, eager = false, className = '' }) => { + const ref = useRef(null) + const inView = useInView(ref, eager) + const [url, setUrl] = useState(null) + + useEffect(() => { + if (!inView || !hasThumbnail || !immichPersonId) return undefined + let cancelled = false + request(immichPersonId).then((loaded) => { if (!cancelled) setUrl(loaded) }) + return () => { cancelled = true } + }, [inView, hasThumbnail, immichPersonId, request]) + + return ( + + ) +} + +// Associer une personne de l'arbre à une personne Immich : sa vignette devient le portrait. +// Réservé aux administrateurs de l'arbre (l'API vérifie le rôle côté serveur). +const ImmichFacePanel = ({ person, treeId, token, onClose, onImmichChange }) => { + const [available, setAvailable] = useState(null) // null : vérification en cours + const [unavailableReason, setUnavailableReason] = useState('') + const [people, setPeople] = useState([]) + const [loadingPeople, setLoadingPeople] = useState(false) + const [linkedId, setLinkedId] = useState(null) // personne Immich déjà associée à cette fiche + const [search, setSearch] = useState('') + const [selected, setSelected] = useState(null) + const [actionLoading, setActionLoading] = useState(false) + const [confirmReplace, setConfirmReplace] = useState(false) + const [error, setError] = useState('') + const requestThumbnail = useFaceThumbnails(treeId, token) + + useEffect(() => { + let cancelled = false + + const load = async () => { + try { + const status = await checkImmichStatus(treeId, token) + if (cancelled) return + setAvailable(Boolean(status?.available)) + setUnavailableReason(status?.available ? '' : (status?.reason || 'unreachable')) + if (!status?.available) return + + setLoadingPeople(true) + const [immichPeople, link] = await Promise.all([ + listImmichPeople(treeId, token), + fetchImmichLink(treeId, person.id, token).catch(() => null), + ]) + if (cancelled) return + setPeople(immichPeople) + setLinkedId(link) + } catch (err) { + if (cancelled) return + setAvailable(false) + setUnavailableReason('') + setError(getImmichErrorMessage(err, t)) + } finally { + if (!cancelled) setLoadingPeople(false) + } + } + + load() + return () => { cancelled = true } + }, [treeId, token, person.id]) + + const handleSelect = useCallback((immichPerson) => { + setSelected(immichPerson) + setError('') + setConfirmReplace(false) + }, []) + + const handleAssign = useCallback(async (replaceAvatar = false) => { + if (!selected || actionLoading) return + setActionLoading(true) + setError('') + try { + await assignImmichPerson(treeId, person.id, selected.id, token, { replaceAvatar }) + onImmichChange?.(person.id) + onClose?.() + } catch (err) { + // Un portrait est déjà en place : le serveur refuse le remplacement en silence + // (409 avatar_exists) ; il revient à l'administrateur de le confirmer. + if (!replaceAvatar && err?.payload?.error === 'avatar_exists') { + setConfirmReplace(true) + } else { + setError(getImmichErrorMessage(err, t)) + } + } finally { + setActionLoading(false) + } + }, [selected, actionLoading, treeId, person, token, onImmichChange, onClose]) + + const handleUnassign = useCallback(async () => { + if (!person.avatarFromImmich || actionLoading) return + setActionLoading(true) + setError('') + try { + await unassignImmichPerson(treeId, person.id, token) + onImmichChange?.(person.id) + onClose?.() + } catch (err) { + setError(getImmichErrorMessage(err, t)) + } finally { + setActionLoading(false) + } + }, [person, actionLoading, treeId, token, onImmichChange, onClose]) + + const filteredPeople = search.trim() + ? people.filter((immichPerson) => immichPerson.name?.toLowerCase().includes(search.trim().toLowerCase())) + : people + + const handleOverlayClick = (event) => { + if (event.target === event.currentTarget) { + onClose() + } + } + + // L'association en place se retire aussi bien sans connexion : changer ou retirer le serveur + // Immich ne laisse jamais une ancienne image impossible à nettoyer manuellement. Le graphe + // ne dit que l'origine du portrait (avatarFromImmich), jamais l'identifiant Immich. + const unassignBlock = person.avatarFromImmich && ( +
+

{t('{name} est déjà associée à une personne Immich.', { name: person.firstName || person.lastName })}

+ +
+ ) + + return createPortal( +
+
+
+

{t('Reconnaissance des visages')}

+

{person.firstName} {person.lastName}

+
+ + + {available === null || loadingPeople ? ( +
+ ) : available === false ? ( +
+ {unassignBlock} +

+ {unavailableReason === 'not_configured' + ? t('Immich n’est pas configuré pour cet arbre. Ses administrateurs le règlent dans Paramètres de l’arbre.') + : t('Immich est injoignable.')} +

+ {error &&
{error}
} +
+ ) : ( +
+ {unassignBlock} + +
+ {t('Personne à associer dans Immich')} +
+
+
+ + {filteredPeople.length === 0 ? ( +

{people.length === 0 ? t('Aucune personne dans Immich.') : t('Aucune personne trouvée.')}

+ ) : ( +
+ {filteredPeople.map((immichPerson) => { + const isSelected = selected?.id === immichPerson.id + const isLinked = linkedId === immichPerson.id + return ( + + ) + })} +
+ )} + + {selected && ( +
+ +
{selected.name || t('Sans nom')}
+
+ )} + + {error &&
{error}
} + + {confirmReplace && ( +

+ {t('Un portrait est déjà en place. Associer cette personne Immich remplacera le portrait actuel et supprimera son fichier.')} +

+ )} + +
+ {confirmReplace ? ( + <> + + + + ) : ( + <> + + + + )} +
+
+ )} +
+
, + document.body + ) +} + +export default ImmichFacePanel diff --git a/frontend/src/components/PersonCard.css b/frontend/src/components/PersonCard.css index e1cd883..b05b50c 100644 --- a/frontend/src/components/PersonCard.css +++ b/frontend/src/components/PersonCard.css @@ -55,6 +55,9 @@ .pc-photo--add:focus-visible { outline: 2px solid var(--pz-a500); outline-offset: 3px; } .pc-photo--add:disabled { opacity: .6; cursor: default; } .pc-photo-actions { display: grid; gap: 4px; justify-items: center; } +/* Menu du choix de source du portrait : au-dessus de la fiche (z-index 1000), sous la modale Immich (2200) */ +.pc-source-backdrop { position: fixed; inset: 0; z-index: 1100; } +.pc-source-menu { position: fixed; z-index: 1150; min-width: 220px; } .pc-photo-btn { border: 0; background: none; padding: 2px 4px; cursor: pointer; font: 500 12px var(--pz-sans); color: var(--pz-a700); text-decoration: underline; text-underline-offset: 2px; diff --git a/frontend/src/components/PersonCard.jsx b/frontend/src/components/PersonCard.jsx index 80e678d..a20cdce 100644 --- a/frontend/src/components/PersonCard.jsx +++ b/frontend/src/components/PersonCard.jsx @@ -1,7 +1,10 @@ import { useState, useEffect, useRef, forwardRef } from 'react' -import { Save, Trash2, Plus, X, Search, Check, Play, ImagePlus } from 'lucide-react' +import { createPortal } from 'react-dom' +import { Save, Trash2, Plus, X, Search, Check, Play, ImagePlus, Sparkles } from 'lucide-react' import { getParents, getChildren, getPersonUnions, getPersonMedias, filiations, persons, unions } from '../data/mockData' +import { fetchImmichConfig } from '../api/immichApi.js' import GeoMediaThumbnail from './GeoMediaThumbnail' +import ImmichFacePanel from './ImmichFacePanel.jsx' import './PersonCard.css' import PzBusy from './PzBusy.jsx' import { t, dateLocale } from '../i18n/index.js' @@ -35,6 +38,9 @@ const PersonCard = ({ onManageMedia, onAvatarUpload, onAvatarDelete, + treeId = null, + immichToken = null, + onImmichChange, avatarActionLoading = false, avatarActionError = '', isAdmin = false, @@ -55,6 +61,14 @@ const PersonCard = ({ const [saving, setSaving] = useState(false) const [saveSuccess, setSaveSuccess] = useState(false) const [showDeleteConfirm, setShowDeleteConfirm] = useState(false) + const [showImmichPanel, setShowImmichPanel] = useState(false) + // null : connexion Immich de l'arbre inconnue, puis booléen. Le menu de source ne se propose + // qu'à qui peut agir (owner/admin de l'arbre, comme pour toute action Immich) et seulement + // si l'arbre est connecté ou qu'une association passée demande un nettoyage. + const [immichConfigured, setImmichConfigured] = useState(null) + const [showSourceMenu, setShowSourceMenu] = useState(false) + const [sourceMenuPos, setSourceMenuPos] = useState({ top: 0, left: 0 }) + const sourceBtnRef = useRef(null) // Inline relation search state const [activeRelationSearch, setActiveRelationSearch] = useState(null) // 'parent' | 'spouse' | 'child' | null @@ -70,8 +84,49 @@ const PersonCard = ({ setActiveRelationSearch(null) setRelationSearchQuery('') setSaveSuccess(false) + setShowSourceMenu(false) }, [person.id]) + // Connexion Immich de l'arbre : métadonnées sans clé. Une erreur (rôle périmé, réseau) se + // traduit par « non configuré » : la fiche reste utilisable, simplement sans choix de source. + // Seul un administrateur de l'arbre voit l'option Immich, comme côté serveur. + useEffect(() => { + let cancelled = false + setImmichConfigured(null) + setShowSourceMenu(false) + if (!editMode || !isAdmin || !treeId || !onImmichChange || !immichToken) return undefined + fetchImmichConfig(treeId, immichToken) + .then(({ config }) => { if (!cancelled) setImmichConfigured(Boolean(config?.configured)) }) + .catch(() => { if (!cancelled) setImmichConfigured(false) }) + return () => { cancelled = true } + }, [editMode, isAdmin, treeId, immichToken, onImmichChange]) + + useEffect(() => { + if (!showSourceMenu) return undefined + const onKeyDown = (event) => { if (event.key === 'Escape') setShowSourceMenu(false) } + window.addEventListener('keydown', onKeyDown) + return () => window.removeEventListener('keydown', onKeyDown) + }, [showSourceMenu]) + + const immichUsable = isAdmin && Boolean(immichConfigured || person.avatarFromImmich) + const openAvatarPicker = () => { + if (avatarActionLoading) return + if (immichUsable) { + const rect = sourceBtnRef.current?.getBoundingClientRect() + if (rect) { + setSourceMenuPos({ + top: Math.round(rect.bottom) + 6, + left: Math.round(Math.min(rect.left, window.innerWidth - 252)), + }) + } + setShowSourceMenu(true) + } else { + avatarInputRef.current?.click() + } + } + const chooseFileSource = () => { setShowSourceMenu(false); avatarInputRef.current?.click() } + const chooseImmichSource = () => { setShowSourceMenu(false); setShowImmichPanel(true) } + // Focus search input when relation search opens useEffect(() => { if (activeRelationSearch) { @@ -363,11 +418,24 @@ const PersonCard = ({ )} {editMode && onAvatarUpload && (
- {person.photo && ( - )} @@ -690,6 +758,35 @@ const PersonCard = ({ )} )} + + {/* ── Choix de la source du portrait (menu contextuel) ── */} + {showSourceMenu && ( + createPortal( + <> +
setShowSourceMenu(false)} /> +
+ + +
+ , + document.body, + ) + )} + + {/* ── Association d'un visage Immich (modale) ── */} + {showImmichPanel && treeId && ( + setShowImmichPanel(false)} + onImmichChange={onImmichChange} + /> + )}
) } diff --git a/frontend/src/components/SettingsPanels.css b/frontend/src/components/SettingsPanels.css index 5590e36..9325a9a 100644 --- a/frontend/src/components/SettingsPanels.css +++ b/frontend/src/components/SettingsPanels.css @@ -44,6 +44,8 @@ .ts-row--muted { opacity: .6; } .ts-row-text { display: grid; gap: 4px; min-width: 0; } .ts-row-text strong { font: 500 14.5px var(--pz-sans); color: var(--pz-ink); } +/* La grille étire ses enfants : une pastille garde la largeur de son texte. */ +.ts-row-text > .pz-tag { justify-self: start; } .ts-row-actions { display: flex; gap: 6px; flex-wrap: wrap; justify-content: flex-end; flex: none; } .ts-file { justify-self: start; margin-top: 4px; } .ts-file-input { display: none; } diff --git a/frontend/src/data/mockData.js b/frontend/src/data/mockData.js index 7a1084d..6c3d1ba 100644 --- a/frontend/src/data/mockData.js +++ b/frontend/src/data/mockData.js @@ -115,6 +115,7 @@ function mapRemotePersonToLocal(person, current = null) { profession: person?.profession || null, nationality: person?.nationality || null, photo: current?.photo || null, + avatarFromImmich: person?.avatarFromImmich ?? false, } } diff --git a/frontend/src/data/mockData.test.js b/frontend/src/data/mockData.test.js index 91ee070..ee6caf9 100644 --- a/frontend/src/data/mockData.test.js +++ b/frontend/src/data/mockData.test.js @@ -15,6 +15,7 @@ describe('loadGraphData avatar mapping', () => { deathDate: null, notes: null, avatarUrlPath: '/trees/t-1/persons/p-1/avatar', + avatarFromImmich: true, }, { id: 'p-2', @@ -24,6 +25,7 @@ describe('loadGraphData avatar mapping', () => { deathDate: null, notes: null, avatarUrlPath: null, + avatarFromImmich: false, }, ], unions: [], @@ -48,6 +50,9 @@ describe('loadGraphData avatar mapping', () => { expect(getPersonById('p-1')?.photo).toBe('/api/trees/t-1/persons/p-1/avatar?token=abc') expect(getPersonById('p-2')?.photo).toBeNull() expect(getPersonMedias('p-2')[0]?.source).toBe('Album familial') + // Origine du portrait portée par la personne (faux quand il ne vient pas d'Immich) + expect(getPersonById('p-1')?.avatarFromImmich).toBe(true) + expect(getPersonById('p-2')?.avatarFromImmich).toBe(false) }) }) diff --git a/frontend/src/i18n/en/compte.js b/frontend/src/i18n/en/compte.js index 82a85cf..d90300c 100644 --- a/frontend/src/i18n/en/compte.js +++ b/frontend/src/i18n/en/compte.js @@ -123,6 +123,29 @@ export default { "Dernière vérification": "Final check", "Supprimer « {name} »": "Delete “{name}”", "Tapez le nom exact de l'arbre pour confirmer.": "Type the exact name of the tree to confirm.", + // Section Immich dans l'onglet Avancé (AdminPanel) + 'La connexion Immich est propre à cet arbre : ses administrateurs choisissent une instance autorisée par l’opérateur du serveur et fournissent leur propre clé d’accès.': 'The Immich connection belongs to this tree: its administrators pick an instance authorized by the server operator and provide their own access key.', + 'Configurée': 'Configured', + 'Non configurée': 'Not configured', + 'Clé à ressaisir': 'Key to re-enter', + 'La clé enregistrée ne peut plus être lue (le secret du serveur a changé). Ressaisissez-la pour réactiver la connexion.': 'The saved key can no longer be read (the server secret changed). Enter it again to reactivate the connection.', + 'Instance joignable.': 'Instance reachable.', + 'Test en cours…': 'Testing…', + 'Test impossible.': 'Test failed.', + 'Connexion non testée depuis l’ouverture.': 'Connection not tested since the panel opened.', + 'Tester la connexion': 'Test the connection', + 'Instance Immich': 'Immich instance', + 'Choisir une instance…': 'Choose an instance…', + 'Choisissez l’instance Immich.': 'Choose the Immich instance.', + 'Clé d’accès Immich': 'Immich access key', + 'Laisser vide pour conserver la clé actuelle': 'Leave empty to keep the current key', + 'Clé d’accès de la nouvelle instance requise': 'New instance access key required', + 'L’instance Immich change : indiquez la clé d’accès de la nouvelle instance, l’ancienne n’est pas conservée.': 'The Immich instance is changing: enter the new instance’s access key — the old one is not kept.', + 'Clé créée dans Immich (Paramètres > Clés d’API)': 'Key created in Immich (Settings > API Keys)', + 'Supprimer la connexion': 'Remove the connection', + 'Connexion Immich enregistrée.': 'Immich connection saved.', + 'Supprimer la connexion Immich de cet arbre ? La reconnaissance des visages sera désactivée.': 'Remove this tree\'s Immich connection? Face recognition will be disabled.', + 'Connexion Immich supprimée.': 'Immich connection removed.', // Onglet Visites (TreeVisitsSection) "téléphone": "phone", "tablette": "tablet", diff --git a/frontend/src/i18n/en/fiche.js b/frontend/src/i18n/en/fiche.js index 2c1fcbe..515c3ee 100644 --- a/frontend/src/i18n/en/fiche.js +++ b/frontend/src/i18n/en/fiche.js @@ -259,4 +259,36 @@ export default { 'En rédaction': 'In the newsroom', 'Interview archive radio': 'Archived radio interview', 'Inconnu': 'Unknown', + // Visages venus d'Immich (PersonCard, ImmichFacePanel, immichApi) + 'Depuis Immich': 'From Immich', + 'Depuis un fichier': 'From a file', + 'Source du portrait': 'Portrait source', + 'Visage Immich': 'Immich face', + 'Reconnaissance des visages': 'Face recognition', + 'Immich n’est pas configuré pour cet arbre.': 'Immich is not configured for this tree.', + 'Immich n’est pas configuré pour cet arbre. Ses administrateurs le règlent dans Paramètres de l’arbre.': 'Immich is not configured for this tree. Its administrators set it up in Tree settings.', + 'Immich est injoignable.': 'Immich cannot be reached.', + 'La clé d’accès à Immich a été refusée.': 'The Immich access key was rejected.', + 'Personne introuvable dans Immich.': 'Person not found in Immich.', + 'Identifiant Immich invalide.': 'Invalid Immich identifier.', + 'La vignette Immich n’est pas une image valide.': 'The Immich thumbnail is not a valid image.', + 'Espace disque de l’arbre dépassé.': 'Tree storage quota exceeded.', + 'Indiquez la clé d’accès à Immich pour la première configuration.': 'Enter the Immich access key for the first setup.', + 'Cette instance Immich n’est pas autorisée par l’opérateur du serveur.': 'This Immich instance is not authorized by the server operator.', + 'Seuls les administrateurs de l’arbre peuvent associer un visage Immich.': 'Only tree administrators can link an Immich face.', + 'Erreur inattendue.': 'Unexpected error.', + '{name} est déjà associée à une personne Immich.': '{name} is already linked to an Immich person.', + 'Retirer l’association': 'Remove the link', + 'Personne à associer dans Immich': 'Immich person to link', + 'Rechercher par nom': 'Search by name', + 'Aucune personne dans Immich.': 'No people in Immich.', + 'Aucune personne trouvée.': 'No people found.', + 'Personnes Immich': 'Immich people', + 'Sans nom': 'Unnamed', + 'Associée': 'Linked', + 'Associer et prendre le portrait': 'Link and use as portrait', + 'Un portrait est déjà en place. Associer cette personne Immich remplacera le portrait actuel et supprimera son fichier.': + 'A portrait is already in place. Linking this Immich person will replace the current portrait and delete its file.', + 'Garder le portrait actuel': 'Keep the current portrait', + 'Remplacer le portrait et associer': 'Replace the portrait and link', } diff --git a/frontend/src/utils/graphAdapter.js b/frontend/src/utils/graphAdapter.js index 7fb09ca..c079b16 100644 --- a/frontend/src/utils/graphAdapter.js +++ b/frontend/src/utils/graphAdapter.js @@ -57,6 +57,7 @@ export function adaptGraphForGalaxy(apiGraph, _treeId) { birthDate: p.birthDate, deathDate: p.deathDate, photo: p.avatarUrlPath ? `/api${p.avatarUrlPath}` : null, + avatarFromImmich: Boolean(p.avatarFromImmich), frameType: 'round', // Default }))