From 378071bf138fd283df7d4e978cf8e3d043240206 Mon Sep 17 00:00:00 2001 From: Mistral Vibe Date: Mon, 12 Oct 2026 11:53:12 +0200 Subject: [PATCH 01/22] =?UTF-8?q?Int=C3=A9gration=20Immich=20:=20associer?= =?UTF-8?q?=20un=20visage=20=C3=A0=20une=20personne=20de=20l'arbre?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Colonne persons.immichPersonId (schéma + migration 20261012_001) et exposition dans le graphe pour l'afficher côté fiche. - Client Immich (src/lib/immich.ts) sur le contrat OpenAPI v3.1.0 : ping, /api/people paginé, vignette par personne ; erreurs distinctes entre injoignable, clé refusée et introuvable, identifiants validés comme UUID v4. - Routes /trees/:id/immich/* (status, people, thumbnail, assign, unassign), réservées aux administrateurs de l'arbre ; l'adresse et la clé d'Immich ne quittent jamais le backend. - La vignette passe par le pipeline des portraits (type lu dans les octets, métadonnées retirées, quota de l'arbre) : le fichier est écrit avant la transaction (personne + journal immich_assign) et l'ancien portrait est supprimé après ; un échec du nettoyage est journalisé sans faire échouer la requête. Le désassignement retire le portrait seulement s'il vient d'Immich (préfixe immich-) et préserve un portrait envoyé à la main. - Côté front : bouton « Depuis Immich » sur la fiche en édition, panneau de sélection avec aperçu et retrait de l'association, traductions anglaises, messages d'erreur distincts. - Tests : 16 tests backend (succès, 400/401/403/404/413/502/503, quota, échec de transaction, préservation du portrait manuel, serveur désactivé) et le mapping immichPersonId côté front. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- backend/.env.example | 5 + backend/.env.production.example | 6 + .../migration.sql | 2 + backend/prisma/schema.prisma | 2 + backend/src/app.ts | 2 + backend/src/config/env.ts | 4 + backend/src/lib/immich.ts | 153 +++++ backend/src/routes/immich.ts | 360 +++++++++++ backend/src/routes/media.ts | 9 +- backend/src/utils/graph-payload.ts | 2 + backend/test/immich-unconfigured.test.ts | 99 +++ backend/test/immich.test.ts | 571 ++++++++++++++++++ frontend/src/App.jsx | 8 + frontend/src/api/immichApi.js | 57 ++ frontend/src/components/ImmichFacePanel.css | 81 +++ frontend/src/components/ImmichFacePanel.jsx | 220 +++++++ frontend/src/components/PersonCard.jsx | 23 +- frontend/src/data/mockData.js | 1 + frontend/src/data/mockData.test.js | 5 + frontend/src/i18n/en/fiche.js | 23 + frontend/src/utils/graphAdapter.js | 1 + 21 files changed, 1629 insertions(+), 5 deletions(-) create mode 100644 backend/prisma/migrations/20261012_001_add_immich_person_id/migration.sql create mode 100644 backend/src/lib/immich.ts create mode 100644 backend/src/routes/immich.ts create mode 100644 backend/test/immich-unconfigured.test.ts create mode 100644 backend/test/immich.test.ts create mode 100644 frontend/src/api/immichApi.js create mode 100644 frontend/src/components/ImmichFacePanel.css create mode 100644 frontend/src/components/ImmichFacePanel.jsx diff --git a/backend/.env.example b/backend/.env.example index b6d997d..9f87832 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 via une instance Immich (https://immich.app). Désactivé par défaut. +# IMMICH_API_URL : adresse de l'API, sans slash final. IMMICH_API_KEY : clé créée dans Immich. +IMMICH_ENABLED=false +IMMICH_API_URL="http://immich.example.org:2283" +IMMICH_API_KEY="" diff --git a/backend/.env.production.example b/backend/.env.production.example index 75296d2..3c49081 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 via une instance Immich (https://immich.app). Désactivé par défaut. +# IMMICH_API_URL : adresse de l'API, sans slash final. IMMICH_API_KEY : clé créée dans Immich. +IMMICH_ENABLED=false +IMMICH_API_URL="http://immich.example.org:2283" +IMMICH_API_KEY="" 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/schema.prisma b/backend/prisma/schema.prisma index a80a8d5..cd8290a 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -208,6 +208,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..5aa7530 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), + // Reconnaissance des visages via Immich : désactivé par défaut, adresse et clé de l'instance. + IMMICH_ENABLED: z.preprocess((val) => String(val).toLowerCase() === 'true', z.boolean()).default(false), + IMMICH_API_URL: z.string().url().optional(), + IMMICH_API_KEY: z.string().min(1).optional(), }) export const env = envSchema.parse(process.env) diff --git a/backend/src/lib/immich.ts b/backend/src/lib/immich.ts new file mode 100644 index 0000000..0edf9bb --- /dev/null +++ b/backend/src/lib/immich.ts @@ -0,0 +1,153 @@ +import { env } from '../config/env.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 + +// 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 + } + + private buildUrl(path: string): string { + return new URL(path, `${this.apiUrl}/`).toString() + } + + 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), + }) + } 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 + + // 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) { + const response = await this.fetch(`/api/people?page=${page}&size=${IMMICH_PEOPLE_PAGE_SIZE}`) + const payload = (await response.json()) 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 + } + + // Vignette d'une personne, en octets bruts (JPEG côté Immich). Absente -> ImmichNotFoundError. + async getPersonThumbnail(personId: string): Promise { + const response = await this.fetch(`/api/people/${encodeURIComponent(personId)}/thumbnail`) + return Buffer.from(await response.arrayBuffer()) + } +} + +export function isImmichConfigured(): boolean { + return env.IMMICH_ENABLED && Boolean(env.IMMICH_API_URL && env.IMMICH_API_KEY) +} + +export function getImmichClient(): ImmichClient | null { + if (!isImmichConfigured()) { + return null + } + return new ImmichClient(env.IMMICH_API_URL!, env.IMMICH_API_KEY!) +} diff --git a/backend/src/routes/immich.ts b/backend/src/routes/immich.ts new file mode 100644 index 0000000..b321b5a --- /dev/null +++ b/backend/src/routes/immich.ts @@ -0,0 +1,360 @@ +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 { + getImmichClient, + isImmichConfigured, + isImmichPersonId, + ImmichAuthError, + ImmichNotFoundError, + ImmichUnavailableError, +} from '../lib/immich.js' +import { InvalidMediaError, 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. Toutes les routes sont rattachées à un arbre et réservées à +// ses administrateurs : la liste des visages d'Immich ne se montre pas au premier compte venu. + +const treeParamSchema = z.object({ id: z.string().min(1) }) + +const assignSchema = z.object({ + personId: z.string().min(1), + immichPersonId: z.string().refine(isImmichPersonId, 'invalid_immich_person_id'), +}) + +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'), +}) + +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' }) +} + +function requireConfiguredClient() { + return getImmichClient() +} + +// 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) => { + 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' }) + } + + if (!isImmichConfigured()) { + return reply.send({ available: false, reason: 'not_configured' }) + } + + const client = requireConfiguredClient()! + 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 = requireConfiguredClient() + 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 = requireConfiguredClient() + if (!client) { + return reply.code(503).send({ error: 'immich_not_configured' }) + } + + let thumbnail: Buffer + try { + thumbnail = await client.getPersonThumbnail(params.data.immichPersonId) + } catch (error) { + return replyImmichError(request, reply, error) + } + + if (!thumbnail.length || thumbnail.length > MAX_THUMBNAIL_BYTES) { + request.log.warn({ size: thumbnail.length }, 'Vignette Immich vide ou trop grande') + return reply.code(404).send({ error: 'thumbnail_not_found' }) + } + + // Le type se lit dans les octets, pas dans ce qu'Immich déclare : la vignette finit dans une balise . + const mimeType = sniffMimeType(thumbnail, 'photo') ?? 'image/jpeg' + reply.header('Content-Type', mimeType) + reply.header('Cache-Control', 'private, max-age=3600') + return reply.send(thumbnail) + }) + + 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 = requireConfiguredClient() + 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' }) + } + + // Vignette de la personne Immich : absente -> on associe sans toucher au portrait existant. + let thumbnail: Buffer | null = null + try { + thumbnail = await client.getPersonThumbnail(immichPersonId) + } 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 }) + } + + // 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' }) + } + + 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 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 = person.avatarPath !== null && path.basename(person.avatarPath).startsWith('immich-') + + 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 0488fef..798041a 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 @@ -187,7 +188,7 @@ async function exceedsStorageQuota(app: FastifyRequest['server'], treeId: string // Seules les routes d'envoi acceptent un corps de 12 Mo (fichier en base64), le reste de l'API est à 1 Mo (app.ts) const UPLOAD_RATE_LIMIT = { bodyLimit: UPLOAD_BODY_LIMIT, config: { rateLimit: { max: 30, 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: { diff --git a/backend/src/utils/graph-payload.ts b/backend/src/utils/graph-payload.ts index ea847dc..c66d297 100644 --- a/backend/src/utils/graph-payload.ts +++ b/backend/src/utils/graph-payload.ts @@ -17,6 +17,7 @@ export type GraphPayload = { avatarUrlPath: string | null sex: string | null notes: string | null + immichPersonId: string | null }> unions: Array<{ id: string @@ -90,6 +91,7 @@ export function buildGraphPayload( avatarUrlPath: person.avatarPath ? `/trees/${treeId}/persons/${person.id}/avatar` : null, sex: person.sex, notes: person.notes, + immichPersonId: person.immichPersonId, })), unions: unions.map((union) => ({ id: union.id, diff --git a/backend/test/immich-unconfigured.test.ts b/backend/test/immich-unconfigured.test.ts new file mode 100644 index 0000000..bb84555 --- /dev/null +++ b/backend/test/immich-unconfigured.test.ts @@ -0,0 +1,99 @@ +import { randomUUID } from 'node:crypto' +import type { FastifyInstance } from 'fastify' +import { beforeAll, describe, expect, it, vi } from 'vitest' + +// Immich désactivé : aucune requête vers l'instance ne doit partir, chaque route répond « non configuré ». +// Fichier à part : la configuration est lue au démarrage de l'application, impossible à changer à chaud. + +const { prismaMock } = vi.hoisted(() => ({ + prismaMock: { + user: { + count: vi.fn().mockResolvedValue(1), + }, + person: { + findFirst: vi.fn(), + update: vi.fn(), + }, + treeMembership: { + 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 () => { + delete process.env.IMMICH_ENABLED + delete process.env.IMMICH_API_URL + delete process.env.IMMICH_API_KEY + + 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: disabled server', () => { + it('reports not configured and never calls Immich', 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 }, + }) + + 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 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 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' }) + + expect(fetchMock).not.toHaveBeenCalled() + vi.unstubAllGlobals() + await app.close() + }) +}) diff --git a/backend/test/immich.test.ts b/backend/test/immich.test.ts new file mode 100644 index 0000000..49f28b2 --- /dev/null +++ b/backend/test/immich.test.ts @@ -0,0 +1,571 @@ +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(), + }, + treeMembership: { + 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 +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' } }) +} + +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' + process.env.IMMICH_ENABLED = 'true' + process.env.IMMICH_API_URL = 'http://immich.test' + process.env.IMMICH_API_KEY = 'test-key' + + 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() + + 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 }, + }) + + prismaMock.person.findFirst.mockResolvedValue(null) + prismaMock.person.update.mockResolvedValue({ id: 'person-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('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 : 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 }) + fetchMock.mockResolvedValue(new Response(new Uint8Array(jpegBytes), { status: 200 })) + + 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: 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('assigns without touching the avatar when Immich has no thumbnail', async () => { + const app = createApp() + const token = await createUserToken(app) + + prismaMock.person.findFirst.mockResolvedValue({ id: 'person-1', avatarPath: 'tree-1/person-1/avatar-keep.jpg' }) + 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-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('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 }) + fetchMock.mockResolvedValue(new Response(new Uint8Array(jpegBytes), { status: 200 })) + + 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 }) + fetchMock.mockResolvedValue(new Response(new Uint8Array(jpegBytes), { status: 200 })) + 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 }, + }) + + 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('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() + }) +}) diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 6d1fb8c..f9cea5d 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -1503,6 +1503,11 @@ function App() { } }, [auth.userAuth.token, tree.treeContext.accessToken, tree.treeContext.treeId, refreshTreeAndKeepSelection]) + // 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) => { const accessToken = tree.treeContext.accessToken || auth.userAuth.token if (!accessToken || !tree.treeContext.treeId) return @@ -2698,6 +2703,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} diff --git a/frontend/src/api/immichApi.js b/frontend/src/api/immichApi.js new file mode 100644 index 0000000..f045f41 --- /dev/null +++ b/frontend/src/api/immichApi.js @@ -0,0 +1,57 @@ +import { API_BASE_URL, apiRequest } from './client.js' + +// Reconnaissance des visages : l'API du backend parle à Immich et ne lui expose ni son +// adresse ni sa clé. 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é sur le serveur.') + 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 === '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.') +} + +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 : [] +} + +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) { + return apiRequest(`/trees/${encodeURIComponent(treeId)}/immich/assign`, withAuth({ + method: 'POST', + body: JSON.stringify({ personId, immichPersonId }), + }, 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/ImmichFacePanel.css b/frontend/src/components/ImmichFacePanel.css new file mode 100644 index 0000000..b5fa855 --- /dev/null +++ b/frontend/src/components/ImmichFacePanel.css @@ -0,0 +1,81 @@ +/* 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: 9px 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); } +@media (hover: hover) and (pointer: fine) { .immich-person:hover:not(.is-active) { background: var(--pz-a50); } } + +.immich-preview { + display: grid; + justify-items: center; + gap: 8px; + padding: 12px; + border: 1px dashed var(--pz-line); + border-radius: var(--pz-r-m); +} +.immich-preview img { width: 96px; height: 96px; object-fit: cover; border-radius: 50%; } +.immich-preview-empty { width: 96px; height: 96px; display: grid; place-items: center; border-radius: 50%; background: var(--pz-surface); color: var(--pz-faint); } +.immich-preview-name { font: 500 13px var(--pz-sans); color: var(--pz-faint); } + +.immich-empty { font: 500 13px var(--pz-sans); color: var(--pz-faint); text-align: center; padding: 12px 0; } +.immich-error { margin: 0; } +.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..1c57acf --- /dev/null +++ b/frontend/src/components/ImmichFacePanel.jsx @@ -0,0 +1,220 @@ +import { useCallback, useEffect, useRef, useState } from 'react' +import { ImagePlus, Loader2, Search, Unlink, UserRound, X } from 'lucide-react' + +import { + assignImmichPerson, + checkImmichStatus, + fetchImmichThumbnail, + getImmichErrorMessage, + listImmichPeople, + unassignImmichPerson, +} from '../api/immichApi.js' +import { t } from '../i18n/index.js' +import PzBusy from './PzBusy.jsx' +import './ImmichFacePanel.css' + +// 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 [search, setSearch] = useState('') + const [selected, setSelected] = useState(null) + const [thumbnailUrl, setThumbnailUrl] = useState(null) + const [actionLoading, setActionLoading] = useState(false) + const [error, setError] = useState('') + const thumbnailRef = useRef(null) + + const releaseThumbnail = useCallback(() => { + if (thumbnailRef.current) { + URL.revokeObjectURL(thumbnailRef.current) + thumbnailRef.current = null + } + setThumbnailUrl(null) + }, []) + + useEffect(() => { + let cancelled = false + releaseThumbnail() + + 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 = await listImmichPeople(treeId, token) + if (cancelled) return + setPeople(immichPeople) + } catch (err) { + if (cancelled) return + setAvailable(false) + setUnavailableReason('') + setError(getImmichErrorMessage(err, t)) + } finally { + if (!cancelled) setLoadingPeople(false) + } + } + + load() + return () => { cancelled = true } + }, [treeId, token, releaseThumbnail]) + + useEffect(() => releaseThumbnail, [releaseThumbnail]) + + const loadThumbnail = useCallback(async (immichPersonId) => { + releaseThumbnail() + try { + const url = await fetchImmichThumbnail(treeId, immichPersonId, token) + thumbnailRef.current = url + setThumbnailUrl(url) + } catch { + setThumbnailUrl(null) + } + }, [treeId, token, releaseThumbnail]) + + const handleSelect = useCallback((immichPerson) => { + setSelected(immichPerson) + setError('') + if (immichPerson?.hasThumbnail && immichPerson?.id) { + loadThumbnail(immichPerson.id) + } else { + releaseThumbnail() + } + }, [loadThumbnail, releaseThumbnail]) + + const handleAssign = useCallback(async () => { + if (!selected || actionLoading) return + setActionLoading(true) + setError('') + try { + await assignImmichPerson(treeId, person.id, selected.id, token) + onImmichChange?.(person.id) + onClose?.() + } catch (err) { + setError(getImmichErrorMessage(err, t)) + } finally { + setActionLoading(false) + } + }, [selected, actionLoading, treeId, person, token, onImmichChange, onClose]) + + const handleUnassign = useCallback(async () => { + if (!person.immichPersonId || 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() + } + } + + return ( +
+
+
+

{t('Reconnaissance des visages')}

+

{person.firstName} {person.lastName}

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

+ {unavailableReason === 'not_configured' + ? t('Immich n’est pas configuré sur le serveur.') + : t('Immich est injoignable.')} +

+
+ ) : ( +
+ {person.immichPersonId && ( +
+

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

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

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

+ ) : ( +
+ {filteredPeople.map((immichPerson) => ( + + ))} +
+ )} + +
+ {thumbnailUrl + ? {selected?.name + :
} +
{selected?.name || t('Aucune sélection')}
+
+ + {error &&
{error}
} + +
+ + +
+
+ )} +
+
+ ) +} + +export default ImmichFacePanel diff --git a/frontend/src/components/PersonCard.jsx b/frontend/src/components/PersonCard.jsx index bf35fdb..5c25c37 100644 --- a/frontend/src/components/PersonCard.jsx +++ b/frontend/src/components/PersonCard.jsx @@ -1,7 +1,8 @@ import { useState, useEffect, useRef, forwardRef } from 'react' -import { Save, Trash2, Plus, X, Search, Check, Play } from 'lucide-react' +import { Save, Trash2, Plus, X, Search, Check, Play, Sparkles } from 'lucide-react' import { getParents, getChildren, getPersonUnions, getPersonMedias, filiations, persons, unions } from '../data/mockData' 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 +36,9 @@ const PersonCard = ({ onManageMedia, onAvatarUpload, onAvatarDelete, + treeId = null, + immichToken = null, + onImmichChange, avatarActionLoading = false, avatarActionError = '', isAdmin = false, @@ -55,6 +59,7 @@ const PersonCard = ({ const [saving, setSaving] = useState(false) const [saveSuccess, setSaveSuccess] = useState(false) const [showDeleteConfirm, setShowDeleteConfirm] = useState(false) + const [showImmichPanel, setShowImmichPanel] = useState(false) // Inline relation search state const [activeRelationSearch, setActiveRelationSearch] = useState(null) // 'parent' | 'spouse' | 'child' | null @@ -356,6 +361,11 @@ const PersonCard = ({ {t('Retirer')} )} + {treeId && onImmichChange && ( + + )} )} @@ -675,6 +685,17 @@ const PersonCard = ({ )} )} + + {/* ── Association d'un visage Immich (modale) ── */} + {showImmichPanel && treeId && ( + setShowImmichPanel(false)} + onImmichChange={onImmichChange} + /> + )} ) } diff --git a/frontend/src/data/mockData.js b/frontend/src/data/mockData.js index b57a489..79b7c71 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, + immichPersonId: person?.immichPersonId ?? null, } } diff --git a/frontend/src/data/mockData.test.js b/frontend/src/data/mockData.test.js index 5caa7fe..ca7de5a 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', + immichPersonId: '123e4567-e89b-42d3-a456-426614174000', }, { id: 'p-2', @@ -24,6 +25,7 @@ describe('loadGraphData avatar mapping', () => { deathDate: null, notes: null, avatarUrlPath: null, + immichPersonId: null, }, ], unions: [], @@ -48,5 +50,8 @@ 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') + // Association Immich portée par la personne (null quand il n'y en a pas) + expect(getPersonById('p-1')?.immichPersonId).toBe('123e4567-e89b-42d3-a456-426614174000') + expect(getPersonById('p-2')?.immichPersonId).toBeNull() }) }) diff --git a/frontend/src/i18n/en/fiche.js b/frontend/src/i18n/en/fiche.js index 2c1fcbe..1e04029 100644 --- a/frontend/src/i18n/en/fiche.js +++ b/frontend/src/i18n/en/fiche.js @@ -259,4 +259,27 @@ 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', + 'Visage Immich': 'Immich face', + 'Reconnaissance des visages': 'Face recognition', + 'Immich n’est pas configuré sur le serveur.': 'Immich is not configured on the server.', + '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.', + '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', + 'Aucune sélection': 'No selection', + 'Associer et prendre le portrait': 'Link and use as portrait', } diff --git a/frontend/src/utils/graphAdapter.js b/frontend/src/utils/graphAdapter.js index 7fb09ca..f0f716f 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, + immichPersonId: p.immichPersonId || null, frameType: 'round', // Default })) From 2f64ceb41d4ead3bfa65deceb5e9afb303e9d10a Mon Sep 17 00:00:00 2001 From: Mistral Vibe Date: Mon, 12 Oct 2026 12:21:52 +0200 Subject: [PATCH 02/22] =?UTF-8?q?.env.example=20:=20documenter=20les=20var?= =?UTF-8?q?iables=20Immich=20pour=20l'auto-h=C3=A9bergement?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Le .env.example racine (docker compose, env_file de l'API) ne mentionnait pas IMMICH_ENABLED, IMMICH_API_URL et IMMICH_API_KEY ; seul le .env.example du backend les documentait. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- .env.example | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/.env.example b/.env.example index f6b17af..807415e 100644 --- a/.env.example +++ b/.env.example @@ -34,6 +34,16 @@ 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) ──────────────── +# Associer à chaque personne de l'arbre un visage reconnu par votre instance +# Immich (https://immich.app) ; sa vignette devient le portrait. +# IMMICH_ENABLED : true pour activer. IMMICH_API_URL : adresse de l'instance, +# sans slash final. IMMICH_API_KEY : clé créée dans Immich (Paramètres > Clés d'API). +# Sans ces trois valeurs, la fonction reste éteinte. +# IMMICH_ENABLED=true +# IMMICH_API_URL=http://immich.example.org:2283 +# IMMICH_API_KEY= + # ── 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. From c703a34165dc83ee02457f9ba085c962b37bd12f Mon Sep 17 00:00:00 2001 From: Mistral Vibe Date: Mon, 12 Oct 2026 13:40:38 +0200 Subject: [PATCH 03/22] =?UTF-8?q?Immich=20:=20v=C3=A9rifier=20l'existence?= =?UTF-8?q?=20d'une=20personne=20avant=20l'association?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Le 404 de la vignette ne distingue pas une personne inexistante d'une vignette manquante : l'association pouvait donc être enregistrée pour une personne Immich qui n'existe pas. - ImmichClient.getPerson() : GET /api/people/{id} (200 | 404), qui établit l'existence de la personne et annonce sa vignette. - La route d'association rejette une personne inexistante (404 immich_person_not_found) ; un refus d'authentification (502) ou une erreur serveur (503) n'est jamais pris pour une absence. - La vignette n'est demandée que si Immich en annonce une ; une vignette manquante chez une personne existante associe toujours sans portrait. - Tests : personne inexistante refusée sans toucher base, audit ni fichiers ; vignette disparue entre les deux appels ; échec d'authentification pendant l'association sans changement en base. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- backend/src/lib/immich.ts | 16 +++++ backend/src/routes/immich.ts | 26 +++++++-- backend/test/immich.test.ts | 109 +++++++++++++++++++++++++++++++++-- 3 files changed, 141 insertions(+), 10 deletions(-) diff --git a/backend/src/lib/immich.ts b/backend/src/lib/immich.ts index 0edf9bb..5b1d288 100644 --- a/backend/src/lib/immich.ts +++ b/backend/src/lib/immich.ts @@ -134,6 +134,22 @@ export class ImmichClient { 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 response.json()) 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. async getPersonThumbnail(personId: string): Promise { const response = await this.fetch(`/api/people/${encodeURIComponent(personId)}/thumbnail`) diff --git a/backend/src/routes/immich.ts b/backend/src/routes/immich.ts index b321b5a..91f3bd4 100644 --- a/backend/src/routes/immich.ts +++ b/backend/src/routes/immich.ts @@ -11,6 +11,7 @@ import { ImmichAuthError, ImmichNotFoundError, ImmichUnavailableError, + type ImmichPersonSummary, } from '../lib/immich.js' import { InvalidMediaError, removeStoredFile, sniffMimeType } from '../lib/media-files.js' import { exceedsStorageQuota, getStorageRoot, prepareUploadedFile, requireAdminMembership } from './media.js' @@ -184,15 +185,28 @@ export const immichRoutes: FastifyPluginAsync = async (app) => { return reply.code(404).send({ error: 'person_not_found' }) } - // Vignette de la personne Immich : absente -> on associe sans toucher au portrait existant. - let thumbnail: Buffer | null = null + // 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 { - thumbnail = await client.getPersonThumbnail(immichPersonId) + immichPerson = await client.getPerson(immichPersonId) } catch (error) { - if (!(error instanceof ImmichNotFoundError)) { - return replyImmichError(request, reply, 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) + } catch (error) { + if (!(error instanceof ImmichNotFoundError)) { + return replyImmichError(request, reply, error) + } + // Vignette absente : l'association se fait sans portrait. } - // Vignette absente : l'association se fait sans portrait. } if (!thumbnail) { diff --git a/backend/test/immich.test.ts b/backend/test/immich.test.ts index 49f28b2..d18236f 100644 --- a/backend/test/immich.test.ts +++ b/backend/test/immich.test.ts @@ -46,6 +46,20 @@ 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( @@ -305,7 +319,7 @@ describe('Immich integration: assign', () => { await writeFile(await absStoragePath(oldAvatarRelative), 'old avatar') prismaMock.person.findFirst.mockResolvedValue({ id: 'person-1', avatarPath: oldAvatarRelative }) - fetchMock.mockResolvedValue(new Response(new Uint8Array(jpegBytes), { status: 200 })) + mockImmichPerson() const response = await app.inject({ method: 'POST', @@ -346,7 +360,36 @@ describe('Immich integration: assign', () => { const token = await createUserToken(app) prismaMock.person.findFirst.mockResolvedValue({ id: 'person-1', avatarPath: 'tree-1/person-1/avatar-keep.jpg' }) - fetchMock.mockResolvedValue(new Response('', { status: 404 })) + 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', @@ -365,6 +408,64 @@ describe('Immich integration: assign', () => { 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) @@ -426,7 +527,7 @@ describe('Immich integration: assign', () => { await writeFile(path.join(storageRoot, 'tree-quota', 'big.bin'), Buffer.alloc(1024 * 1024)) prismaMock.person.findFirst.mockResolvedValue({ id: 'person-quota', avatarPath: null }) - fetchMock.mockResolvedValue(new Response(new Uint8Array(jpegBytes), { status: 200 })) + mockImmichPerson() const response = await app.inject({ method: 'POST', @@ -449,7 +550,7 @@ describe('Immich integration: assign', () => { await writeFile(await absStoragePath(oldAvatarRelative), 'old avatar') prismaMock.person.findFirst.mockResolvedValue({ id: 'person-tx', avatarPath: oldAvatarRelative }) - fetchMock.mockResolvedValue(new Response(new Uint8Array(jpegBytes), { status: 200 })) + mockImmichPerson() prismaMock.$transaction.mockRejectedValue(new Error('db down')) const response = await app.inject({ From 50873a4f9e1bd69fa11302fc7e36b857fb541896 Mon Sep 17 00:00:00 2001 From: Mistral Vibe Date: Mon, 12 Oct 2026 16:48:48 +0200 Subject: [PATCH 04/22] Fix Immich modal positioning with portal to always see the Associate button --- frontend/src/components/ImmichFacePanel.jsx | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/frontend/src/components/ImmichFacePanel.jsx b/frontend/src/components/ImmichFacePanel.jsx index 1c57acf..6e6d077 100644 --- a/frontend/src/components/ImmichFacePanel.jsx +++ b/frontend/src/components/ImmichFacePanel.jsx @@ -1,5 +1,6 @@ import { useCallback, useEffect, useRef, useState } from 'react' import { ImagePlus, Loader2, Search, Unlink, UserRound, X } from 'lucide-react' +import { createPortal } from 'react-dom' import { assignImmichPerson, @@ -128,7 +129,7 @@ const ImmichFacePanel = ({ person, treeId, token, onClose, onImmichChange }) => } } - return ( + return createPortal(
@@ -213,7 +214,8 @@ const ImmichFacePanel = ({ person, treeId, token, onClose, onImmichChange }) =>
)}
-
+ , + document.body ) } From a3386824d3af764f722c7d6a0532c525677880b5 Mon Sep 17 00:00:00 2001 From: Mistral Vibe Date: Tue, 13 Oct 2026 14:04:45 +0200 Subject: [PATCH 05/22] =?UTF-8?q?Immich=20par=20arbre=20:=20connexion=20pr?= =?UTF-8?q?opre=20=C3=A0=20chaque=20arbre,=20instances=20autoris=C3=A9es?= =?UTF-8?q?=20par=20l'op=C3=A9rateur?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Nouvelle table tree_immich_configs (adresse + clé d'API chiffrée AES-256-GCM, clé dérivée de JWT_SECRET) et routes GET/PUT/DELETE /trees/:id/immich/config réservées aux administrateurs de l'arbre ; journal d'audit sans secret (adresse et « clé changée » uniquement). - Fin des variables d'env IMMICH_ENABLED / IMMICH_API_URL / IMMICH_API_KEY : l'adresse se choisit parmi IMMICH_ALLOWED_API_URLS, la liste établie par l'opérateur du serveur. Elle filtre l'enregistrement ET chaque requête : retirer une adresse coupe aussitôt les connexions qui l'utilisent. - Changer d'instance exige une nouvelle clé : l'ancienne est écrasée et ne voyage jamais vers le nouveau serveur. - Le désassignement reste possible sans connexion : purement local, il nettoie association et portrait stocké même après suppression de la connexion ; le panneau affiche « Retirer l'association » dans tous les états. - Onglet Immich dans Paramètres de l'arbre : menu des instances autorisées, test de connexion, suppression avec confirmation ; i18n anglais des nouveaux messages. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- .env.example | 14 +- backend/.env.example | 9 +- backend/.env.production.example | 9 +- .../migration.sql | 13 + backend/prisma/schema.prisma | 14 + backend/src/config/env.ts | 8 +- backend/src/lib/immich-secret.ts | 37 ++ backend/src/lib/immich.ts | 80 ++- backend/src/routes/immich.ts | 178 ++++++- backend/test/immich-config.test.ts | 498 ++++++++++++++++++ backend/test/immich-unconfigured.test.ts | 87 ++- backend/test/immich.test.ts | 48 +- frontend/src/api/immichApi.js | 34 +- frontend/src/components/AdminPanel.jsx | 199 ++++++- frontend/src/components/ImmichFacePanel.jsx | 24 +- frontend/src/i18n/en/compte.js | 24 + frontend/src/i18n/en/fiche.js | 5 +- 17 files changed, 1218 insertions(+), 63 deletions(-) create mode 100644 backend/prisma/migrations/20261013_001_tree_immich_config/migration.sql create mode 100644 backend/src/lib/immich-secret.ts create mode 100644 backend/test/immich-config.test.ts diff --git a/.env.example b/.env.example index 807415e..8ce44dc 100644 --- a/.env.example +++ b/.env.example @@ -35,14 +35,12 @@ CORS_ORIGIN=http://localhost # MEDIA_PENDING_QUOTA_PER_TREE_MB=500 # ── Immich (reconnaissance des visages, désactivé par défaut) ──────────────── -# Associer à chaque personne de l'arbre un visage reconnu par votre instance -# Immich (https://immich.app) ; sa vignette devient le portrait. -# IMMICH_ENABLED : true pour activer. IMMICH_API_URL : adresse de l'instance, -# sans slash final. IMMICH_API_KEY : clé créée dans Immich (Paramètres > Clés d'API). -# Sans ces trois valeurs, la fonction reste éteinte. -# IMMICH_ENABLED=true -# IMMICH_API_URL=http://immich.example.org:2283 -# IMMICH_API_KEY= +# Instances Immich autorisées sur ce serveur, séparées par des virgules. Les +# administrateurs de chaque arbre choisissent la leur dans cette liste et donnent +# leur propre clé d'API (créée dans Immich, Paramètres > Clés d'API) ; la clé est +# chiffrée en base. 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=http://immich.example.org:2283,https://immich.example.org # ── Images ──────────────────────────────────────────────────────────────────── # Version des images ghcr.io/iliesallali/parenthese-api et parenthese-web : latest (dernière diff --git a/backend/.env.example b/backend/.env.example index 9f87832..4527662 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -6,8 +6,7 @@ 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 via une instance Immich (https://immich.app). Désactivé par défaut. -# IMMICH_API_URL : adresse de l'API, sans slash final. IMMICH_API_KEY : clé créée dans Immich. -IMMICH_ENABLED=false -IMMICH_API_URL="http://immich.example.org:2283" -IMMICH_API_KEY="" +# Reconnaissance des visages : instances Immich autorisées sur ce serveur, séparées par des +# virgules. Les administrateurs de chaque arbre choisissent la leur dans cette liste 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 3c49081..d82156b 100644 --- a/backend/.env.production.example +++ b/backend/.env.production.example @@ -24,8 +24,7 @@ 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 via une instance Immich (https://immich.app). Désactivé par défaut. -# IMMICH_API_URL : adresse de l'API, sans slash final. IMMICH_API_KEY : clé créée dans Immich. -IMMICH_ENABLED=false -IMMICH_API_URL="http://immich.example.org:2283" -IMMICH_API_KEY="" +# Reconnaissance des visages : instances Immich autorisées sur ce serveur, séparées par des +# virgules. Les administrateurs de chaque arbre choisissent la leur dans cette liste et donnent +# leur propre clé d'API. Sans cette liste, la fonction reste éteinte. +IMMICH_ALLOWED_API_URLS="" 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 cd8290a..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 diff --git a/backend/src/config/env.ts b/backend/src/config/env.ts index 5aa7530..1419f0d 100644 --- a/backend/src/config/env.ts +++ b/backend/src/config/env.ts @@ -50,10 +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), - // Reconnaissance des visages via Immich : désactivé par défaut, adresse et clé de l'instance. - IMMICH_ENABLED: z.preprocess((val) => String(val).toLowerCase() === 'true', z.boolean()).default(false), - IMMICH_API_URL: z.string().url().optional(), - IMMICH_API_KEY: z.string().min(1).optional(), + // 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/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 index 5b1d288..bca7887 100644 --- a/backend/src/lib/immich.ts +++ b/backend/src/lib/immich.ts @@ -1,4 +1,7 @@ +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 : @@ -157,13 +160,76 @@ export class ImmichClient { } } -export function isImmichConfigured(): boolean { - return env.IMMICH_ENABLED && Boolean(env.IMMICH_API_URL && env.IMMICH_API_KEY) -} - -export function getImmichClient(): ImmichClient | null { - if (!isImmichConfigured()) { +// 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 + } + return `${url.origin}${url.pathname.replace(/\/+$/, '')}` + } catch { return null } - return new ImmichClient(env.IMMICH_API_URL!, env.IMMICH_API_KEY!) +} + +let allowedApiUrlsCache: string[] | undefined + +// 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. Les entrées invalides sont +// ignorées avec un avertissement. +export function getImmichAllowedApiUrls(): string[] { + if (allowedApiUrlsCache !== undefined) { + return allowedApiUrlsCache + } + + const urls: string[] = [] + for (const entry of env.IMMICH_ALLOWED_API_URLS.split(',')) { + const trimmed = entry.trim() + if (!trimmed) { + continue + } + const normalized = normalizeImmichApiUrl(trimmed) + if (!normalized) { + console.warn(`IMMICH_ALLOWED_API_URLS : entrée ignorée (URL http(s) invalide) : ${trimmed}`) + continue + } + if (!urls.includes(normalized)) { + urls.push(normalized) + } + } + allowedApiUrlsCache = urls + return urls +} + +export function isImmichApiUrlAllowed(value: string): boolean { + const normalized = normalizeImmichApiUrl(value) + return normalized !== null && getImmichAllowedApiUrls().includes(normalized) +} + +// 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 + } + + return new ImmichClient(config.apiUrl, apiKey) } diff --git a/backend/src/routes/immich.ts b/backend/src/routes/immich.ts index 91f3bd4..e9f6b33 100644 --- a/backend/src/routes/immich.ts +++ b/backend/src/routes/immich.ts @@ -5,20 +5,25 @@ import { mkdir, writeFile } from 'node:fs/promises' import { z } from 'zod' import { - getImmichClient, - isImmichConfigured, + getImmichAllowedApiUrls, + getTreeImmichClient, + isImmichApiUrlAllowed, isImmichPersonId, + normalizeImmichApiUrl, ImmichAuthError, ImmichNotFoundError, ImmichUnavailableError, type ImmichPersonSummary, } from '../lib/immich.js' +import { encryptImmichApiKey } from '../lib/immich-secret.js' import { InvalidMediaError, 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. Toutes les routes sont rattachées à un arbre et réservées à -// ses administrateurs : la liste des visages d'Immich ne se montre pas au premier compte venu. +// 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) }) @@ -36,6 +41,17 @@ const thumbnailParamSchema = z.object({ immichPersonId: z.string().refine(isImmichPersonId, 'invalid_immich_person_id'), }) +// Connexion Immich d'un arbre : adresse choisie parmi celles autorisées par l'opérateur du +// serveur (IMMICH_ALLOWED_API_URLS). 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({ + apiUrl: z + .string() + .url() + .refine((value) => value.startsWith('http://') || value.startsWith('https://'), 'invalid_api_url'), + apiKey: z.string().min(1).max(512).optional(), +}) + const MAX_THUMBNAIL_BYTES = 5 * 1024 * 1024 function replyImmichError(request: FastifyRequest, reply: FastifyReply, error: unknown): FastifyReply { @@ -52,8 +68,13 @@ function replyImmichError(request: FastifyRequest, reply: FastifyReply, error: u return reply.code(500).send({ error: 'immich_api_error' }) } -function requireConfiguredClient() { - return getImmichClient() +// Métadonnées sûres d'une connexion Immich d'arbre : jamais la clé, jamais son chiffré. Une +// adresse sortie de la liste de l'opérateur vaut « non configuré » : la connexion est inerte. +function immichConfigSummary(config: { apiUrl: string; updatedAt: Date } | null) { + if (!config || !isImmichApiUrlAllowed(config.apiUrl)) { + return { configured: false, apiUrl: null, updatedAt: null } + } + return { configured: true, apiUrl: config.apiUrl, updatedAt: config.updatedAt } } // Portraits venus d'Immich : même nommage que les envois manuels (« avatar- »), avec le @@ -64,6 +85,139 @@ function buildAvatarRelativePath(treeId: string, personId: string, extension: st } 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, updatedAt: true }, + }) + + return reply.send({ + config: immichConfigSummary(config), + // Les administrateurs choisissent parmi cette liste : le front en fait un menu, pas un champ libre. + allowedApiUrls: getImmichAllowedApiUrls(), + }) + }) + + 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'adresse doit faire partie de la liste de l'opérateur : le serveur ne devient jamais + // un proxy vers un service interne choisi librement (SSRF). + if (!isImmichApiUrlAllowed(payload.data.apiUrl)) { + return reply.code(400).send({ error: 'api_url_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 : on ne devine jamais d'identifiants ailleurs. + if (!payload.data.apiKey && !existing) { + 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) !== normalizeImmichApiUrl(payload.data.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: payload.data.apiUrl, apiKeyEnc }, + update: { apiUrl: payload.data.apiUrl, apiKeyEnc }, + select: { apiUrl: 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: { apiUrl: payload.data.apiUrl, 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, apiUrl: 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' }) @@ -78,11 +232,11 @@ export const immichRoutes: FastifyPluginAsync = async (app) => { return reply.code(403).send({ error: 'forbidden' }) } - if (!isImmichConfigured()) { + const client = await getTreeImmichClient(app.prisma, params.data.id) + if (!client) { return reply.send({ available: false, reason: 'not_configured' }) } - const client = requireConfiguredClient()! const available = await client.ping() return reply.send({ available, reason: available ? null : 'unreachable' }) }) @@ -101,7 +255,7 @@ export const immichRoutes: FastifyPluginAsync = async (app) => { return reply.code(403).send({ error: 'forbidden' }) } - const client = requireConfiguredClient() + const client = await getTreeImmichClient(app.prisma, params.data.id) if (!client) { return reply.code(503).send({ error: 'immich_not_configured' }) } @@ -130,7 +284,7 @@ export const immichRoutes: FastifyPluginAsync = async (app) => { return reply.code(403).send({ error: 'forbidden' }) } - const client = requireConfiguredClient() + const client = await getTreeImmichClient(app.prisma, params.data.id) if (!client) { return reply.code(503).send({ error: 'immich_not_configured' }) } @@ -169,7 +323,7 @@ export const immichRoutes: FastifyPluginAsync = async (app) => { return reply.code(403).send({ error: 'forbidden' }) } - const client = requireConfiguredClient() + const client = await getTreeImmichClient(app.prisma, params.data.id) if (!client) { return reply.code(503).send({ error: 'immich_not_configured' }) } @@ -318,6 +472,8 @@ export const immichRoutes: FastifyPluginAsync = async (app) => { 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 diff --git a/backend/test/immich-config.test.ts b/backend/test/immich-config.test.ts new file mode 100644 index 0000000..e213cf0 --- /dev/null +++ b/backend/test/immich-config.test.ts @@ -0,0 +1,498 @@ +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,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, + 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, apiUrl: 'http://immich-tree-1.test' }) + const serialized = JSON.stringify(body) + expect(serialized).not.toContain('secret-key-tree-1') + expect(serialized).not.toContain('apiKey') + expect(serialized).not.toContain(TREE_1_ENC) + 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, apiUrl: null, updatedAt: null }) + expect(response.json().allowedApiUrls).toEqual([ + 'http://immich-tree-1.test', + 'http://immich-tree-2.test', + 'http://immich.example.org:2283', + 'http://immich.example.org', + 'http://immich-moved.example.org', + ]) + 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: { apiUrl: 'http://immich.example.org:2283', apiKey: 'my-new-key' }, + }) + + expect(response.statusCode).toBe(200) + expect(response.json().config).toMatchObject({ configured: true, apiUrl: '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: { apiUrl: 'http://immich.example.org:2283', 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: { apiUrl: 'http://immich-tree-1.test' }, + }) + + expect(response.statusCode).toBe(200) + expect(response.json().config.apiUrl).toBe('http://immich-tree-1.test') + + 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({ + apiUrl: 'http://immich-tree-1.test', + 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: { apiUrl: 'http://immich-moved.example.org' }, + }) + + // 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: { apiUrl: 'http://immich.example.org' }, + }) + + expect(response.statusCode).toBe(400) + expect(response.json()).toEqual({ error: 'api_key_required' }) + expect(prismaMock.treeImmichConfig.upsert).not.toHaveBeenCalled() + await app.close() + }) + + it('rejects a non-http URL', 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: { apiUrl: '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: { apiUrl: 'http://immich.example.org', 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: { apiUrl: 'http://evil.example.org', apiKey: 'evil-key' }, + }) + expect(otherTree.statusCode).toBe(403) + + const anonymous = await app.inject({ + method: 'PUT', + url: '/trees/tree-1/immich/config', + payload: { apiUrl: 'http://immich.example.org', 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, apiUrl: 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 address 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: { apiUrl: 'http://internal-service.example.org:8080', 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: 'api_url_not_allowed' }) + expect(prismaMock.treeImmichConfig.upsert).not.toHaveBeenCalled() + expect(prismaMock.auditLog.create).not.toHaveBeenCalled() + await app.close() + }) + + it('accepts a listed address modulo a trailing slash', 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: { apiUrl: 'http://immich-tree-1.test/', apiKey: 'my-new-key' }, + }) + + expect(response.statusCode).toBe(200) + // Stockée telle quelle (le client retire le slash final à l'usage) : c'est la comparaison + // avec la liste qui se fait modulo le slash final, pas le stockage. + expect(response.json().config).toMatchObject({ configured: true, apiUrl: '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, apiUrl: 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 index bb84555..429c99b 100644 --- a/backend/test/immich-unconfigured.test.ts +++ b/backend/test/immich-unconfigured.test.ts @@ -2,8 +2,11 @@ import { randomUUID } from 'node:crypto' import type { FastifyInstance } from 'fastify' import { beforeAll, describe, expect, it, vi } from 'vitest' -// Immich désactivé : aucune requête vers l'instance ne doit partir, chaque route répond « non configuré ». -// Fichier à part : la configuration est lue au démarrage de l'application, impossible à changer à chaud. +// 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: { @@ -17,6 +20,9 @@ const { prismaMock } = vi.hoisted(() => ({ treeMembership: { findUnique: vi.fn(), }, + treeImmichConfig: { + findUnique: vi.fn(), + }, auditLog: { create: vi.fn(), }, @@ -32,9 +38,10 @@ vi.mock('../src/lib/prisma.js', () => ({ let createApp: () => FastifyInstance beforeAll(async () => { - delete process.env.IMMICH_ENABLED - delete process.env.IMMICH_API_URL - delete process.env.IMMICH_API_KEY + // 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' process.env.NODE_ENV = 'test' process.env.PORT = '4000' @@ -48,8 +55,8 @@ beforeAll(async () => { createApp = module.createApp }) -describe('Immich integration: disabled server', () => { - it('reports not configured and never calls Immich', async () => { +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( @@ -63,6 +70,8 @@ describe('Immich integration: disabled server', () => { 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) @@ -75,6 +84,16 @@ describe('Immich integration: disabled server', () => { 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, apiUrl: null, updatedAt: null }) + // Aucune instance autorisée par l'opérateur : le menu des adresses est vide. + expect(config.json().allowedApiUrls).toEqual([]) + const people = await app.inject({ method: 'GET', url: '/trees/tree-1/immich/people', @@ -83,6 +102,14 @@ describe('Immich integration: disabled server', () => { 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', @@ -92,8 +119,54 @@ describe('Immich integration: disabled server', () => { 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: { apiUrl: 'http://immich.example.org', apiKey: 'some-key' }, + }) + + expect(response.statusCode).toBe(400) + expect(response.json()).toEqual({ error: 'api_url_not_allowed' }) + await app.close() + }) }) diff --git a/backend/test/immich.test.ts b/backend/test/immich.test.ts index d18236f..1a75781 100644 --- a/backend/test/immich.test.ts +++ b/backend/test/immich.test.ts @@ -19,6 +19,9 @@ const { prismaMock } = vi.hoisted(() => ({ treeMembership: { findUnique: vi.fn(), }, + treeImmichConfig: { + findUnique: vi.fn(), + }, mediaItem: { aggregate: vi.fn(), }, @@ -37,6 +40,7 @@ vi.mock('../src/lib/prisma.js', () => ({ 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' @@ -97,9 +101,13 @@ beforeAll(async () => { 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://immich.test' - process.env.IMMICH_API_KEY = 'test-key' + 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' storageRoot = await mkdtemp(path.join(os.tmpdir(), 'parenthese-immich-')) process.env.MEDIA_STORAGE_PATH = storageRoot @@ -108,6 +116,11 @@ beforeAll(async () => { 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 @@ -139,6 +152,9 @@ beforeEach(async () => { 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.auditLog.create.mockResolvedValue({ id: 'audit-1' }) @@ -149,6 +165,34 @@ beforeEach(async () => { }) 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) diff --git a/frontend/src/api/immichApi.js b/frontend/src/api/immichApi.js index f045f41..bea85a4 100644 --- a/frontend/src/api/immichApi.js +++ b/frontend/src/api/immichApi.js @@ -1,7 +1,9 @@ import { API_BASE_URL, apiRequest } from './client.js' -// Reconnaissance des visages : l'API du backend parle à Immich et ne lui expose ni son -// adresse ni sa clé. Les erreurs distinguent non configuré / injoignable / clé refusée. +// 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 @@ -10,18 +12,44 @@ function withAuth(options = {}, token) { export function getImmichErrorMessage(error, t) { const code = error?.payload?.error || '' - if (code === 'immich_not_configured') return t('Immich n’est pas configuré sur le serveur.') + 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 === 'api_url_not_allowed') return t('Cette adresse 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é) et adresses autorisées par +// l'opérateur, 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, apiUrl: null, updatedAt: null }, + allowedApiUrls: Array.isArray(data?.allowedApiUrls) ? data.allowedApiUrls : [], + } +} + +export async function saveImmichConfig(treeId, { apiUrl, apiKey }, token) { + const data = await apiRequest(`/trees/${encodeURIComponent(treeId)}/immich/config`, withAuth({ + method: 'PUT', + body: JSON.stringify({ apiUrl, ...(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)) } diff --git a/frontend/src/components/AdminPanel.jsx b/frontend/src/components/AdminPanel.jsx index d4cab54..fa72858 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' @@ -51,6 +58,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 [immichAllowedUrls, setImmichAllowedUrls] = useState([]) + const [immichApiUrl, setImmichApiUrl] = 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 +82,22 @@ const AdminPanel = ({ setGedcomFile(null) setImportingGedcom(false) + setImmichConfig(null) + setImmichAllowedUrls([]) + setImmichApiUrl('') + setImmichApiKey('') + setImmichStatus(null) + fetchImmichConfig(treeId, authToken) + .then(({ config, allowedApiUrls }) => { + if (!active) return + setImmichConfig(config) + setImmichAllowedUrls(allowedApiUrls) + setImmichApiUrl(allowedApiUrls.includes(config?.apiUrl) ? config.apiUrl : '') + }) + .catch(() => { + // Configuration non chargée : l'onglet Immich affichera l'état inconnu + }) + fetchTreeSettings(treeId, authToken) .then((settings) => { if (!active || !settings) return @@ -253,6 +285,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 apiUrl = immichApiUrl + if (!apiUrl) { + setErrorMessage(t('Choisissez l’adresse de 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.apiUrl && immichConfig.apiUrl !== apiUrl) + 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, { apiUrl, apiKey }, authToken) + setImmichConfig(config || { configured: true, apiUrl, 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) 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, apiUrl: null, updatedAt: null }) + setImmichApiUrl('') + setImmichApiKey('') + setImmichStatus(null) + setSuccessMessage(t('Connexion Immich supprimée.')) + } catch (err) { + setErrorMessage(getImmichErrorMessage(err, t)) + } finally { + setImmichBusy(false) + } + } + if (!visible) return null return ( @@ -281,6 +388,7 @@ const AdminPanel = ({ + @@ -426,6 +534,95 @@ const AdminPanel = ({ )} + {section === 'immich' && ( +
+
+
+ {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 === null + ? t('État inconnu') + : immichConfig.configured + ? t('Configurée') + : t('Non configurée')} + + {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 && ( +
+ +
+ )} +
+ + {immichAllowedUrls.length === 0 ? ( +

+ {immichConfig === null + ? t('État inconnu') + : t('Aucune instance Immich n’est autorisée par l’opérateur de ce serveur. La reconnaissance des visages reste désactivée.')} +

+ ) : ( +
+
+ + +
+ +
+ + setImmichApiKey(event.target.value)} + placeholder={immichConfig?.configured + ? (immichConfig.apiUrl && immichApiUrl !== immichConfig.apiUrl + ? 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 && ( + + )} +
+
+ )} +
+ )} + {section === 'danger' && (
diff --git a/frontend/src/components/ImmichFacePanel.jsx b/frontend/src/components/ImmichFacePanel.jsx index 6e6d077..93a1813 100644 --- a/frontend/src/components/ImmichFacePanel.jsx +++ b/frontend/src/components/ImmichFacePanel.jsx @@ -129,6 +129,17 @@ const ImmichFacePanel = ({ person, treeId, token, onClose, onImmichChange }) => } } + // 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. + const currentAssociation = person.immichPersonId && ( +
+

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

+ +
+ ) + return createPortal(
@@ -144,22 +155,17 @@ const ImmichFacePanel = ({ person, treeId, token, onClose, onImmichChange }) =>
) : available === false ? (
+ {currentAssociation}

{unavailableReason === 'not_configured' - ? t('Immich n’est pas configuré sur le serveur.') + ? 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}
}
) : (
- {person.immichPersonId && ( -
-

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

- -
- )} + {currentAssociation}
{t('Personne à associer dans Immich')} diff --git a/frontend/src/i18n/en/compte.js b/frontend/src/i18n/en/compte.js index 82a85cf..e08ff1b 100644 --- a/frontend/src/i18n/en/compte.js +++ b/frontend/src/i18n/en/compte.js @@ -123,6 +123,30 @@ 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.", + // Onglet Immich (AdminPanel, connexion Immich propre à l'arbre) + 'Immich': 'Immich', + '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.', + 'État inconnu': 'Unknown state', + 'Configurée': 'Configured', + 'Non configurée': 'Not configured', + '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', + 'Adresse de l’instance Immich': 'Immich instance URL', + 'Choisir une instance…': 'Choose an instance…', + 'Choisissez l’adresse de l’instance Immich.': 'Choose the Immich instance address.', + 'Aucune instance Immich n’est autorisée par l’opérateur de ce serveur. La reconnaissance des visages reste désactivée.': 'No Immich instance has been authorized by this server’s operator. Face recognition stays disabled.', + '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 1e04029..fc08ad5 100644 --- a/frontend/src/i18n/en/fiche.js +++ b/frontend/src/i18n/en/fiche.js @@ -263,13 +263,16 @@ export default { 'Depuis Immich': 'From Immich', 'Visage Immich': 'Immich face', 'Reconnaissance des visages': 'Face recognition', - 'Immich n’est pas configuré sur le serveur.': 'Immich is not configured on the server.', + '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 adresse Immich n’est pas autorisée par l’opérateur du serveur.': 'This Immich address 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.', From 0bda88920d24cf2ca499d03bc1706adeeb214fcc Mon Sep 17 00:00:00 2001 From: Mistral Vibe Date: Tue, 13 Oct 2026 15:58:32 +0200 Subject: [PATCH 06/22] Immich : demander confirmation avant de remplacer un portrait existant MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit L'association remplaçait et supprimait le portrait en place sans rien demander. Le serveur refuse maintenant le remplacement d'un portrait existant (409 avatar_exists), quelle que soit son origine, tant que la requête ne porte pas replaceAvatar ; le panneau Immich transforme ce refus en demande de confirmation avant de rejouer la requête. Sans vignette Immich, l'association ne touche pas au portrait et aucune confirmation n'est demandée. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- backend/src/routes/immich.ts | 10 ++++ backend/test/immich.test.ts | 59 +++++++++++++++++++-- frontend/src/api/immichApi.js | 6 ++- frontend/src/components/ImmichFacePanel.css | 11 ++++ frontend/src/components/ImmichFacePanel.jsx | 44 ++++++++++++--- frontend/src/i18n/en/fiche.js | 4 ++ 6 files changed, 121 insertions(+), 13 deletions(-) diff --git a/backend/src/routes/immich.ts b/backend/src/routes/immich.ts index e9f6b33..c0dc964 100644 --- a/backend/src/routes/immich.ts +++ b/backend/src/routes/immich.ts @@ -30,6 +30,9 @@ const treeParamSchema = z.object({ id: 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({ @@ -385,6 +388,13 @@ export const immichRoutes: FastifyPluginAsync = async (app) => { 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> diff --git a/backend/test/immich.test.ts b/backend/test/immich.test.ts index 1a75781..3ab3062 100644 --- a/backend/test/immich.test.ts +++ b/backend/test/immich.test.ts @@ -357,7 +357,8 @@ describe('Immich integration: assign', () => { const app = createApp() const token = await createUserToken(app) - // Portrait manuel en place : il doit être supprimé une fois la base à jour. + // 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') @@ -369,7 +370,7 @@ describe('Immich integration: assign', () => { method: 'POST', url: '/trees/tree-1/immich/assign', headers: { authorization: `Bearer ${token}` }, - payload: { personId: 'person-1', immichPersonId }, + payload: { personId: 'person-1', immichPersonId, replaceAvatar: true }, }) expect(response.statusCode).toBe(200) @@ -399,10 +400,62 @@ describe('Immich integration: assign', () => { 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: '' }) @@ -601,7 +654,7 @@ describe('Immich integration: assign', () => { method: 'POST', url: '/trees/tree-1/immich/assign', headers: { authorization: `Bearer ${token}` }, - payload: { personId: 'person-tx', immichPersonId }, + payload: { personId: 'person-tx', immichPersonId, replaceAvatar: true }, }) expect(response.statusCode).toBe(500) diff --git a/frontend/src/api/immichApi.js b/frontend/src/api/immichApi.js index bea85a4..7253554 100644 --- a/frontend/src/api/immichApi.js +++ b/frontend/src/api/immichApi.js @@ -70,10 +70,12 @@ export async function fetchImmichThumbnail(treeId, immichPersonId, token) { return URL.createObjectURL(await response.blob()) } -export async function assignImmichPerson(treeId, personId, immichPersonId, token) { +export async function assignImmichPerson(treeId, personId, immichPersonId, token, { replaceAvatar = false } = {}) { return apiRequest(`/trees/${encodeURIComponent(treeId)}/immich/assign`, withAuth({ method: 'POST', - body: JSON.stringify({ personId, immichPersonId }), + // 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)) } diff --git a/frontend/src/components/ImmichFacePanel.css b/frontend/src/components/ImmichFacePanel.css index b5fa855..9706ac1 100644 --- a/frontend/src/components/ImmichFacePanel.css +++ b/frontend/src/components/ImmichFacePanel.css @@ -77,5 +77,16 @@ .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 index 93a1813..48b413f 100644 --- a/frontend/src/components/ImmichFacePanel.jsx +++ b/frontend/src/components/ImmichFacePanel.jsx @@ -25,6 +25,7 @@ const ImmichFacePanel = ({ person, treeId, token, onClose, onImmichChange }) => const [selected, setSelected] = useState(null) const [thumbnailUrl, setThumbnailUrl] = useState(null) const [actionLoading, setActionLoading] = useState(false) + const [confirmReplace, setConfirmReplace] = useState(false) const [error, setError] = useState('') const thumbnailRef = useRef(null) @@ -82,6 +83,7 @@ const ImmichFacePanel = ({ person, treeId, token, onClose, onImmichChange }) => const handleSelect = useCallback((immichPerson) => { setSelected(immichPerson) setError('') + setConfirmReplace(false) if (immichPerson?.hasThumbnail && immichPerson?.id) { loadThumbnail(immichPerson.id) } else { @@ -89,16 +91,22 @@ const ImmichFacePanel = ({ person, treeId, token, onClose, onImmichChange }) => } }, [loadThumbnail, releaseThumbnail]) - const handleAssign = useCallback(async () => { + const handleAssign = useCallback(async (replaceAvatar = false) => { if (!selected || actionLoading) return setActionLoading(true) setError('') try { - await assignImmichPerson(treeId, person.id, selected.id, token) + await assignImmichPerson(treeId, person.id, selected.id, token, { replaceAvatar }) onImmichChange?.(person.id) onClose?.() } catch (err) { - setError(getImmichErrorMessage(err, t)) + // 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) } @@ -210,12 +218,32 @@ const ImmichFacePanel = ({ person, treeId, token, onClose, onImmichChange }) => {error &&
{error}
} + {confirmReplace && ( +

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

+ )} +
- - + {confirmReplace ? ( + <> + + + + ) : ( + <> + + + + )}
)} diff --git a/frontend/src/i18n/en/fiche.js b/frontend/src/i18n/en/fiche.js index fc08ad5..8236c81 100644 --- a/frontend/src/i18n/en/fiche.js +++ b/frontend/src/i18n/en/fiche.js @@ -285,4 +285,8 @@ export default { 'Sans nom': 'Unnamed', 'Aucune sélection': 'No selection', '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', } From 8d36a08b11d594dc37ac96371e916af8a6b7f3e9 Mon Sep 17 00:00:00 2001 From: Mistral Vibe Date: Tue, 13 Oct 2026 17:39:23 +0200 Subject: [PATCH 07/22] =?UTF-8?q?Immich=20:=20retirer=20l'identifiant=20Im?= =?UTF-8?q?mich=20du=20graphe=20envoy=C3=A9=20aux=20visiteurs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - buildGraphPayload ne mappe plus immichPersonId ; test qu'il n'apparaît pas - le front ne propage plus le champ (graphAdapter, mockData et son test) - le panneau Immich propose le retrait d'association en permanence, sans lire le champ ; unassign sans association ne fait rien : pas d'écriture, pas d'entrée d'audit (test du no-op), et le bouton de la fiche garde un libellé fixe Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- backend/src/routes/immich.ts | 6 ++++++ backend/src/utils/graph-payload.ts | 2 -- backend/test/graph-payload.test.ts | 4 ++++ backend/test/immich.test.ts | 20 ++++++++++++++++++++ frontend/src/components/ImmichFacePanel.jsx | 16 +++++++++------- frontend/src/components/PersonCard.jsx | 2 +- frontend/src/data/mockData.js | 1 - frontend/src/data/mockData.test.js | 5 ----- frontend/src/i18n/en/fiche.js | 4 ++-- frontend/src/utils/graphAdapter.js | 1 - 10 files changed, 42 insertions(+), 19 deletions(-) diff --git a/backend/src/routes/immich.ts b/backend/src/routes/immich.ts index c0dc964..3ff6609 100644 --- a/backend/src/routes/immich.ts +++ b/backend/src/routes/immich.ts @@ -495,6 +495,12 @@ export const immichRoutes: FastifyPluginAsync = async (app) => { 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 = person.avatarPath !== null && path.basename(person.avatarPath).startsWith('immich-') diff --git a/backend/src/utils/graph-payload.ts b/backend/src/utils/graph-payload.ts index c66d297..ea847dc 100644 --- a/backend/src/utils/graph-payload.ts +++ b/backend/src/utils/graph-payload.ts @@ -17,7 +17,6 @@ export type GraphPayload = { avatarUrlPath: string | null sex: string | null notes: string | null - immichPersonId: string | null }> unions: Array<{ id: string @@ -91,7 +90,6 @@ export function buildGraphPayload( avatarUrlPath: person.avatarPath ? `/trees/${treeId}/persons/${person.id}/avatar` : null, sex: person.sex, notes: person.notes, - immichPersonId: person.immichPersonId, })), 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..8b1e272 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(), @@ -97,6 +98,9 @@ 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. + expect(graph.persons[0]).not.toHaveProperty('immichPersonId') + expect(graph.persons[1]).not.toHaveProperty('immichPersonId') 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.test.ts b/backend/test/immich.test.ts index 3ab3062..2cd94b4 100644 --- a/backend/test/immich.test.ts +++ b/backend/test/immich.test.ts @@ -737,6 +737,26 @@ describe('Immich integration: unassign', () => { 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) diff --git a/frontend/src/components/ImmichFacePanel.jsx b/frontend/src/components/ImmichFacePanel.jsx index 48b413f..b0e9e99 100644 --- a/frontend/src/components/ImmichFacePanel.jsx +++ b/frontend/src/components/ImmichFacePanel.jsx @@ -113,7 +113,7 @@ const ImmichFacePanel = ({ person, treeId, token, onClose, onImmichChange }) => }, [selected, actionLoading, treeId, person, token, onImmichChange, onClose]) const handleUnassign = useCallback(async () => { - if (!person.immichPersonId || actionLoading) return + if (actionLoading) return setActionLoading(true) setError('') try { @@ -137,11 +137,13 @@ const ImmichFacePanel = ({ person, treeId, token, onClose, onImmichChange }) => } } - // 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. - const currentAssociation = person.immichPersonId && ( + // Le retrait se propose toujours : le graphe ne dit plus qui est associé. Une association en + // place se retire aussi bien sans connexion : changer ou retirer le serveur Immich ne laisse + // jamais une ancienne image impossible à nettoyer manuellement. Sans association, le retrait + // ne fait rien côté serveur. + const unassignBlock = (
-

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

+

{t('{name} peut être détachée d’une personne Immich, même si Immich est injoignable.', { name: person.firstName || person.lastName })}

@@ -163,7 +165,7 @@ const ImmichFacePanel = ({ person, treeId, token, onClose, onImmichChange }) =>
) : available === false ? (
- {currentAssociation} + {unassignBlock}

{unavailableReason === 'not_configured' ? t('Immich n’est pas configuré pour cet arbre. Ses administrateurs le règlent dans Paramètres de l’arbre.') @@ -173,7 +175,7 @@ const ImmichFacePanel = ({ person, treeId, token, onClose, onImmichChange }) =>

) : (
- {currentAssociation} + {unassignBlock}
{t('Personne à associer dans Immich')} diff --git a/frontend/src/components/PersonCard.jsx b/frontend/src/components/PersonCard.jsx index a022e0d..fed617a 100644 --- a/frontend/src/components/PersonCard.jsx +++ b/frontend/src/components/PersonCard.jsx @@ -378,7 +378,7 @@ const PersonCard = ({ )} {treeId && onImmichChange && ( )}
diff --git a/frontend/src/data/mockData.js b/frontend/src/data/mockData.js index 0d0ea97..7a1084d 100644 --- a/frontend/src/data/mockData.js +++ b/frontend/src/data/mockData.js @@ -115,7 +115,6 @@ function mapRemotePersonToLocal(person, current = null) { profession: person?.profession || null, nationality: person?.nationality || null, photo: current?.photo || null, - immichPersonId: person?.immichPersonId ?? null, } } diff --git a/frontend/src/data/mockData.test.js b/frontend/src/data/mockData.test.js index 80a5104..91ee070 100644 --- a/frontend/src/data/mockData.test.js +++ b/frontend/src/data/mockData.test.js @@ -15,7 +15,6 @@ describe('loadGraphData avatar mapping', () => { deathDate: null, notes: null, avatarUrlPath: '/trees/t-1/persons/p-1/avatar', - immichPersonId: '123e4567-e89b-42d3-a456-426614174000', }, { id: 'p-2', @@ -25,7 +24,6 @@ describe('loadGraphData avatar mapping', () => { deathDate: null, notes: null, avatarUrlPath: null, - immichPersonId: null, }, ], unions: [], @@ -50,9 +48,6 @@ 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') - // Association Immich portée par la personne (null quand il n'y en a pas) - expect(getPersonById('p-1')?.immichPersonId).toBe('123e4567-e89b-42d3-a456-426614174000') - expect(getPersonById('p-2')?.immichPersonId).toBeNull() }) }) diff --git a/frontend/src/i18n/en/fiche.js b/frontend/src/i18n/en/fiche.js index 8236c81..f54142c 100644 --- a/frontend/src/i18n/en/fiche.js +++ b/frontend/src/i18n/en/fiche.js @@ -261,7 +261,6 @@ export default { 'Inconnu': 'Unknown', // Visages venus d'Immich (PersonCard, ImmichFacePanel, immichApi) 'Depuis Immich': 'From Immich', - '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.', @@ -275,7 +274,8 @@ export default { 'Cette adresse Immich n’est pas autorisée par l’opérateur du serveur.': 'This Immich address 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.', + '{name} peut être détachée d’une personne Immich, même si Immich est injoignable.': + '{name} can be detached from an Immich person, even when Immich cannot be reached.', 'Retirer l’association': 'Remove the link', 'Personne à associer dans Immich': 'Immich person to link', 'Rechercher par nom': 'Search by name', diff --git a/frontend/src/utils/graphAdapter.js b/frontend/src/utils/graphAdapter.js index f0f716f..7fb09ca 100644 --- a/frontend/src/utils/graphAdapter.js +++ b/frontend/src/utils/graphAdapter.js @@ -57,7 +57,6 @@ export function adaptGraphForGalaxy(apiGraph, _treeId) { birthDate: p.birthDate, deathDate: p.deathDate, photo: p.avatarUrlPath ? `/api${p.avatarUrlPath}` : null, - immichPersonId: p.immichPersonId || null, frameType: 'round', // Default })) From 310f2fb597ed4bbabdc13c2ee05969be9c650e83 Mon Sep 17 00:00:00 2001 From: Mistral Vibe Date: Tue, 13 Oct 2026 17:47:37 +0200 Subject: [PATCH 08/22] Immich : publier l'origine du portrait dans le graphe, pas l'identifiant MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - avatarFromImmich (fichier préfixé « immich- ») remplace immichPersonId côté front : le panneau ne propose le retrait que si le portrait vient d'Immich, et le bouton de la fiche retrouve son libellé distinctif - helper isImmichAvatarPath partagé entre le payload du graphe et la route unassign, qui testaient le préfixe chacun de son côté - tests : origine du portrait dans le payload (vrai/faux/null) Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- backend/src/lib/media-files.ts | 6 ++++++ backend/src/routes/immich.ts | 4 ++-- backend/src/utils/graph-payload.ts | 3 +++ backend/test/graph-payload.test.ts | 23 +++++++++++++++++++++ frontend/src/components/ImmichFacePanel.jsx | 13 ++++++------ frontend/src/components/PersonCard.jsx | 2 +- frontend/src/data/mockData.js | 1 + frontend/src/data/mockData.test.js | 5 +++++ frontend/src/i18n/en/fiche.js | 4 ++-- frontend/src/utils/graphAdapter.js | 1 + 10 files changed, 50 insertions(+), 12 deletions(-) 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 index 3ff6609..024ed46 100644 --- a/backend/src/routes/immich.ts +++ b/backend/src/routes/immich.ts @@ -16,7 +16,7 @@ import { type ImmichPersonSummary, } from '../lib/immich.js' import { encryptImmichApiKey } from '../lib/immich-secret.js' -import { InvalidMediaError, removeStoredFile, sniffMimeType } from '../lib/media-files.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 @@ -503,7 +503,7 @@ export const immichRoutes: FastifyPluginAsync = async (app) => { // 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 = person.avatarPath !== null && path.basename(person.avatarPath).startsWith('immich-') + const avatarFromImmich = isImmichAvatarPath(person.avatarPath) const updateData: { immichPersonId: null 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 8b1e272..bb18e36 100644 --- a/backend/test/graph-payload.test.ts +++ b/backend/test/graph-payload.test.ts @@ -42,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, [ { @@ -99,8 +117,13 @@ describe('buildGraphPayload', () => { 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/frontend/src/components/ImmichFacePanel.jsx b/frontend/src/components/ImmichFacePanel.jsx index b0e9e99..e029727 100644 --- a/frontend/src/components/ImmichFacePanel.jsx +++ b/frontend/src/components/ImmichFacePanel.jsx @@ -113,7 +113,7 @@ const ImmichFacePanel = ({ person, treeId, token, onClose, onImmichChange }) => }, [selected, actionLoading, treeId, person, token, onImmichChange, onClose]) const handleUnassign = useCallback(async () => { - if (actionLoading) return + if (!person.avatarFromImmich || actionLoading) return setActionLoading(true) setError('') try { @@ -137,13 +137,12 @@ const ImmichFacePanel = ({ person, treeId, token, onClose, onImmichChange }) => } } - // Le retrait se propose toujours : le graphe ne dit plus qui est associé. Une association en - // place se retire aussi bien sans connexion : changer ou retirer le serveur Immich ne laisse - // jamais une ancienne image impossible à nettoyer manuellement. Sans association, le retrait - // ne fait rien côté serveur. - const unassignBlock = ( + // 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} peut être détachée d’une personne Immich, même si Immich est injoignable.', { name: person.firstName || person.lastName })}

+

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

diff --git a/frontend/src/components/PersonCard.jsx b/frontend/src/components/PersonCard.jsx index fed617a..3642112 100644 --- a/frontend/src/components/PersonCard.jsx +++ b/frontend/src/components/PersonCard.jsx @@ -378,7 +378,7 @@ const PersonCard = ({ )} {treeId && onImmichChange && ( )}
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/fiche.js b/frontend/src/i18n/en/fiche.js index f54142c..8236c81 100644 --- a/frontend/src/i18n/en/fiche.js +++ b/frontend/src/i18n/en/fiche.js @@ -261,6 +261,7 @@ export default { 'Inconnu': 'Unknown', // Visages venus d'Immich (PersonCard, ImmichFacePanel, immichApi) 'Depuis Immich': 'From Immich', + '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.', @@ -274,8 +275,7 @@ export default { 'Cette adresse Immich n’est pas autorisée par l’opérateur du serveur.': 'This Immich address 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} peut être détachée d’une personne Immich, même si Immich est injoignable.': - '{name} can be detached from an Immich person, even when Immich cannot be reached.', + '{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', 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 })) From 8803463ce42aae42688b16950fe3bedc1655a2a2 Mon Sep 17 00:00:00 2001 From: Mistral Vibe Date: Tue, 13 Oct 2026 18:43:16 +0200 Subject: [PATCH 09/22] =?UTF-8?q?Immich=20:=20le=20choix=20de=20la=20sourc?= =?UTF-8?q?e=20passe=20par=20un=20menu=20sur=20=C2=AB=20Changer=20=C2=BB?= =?UTF-8?q?=20;=20=C2=AB=20Retirer=20=C2=BB=20d=C3=A9sassigne=20les=20visa?= =?UTF-8?q?ges=20Immich?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - PersonCard : le lien « Depuis Immich » empilé sous « Changer »/« Retirer » disparaît ; « Changer »/« Ajouter une photo » ouvre un menu contextuel (portail, pz-menu) proposant « Depuis un fichier » ou « Depuis Immich », seulement quand l'arbre a une connexion Immich ou que la personne garde un portrait venu d'Immich (sinon sélecteur direct). La connexion se lit via GET /trees/:id/immich/config à l'ouverture en édition. - « Retirer » transmet l'origine du portrait ; App route vers unassignImmichPerson quand il vient d'Immich (portrait + association retirés ensemble) au lieu de la suppression seule qui laissait une association pendante. Erreurs du chemin Immich mappées par getImmichErrorMessage. - i18n en : « Depuis un fichier », « Source du portrait ». Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- frontend/src/App.jsx | 19 ++++-- frontend/src/components/PersonCard.css | 3 + frontend/src/components/PersonCard.jsx | 89 ++++++++++++++++++++++++-- frontend/src/i18n/en/fiche.js | 2 + 4 files changed, 102 insertions(+), 11 deletions(-) diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index c1e8586..3af018d 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' @@ -1540,18 +1541,28 @@ function App() { await refreshTreeAndKeepSelection(personId, { relayout: false, avatarCacheBust: Date.now() }) }, [refreshTreeAndKeepSelection]) - const handlePersonAvatarDelete = useCallback(async (personId) => { + 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]) 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 3642112..880ccc3 100644 --- a/frontend/src/components/PersonCard.jsx +++ b/frontend/src/components/PersonCard.jsx @@ -1,6 +1,8 @@ import { useState, useEffect, useRef, forwardRef } from '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' @@ -60,6 +62,13 @@ const PersonCard = ({ 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 @@ -75,8 +84,48 @@ 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. + useEffect(() => { + let cancelled = false + setImmichConfigured(null) + setShowSourceMenu(false) + if (!editMode || !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, 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 = 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) { @@ -368,19 +417,27 @@ const PersonCard = ({ )} {editMode && onAvatarUpload && (
- {person.photo && ( - )} - {treeId && onImmichChange && ( - - )}
)}
@@ -701,6 +758,24 @@ const PersonCard = ({ )} + {/* ── Choix de la source du portrait (menu contextuel) ── */} + {showSourceMenu && ( + createPortal( + <> +
setShowSourceMenu(false)} /> +
+ + +
+ , + document.body, + ) + )} + {/* ── Association d'un visage Immich (modale) ── */} {showImmichPanel && treeId && ( Date: Tue, 13 Oct 2026 19:08:52 +0200 Subject: [PATCH 10/22] =?UTF-8?q?Immich=20:=20un=20portrait=20d=C3=A9pos?= =?UTF-8?q?=C3=A9=20=C3=A0=20la=20main=20remplace=20aussi=20le=20lien=20Im?= =?UTF-8?q?mich?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit POST /trees/:id/persons/:personId/avatar lit immichPersonId de la personne et le remet à null quand une association existe ; l'entrée d'audit person_avatar_updated trace le retrait via payloadJson immichLinkRemoved. Sans cela, l'association survivait invisible en base après remplacement du portrait par un fichier. Test : l'envoi d'un fichier sur un portrait Immich efface l'association (échouait avant ce fix : immichPersonId absent de l'update) ; sans association, le champ n'est pas touché. Generated by Mistral Vibe. Co-Authored-By: Mistral Vibe --- backend/src/routes/media.ts | 6 ++++ backend/test/immich.test.ts | 65 +++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) diff --git a/backend/src/routes/media.ts b/backend/src/routes/media.ts index dde0c94..0e07c57 100644 --- a/backend/src/routes/media.ts +++ b/backend/src/routes/media.ts @@ -494,6 +494,7 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => { select: { id: true, avatarPath: true, + immichPersonId: true, }, }) @@ -554,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 } : {}), }, }) @@ -568,6 +573,7 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => { action: 'person_avatar_updated', entityType: 'person', entityId: params.data.personId, + ...(person.immichPersonId ? { payloadJson: { immichLinkRemoved: true } } : {}), }, }) diff --git a/backend/test/immich.test.ts b/backend/test/immich.test.ts index 2cd94b4..0969d82 100644 --- a/backend/test/immich.test.ts +++ b/backend/test/immich.test.ts @@ -15,6 +15,7 @@ const { prismaMock } = vi.hoisted(() => ({ person: { findFirst: vi.fn(), update: vi.fn(), + updateMany: vi.fn(), }, treeMembership: { findUnique: vi.fn(), @@ -157,6 +158,7 @@ beforeEach(async () => { 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 } }) @@ -787,3 +789,66 @@ describe('Immich integration: unassign', () => { 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() + }) +}) From 44dd203069d621d143983791412ae9cd4aaf1559 Mon Sep 17 00:00:00 2001 From: IliesAllali Date: Fri, 16 Oct 2026 18:04:50 +0200 Subject: [PATCH 11/22] =?UTF-8?q?Immich=20:=20ne=20jamais=20suivre=20une?= =?UTF-8?q?=20redirection=20avec=20la=20cl=C3=A9=20d'API?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fetch suivait les redirections par défaut : une instance autorisée qui répond 3xx pouvait recevoir x-api-key sur une autre adresse. Les appels passent en redirect: 'error' (remontée en immich_unreachable), avec un test qui le prouve. Co-Authored-By: Claude Opus 5.5 --- backend/src/lib/immich.ts | 2 ++ backend/test/immich.test.ts | 30 ++++++++++++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/backend/src/lib/immich.ts b/backend/src/lib/immich.ts index bca7887..2b00bbb 100644 --- a/backend/src/lib/immich.ts +++ b/backend/src/lib/immich.ts @@ -76,6 +76,8 @@ export class ImmichClient { 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. diff --git a/backend/test/immich.test.ts b/backend/test/immich.test.ts index 0969d82..0b53c56 100644 --- a/backend/test/immich.test.ts +++ b/backend/test/immich.test.ts @@ -852,3 +852,33 @@ describe('Immich integration: manual avatar replacing an Immich portrait', () => 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() + }) +}) From 63b9761ec47520a78a36de7ac5c1d76aca07a631 Mon Sep 17 00:00:00 2001 From: IliesAllali Date: Fri, 16 Oct 2026 18:05:50 +0200 Subject: [PATCH 12/22] Immich : garder le chemin de l'instance, comparer origine et chemin MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit new URL(chemin, base) effaçait le sous-chemin d'une instance derrière un proxy (https://hote/immich devenait https://hote/api/...). L'adresse se concatène désormais. Une adresse avec identifiants, requête ou fragment est refusée, et le client reçoit l'adresse autorisée normalisée, jamais la valeur brute de la base. Tests : sous-chemin, domaine préfixe, userinfo. Co-Authored-By: Claude Opus 5.5 --- backend/src/lib/immich.ts | 12 ++++++++++-- backend/test/immich.test.ts | 38 ++++++++++++++++++++++++++++++++++++- 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/backend/src/lib/immich.ts b/backend/src/lib/immich.ts index 2b00bbb..a6bcb82 100644 --- a/backend/src/lib/immich.ts +++ b/backend/src/lib/immich.ts @@ -65,8 +65,10 @@ export class ImmichClient { 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). private buildUrl(path: string): string { - return new URL(path, `${this.apiUrl}/`).toString() + return `${this.apiUrl}${path}` } private async fetch(path: string): Promise { @@ -170,6 +172,11 @@ export function normalizeImmichApiUrl(value: string): string | null { 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 @@ -233,5 +240,6 @@ export async function getTreeImmichClient(prisma: PrismaClient, treeId: string): return null } - return new ImmichClient(config.apiUrl, apiKey) + // Le client reçoit l'adresse autorisée, normalisée : pas celle, brute, de la base. + return new ImmichClient(normalizeImmichApiUrl(config.apiUrl)!, apiKey) } diff --git a/backend/test/immich.test.ts b/backend/test/immich.test.ts index 0b53c56..e96ab15 100644 --- a/backend/test/immich.test.ts +++ b/backend/test/immich.test.ts @@ -108,7 +108,7 @@ beforeAll(async () => { 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' + process.env.IMMICH_ALLOWED_API_URLS = 'http://immich.test,http://immich.test/immich' storageRoot = await mkdtemp(path.join(os.tmpdir(), 'parenthese-immich-')) process.env.MEDIA_STORAGE_PATH = storageRoot @@ -882,3 +882,39 @@ describe('Immich integration: redirections', () => { 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() + }) +}) From fbcac3afd418e574b8c74569a79a6bd929f15458 Mon Sep 17 00:00:00 2001 From: IliesAllali Date: Fri, 16 Oct 2026 18:05:51 +0200 Subject: [PATCH 13/22] =?UTF-8?q?Tests=20Immich=20:=20liste=20d'instances?= =?UTF-8?q?=20vide=20explicite,=20ind=C3=A9pendante=20du=20.env=20local?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Le test « aucune instance autorisée » héritait de IMMICH_ALLOWED_API_URLS du backend/.env de développement et échouait sur une machine qui le renseigne. Co-Authored-By: Claude Opus 5.5 --- backend/test/immich-unconfigured.test.ts | 2 ++ 1 file changed, 2 insertions(+) diff --git a/backend/test/immich-unconfigured.test.ts b/backend/test/immich-unconfigured.test.ts index 429c99b..85e15c2 100644 --- a/backend/test/immich-unconfigured.test.ts +++ b/backend/test/immich-unconfigured.test.ts @@ -42,6 +42,8 @@ beforeAll(async () => { 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' From 265b3b30a0a0b62c50095b452b182c35de4293f0 Mon Sep 17 00:00:00 2001 From: IliesAllali Date: Fri, 16 Oct 2026 18:08:54 +0200 Subject: [PATCH 14/22] Immich : les instances se choisissent par leur nom, jamais par leur adresse MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit L'API ne renvoie plus les adresses brutes d'Immich à un administrateur d'arbre : la liste IMMICH_ALLOWED_API_URLS devient des instances nommées (« Libellé=https://adresse », libellé facultatif, nom d'hôte par défaut). Chaque instance a un identifiant opaque dérivé de son adresse, donc stable même si l'opérateur réordonne la liste. Le PUT accepte cet identifiant et stocke l'adresse canonique de la liste. Deux instances au même nom d'hôte sans libellé sont refusées au démarrage avec un avertissement. Les variables d'exemple documentent le format, la liste reste compatible avec les adresses seules. Co-Authored-By: Claude Opus 5.5 --- .env.example | 15 +++--- backend/.env.example | 5 +- backend/.env.production.example | 5 +- backend/src/lib/immich.ts | 58 ++++++++++++++------ backend/src/routes/immich.ts | 52 +++++++++--------- backend/test/immich-config.test.ts | 68 +++++++++++++----------- backend/test/immich-unconfigured.test.ts | 8 +-- backend/test/immich.test.ts | 2 +- frontend/src/api/immichApi.js | 14 ++--- frontend/src/components/AdminPanel.jsx | 46 ++++++++-------- frontend/src/i18n/en/compte.js | 4 +- frontend/src/i18n/en/fiche.js | 2 +- 12 files changed, 158 insertions(+), 121 deletions(-) diff --git a/.env.example b/.env.example index 8ce44dc..4c005af 100644 --- a/.env.example +++ b/.env.example @@ -35,12 +35,15 @@ CORS_ORIGIN=http://localhost # 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. Les -# administrateurs de chaque arbre choisissent la leur dans cette liste et donnent -# leur propre clé d'API (créée dans Immich, Paramètres > Clés d'API) ; la clé est -# chiffrée en base. 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=http://immich.example.org:2283,https://immich.example.org +# 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 diff --git a/backend/.env.example b/backend/.env.example index 4527662..02584f4 100644 --- a/backend/.env.example +++ b/backend/.env.example @@ -7,6 +7,7 @@ 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. Les administrateurs de chaque arbre choisissent la leur dans cette liste et donnent -# leur propre clé d'API. Sans cette liste, la fonction reste éteinte. +# 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 d82156b..239b528 100644 --- a/backend/.env.production.example +++ b/backend/.env.production.example @@ -25,6 +25,7 @@ CORS_ORIGIN="https://arbre.example.org" MEDIA_STORAGE_PATH="/var/lib/parenthese/media" # Reconnaissance des visages : instances Immich autorisées sur ce serveur, séparées par des -# virgules. Les administrateurs de chaque arbre choisissent la leur dans cette liste et donnent -# leur propre clé d'API. Sans cette liste, la fonction reste éteinte. +# 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/src/lib/immich.ts b/backend/src/lib/immich.ts index a6bcb82..71ebfaf 100644 --- a/backend/src/lib/immich.ts +++ b/backend/src/lib/immich.ts @@ -1,3 +1,5 @@ +import { createHash } from 'node:crypto' + import type { PrismaClient } from '@prisma/client' import { env } from '../config/env.js' @@ -183,39 +185,63 @@ export function normalizeImmichApiUrl(value: string): string | null { } } -let allowedApiUrlsCache: string[] | undefined +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. Les entrées invalides sont -// ignorées avec un avertissement. -export function getImmichAllowedApiUrls(): string[] { - if (allowedApiUrlsCache !== undefined) { - return allowedApiUrlsCache +// 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 urls: string[] = [] + const instances: ImmichInstance[] = [] for (const entry of env.IMMICH_ALLOWED_API_URLS.split(',')) { const trimmed = entry.trim() if (!trimmed) { continue } - const normalized = normalizeImmichApiUrl(trimmed) - if (!normalized) { + 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 (!urls.includes(normalized)) { - urls.push(normalized) + 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 }) } - allowedApiUrlsCache = urls - return urls + 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 { - const normalized = normalizeImmichApiUrl(value) - return normalized !== null && getImmichAllowedApiUrls().includes(normalized) + return getImmichInstanceByApiUrl(value) !== undefined } // Connexion Immich d'un arbre : résolue par arbre, côté serveur, à chaque requête. Pas de client @@ -241,5 +267,5 @@ export async function getTreeImmichClient(prisma: PrismaClient, treeId: string): } // Le client reçoit l'adresse autorisée, normalisée : pas celle, brute, de la base. - return new ImmichClient(normalizeImmichApiUrl(config.apiUrl)!, apiKey) + return new ImmichClient(getImmichInstanceByApiUrl(config.apiUrl)!.apiUrl, apiKey) } diff --git a/backend/src/routes/immich.ts b/backend/src/routes/immich.ts index 024ed46..1ac3894 100644 --- a/backend/src/routes/immich.ts +++ b/backend/src/routes/immich.ts @@ -5,9 +5,9 @@ import { mkdir, writeFile } from 'node:fs/promises' import { z } from 'zod' import { - getImmichAllowedApiUrls, + getImmichInstanceByApiUrl, + getImmichInstances, getTreeImmichClient, - isImmichApiUrlAllowed, isImmichPersonId, normalizeImmichApiUrl, ImmichAuthError, @@ -44,14 +44,12 @@ const thumbnailParamSchema = z.object({ immichPersonId: z.string().refine(isImmichPersonId, 'invalid_immich_person_id'), }) -// Connexion Immich d'un arbre : adresse choisie parmi celles autorisées par l'opérateur du -// serveur (IMMICH_ALLOWED_API_URLS). La clé se joint à la mise à jour ou, si le champ reste -// vide, celle en place est conservée — jamais relue par le front. +// 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({ - apiUrl: z - .string() - .url() - .refine((value) => value.startsWith('http://') || value.startsWith('https://'), 'invalid_api_url'), + instanceId: z.string().regex(/^[0-9a-f]{16}$/, 'invalid_instance_id'), apiKey: z.string().min(1).max(512).optional(), }) @@ -71,13 +69,15 @@ function replyImmichError(request: FastifyRequest, reply: FastifyReply, error: u 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é. Une -// adresse sortie de la liste de l'opérateur vaut « non configuré » : la connexion est inerte. +// 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. function immichConfigSummary(config: { apiUrl: string; updatedAt: Date } | null) { - if (!config || !isImmichApiUrlAllowed(config.apiUrl)) { - return { configured: false, apiUrl: null, updatedAt: null } + const instance = config ? getImmichInstanceByApiUrl(config.apiUrl) : undefined + if (!config || !instance) { + return { configured: false, instanceId: null, label: null, updatedAt: null } } - return { configured: true, apiUrl: config.apiUrl, updatedAt: config.updatedAt } + return { configured: true, instanceId: instance.id, label: instance.label, updatedAt: config.updatedAt } } // Portraits venus d'Immich : même nommage que les envois manuels (« avatar- »), avec le @@ -112,8 +112,8 @@ export const immichRoutes: FastifyPluginAsync = async (app) => { return reply.send({ config: immichConfigSummary(config), - // Les administrateurs choisissent parmi cette liste : le front en fait un menu, pas un champ libre. - allowedApiUrls: getImmichAllowedApiUrls(), + // Les administrateurs choisissent parmi ces instances : le front en fait un menu, pas un champ libre. + instances: getImmichInstances().map(({ id, label }) => ({ id, label })), }) }) @@ -135,10 +135,12 @@ export const immichRoutes: FastifyPluginAsync = async (app) => { return reply.code(403).send({ error: 'forbidden' }) } - // L'adresse doit faire partie de la liste de l'opérateur : le serveur ne devient jamais - // un proxy vers un service interne choisi librement (SSRF). - if (!isImmichApiUrlAllowed(payload.data.apiUrl)) { - return reply.code(400).send({ error: 'api_url_not_allowed' }) + // 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 @@ -156,7 +158,7 @@ export const immichRoutes: FastifyPluginAsync = async (app) => { // 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) !== normalizeImmichApiUrl(payload.data.apiUrl)) { + && normalizeImmichApiUrl(existing.apiUrl) !== instance.apiUrl) { return reply.code(400).send({ error: 'api_key_required' }) } @@ -166,8 +168,8 @@ export const immichRoutes: FastifyPluginAsync = async (app) => { const config = await app.prisma.treeImmichConfig.upsert({ where: { treeId }, - create: { treeId, apiUrl: payload.data.apiUrl, apiKeyEnc }, - update: { apiUrl: payload.data.apiUrl, apiKeyEnc }, + create: { treeId, apiUrl: instance.apiUrl, apiKeyEnc }, + update: { apiUrl: instance.apiUrl, apiKeyEnc }, select: { apiUrl: true, updatedAt: true }, }) @@ -180,7 +182,7 @@ export const immichRoutes: FastifyPluginAsync = async (app) => { action: 'immich_config_updated', entityType: 'tree_immich_config', entityId: treeId, - payloadJson: { apiUrl: payload.data.apiUrl, apiKeyChanged: Boolean(payload.data.apiKey) }, + payloadJson: { instanceId: instance.id, apiKeyChanged: Boolean(payload.data.apiKey) }, }, }) @@ -218,7 +220,7 @@ export const immichRoutes: FastifyPluginAsync = async (app) => { }) } - return reply.send({ config: { configured: false, apiUrl: null, updatedAt: null } }) + return reply.send({ config: { configured: false, instanceId: null, label: null, updatedAt: null } }) }) app.get('/trees/:id/immich/status', async (request, reply) => { diff --git a/backend/test/immich-config.test.ts b/backend/test/immich-config.test.ts index e213cf0..0a5a7ed 100644 --- a/backend/test/immich-config.test.ts +++ b/backend/test/immich-config.test.ts @@ -61,7 +61,7 @@ beforeAll(async () => { 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,http://immich.example.org:2283,http://immich.example.org,http://immich-moved.example.org' + 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') @@ -132,8 +132,10 @@ describe('Immich configuration: read', () => { expect(response.statusCode).toBe(200) const body = response.json() - expect(body.config).toMatchObject({ configured: true, apiUrl: 'http://immich-tree-1.test' }) + 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) @@ -153,14 +155,15 @@ describe('Immich configuration: read', () => { // 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, apiUrl: null, updatedAt: null }) - expect(response.json().allowedApiUrls).toEqual([ - 'http://immich-tree-1.test', - 'http://immich-tree-2.test', - 'http://immich.example.org:2283', - 'http://immich.example.org', - 'http://immich-moved.example.org', + expect(response.json().config).toEqual({ configured: 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() }) }) @@ -175,11 +178,13 @@ describe('Immich configuration: write', () => { method: 'PUT', url: '/trees/tree-1/immich/config', headers: { authorization: `Bearer ${token}` }, - payload: { apiUrl: 'http://immich.example.org:2283', apiKey: 'my-new-key' }, + payload: { instanceId: '6fc8e421ad9b5371', apiKey: 'my-new-key' }, }) expect(response.statusCode).toBe(200) - expect(response.json().config).toMatchObject({ configured: true, apiUrl: 'http://immich.example.org:2283' }) + 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' }) @@ -195,7 +200,7 @@ describe('Immich configuration: write', () => { action: 'immich_config_updated', entityType: 'tree_immich_config', entityId: 'tree-1', - payloadJson: { apiUrl: 'http://immich.example.org:2283', apiKeyChanged: true }, + payloadJson: { instanceId: '6fc8e421ad9b5371', apiKeyChanged: true }, }, }) @@ -211,18 +216,18 @@ describe('Immich configuration: write', () => { method: 'PUT', url: '/trees/tree-1/immich/config', headers: { authorization: `Bearer ${token}` }, - payload: { apiUrl: 'http://immich-tree-1.test' }, + payload: { instanceId: 'c2ec51abd0edebf3' }, }) expect(response.statusCode).toBe(200) - expect(response.json().config.apiUrl).toBe('http://immich-tree-1.test') + 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({ - apiUrl: 'http://immich-tree-1.test', + instanceId: 'c2ec51abd0edebf3', apiKeyChanged: false, }) await app.close() @@ -236,7 +241,7 @@ describe('Immich configuration: write', () => { method: 'PUT', url: '/trees/tree-1/immich/config', headers: { authorization: `Bearer ${token}` }, - payload: { apiUrl: 'http://immich-moved.example.org' }, + payload: { instanceId: '2d46a51941003fcd' }, }) // La clé de l'ancienne instance ne vaut rien pour la nouvelle, et ne lui est jamais @@ -256,7 +261,7 @@ describe('Immich configuration: write', () => { method: 'PUT', url: '/trees/tree-1/immich/config', headers: { authorization: `Bearer ${token}` }, - payload: { apiUrl: 'http://immich.example.org' }, + payload: { instanceId: '2c47e4ca85342f88' }, }) expect(response.statusCode).toBe(400) @@ -265,7 +270,7 @@ describe('Immich configuration: write', () => { await app.close() }) - it('rejects a non-http URL', async () => { + it('rejects an identifier that is not an instance id', async () => { const app = createApp() const token = await createUserToken(app) @@ -273,7 +278,7 @@ describe('Immich configuration: write', () => { method: 'PUT', url: '/trees/tree-1/immich/config', headers: { authorization: `Bearer ${token}` }, - payload: { apiUrl: 'ftp://immich.example.org', apiKey: 'my-new-key' }, + payload: { instanceId: 'ftp://immich.example.org', apiKey: 'my-new-key' }, }) expect(response.statusCode).toBe(400) @@ -291,7 +296,7 @@ describe('Immich configuration: write', () => { method: 'PUT', url: '/trees/tree-1/immich/config', headers: { authorization: `Bearer ${memberToken}` }, - payload: { apiUrl: 'http://immich.example.org', apiKey: 'stolen-key' }, + payload: { instanceId: '2c47e4ca85342f88', apiKey: 'stolen-key' }, }) expect(member.statusCode).toBe(403) @@ -300,14 +305,14 @@ describe('Immich configuration: write', () => { method: 'PUT', url: '/trees/tree-2/immich/config', headers: { authorization: `Bearer ${ownerToken}` }, - payload: { apiUrl: 'http://evil.example.org', apiKey: 'evil-key' }, + 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: { apiUrl: 'http://immich.example.org', apiKey: 'key' }, + payload: { instanceId: '2c47e4ca85342f88', apiKey: 'key' }, }) expect(anonymous.statusCode).toBe(401) @@ -329,7 +334,7 @@ describe('Immich configuration: removal', () => { }) expect(response.statusCode).toBe(200) - expect(response.json().config).toEqual({ configured: false, apiUrl: null, updatedAt: null }) + expect(response.json().config).toEqual({ configured: false, instanceId: null, label: null, updatedAt: null }) expect(prismaMock.treeImmichConfig.deleteMany).toHaveBeenCalledWith({ where: { treeId: 'tree-1' } }) expect(prismaMock.auditLog.create).toHaveBeenCalledWith({ data: { @@ -423,7 +428,7 @@ describe('Immich credentials: tree isolation', () => { }) describe('Immich configuration: operator allowlist', () => { - it('rejects an address outside the list and changes nothing', async () => { + it('rejects an instance outside the list and changes nothing', async () => { const app = createApp() const token = await createUserToken(app) @@ -431,18 +436,18 @@ describe('Immich configuration: operator allowlist', () => { method: 'PUT', url: '/trees/tree-1/immich/config', headers: { authorization: `Bearer ${token}` }, - payload: { apiUrl: 'http://internal-service.example.org:8080', apiKey: 'stolen-key' }, + 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: 'api_url_not_allowed' }) + expect(response.json()).toEqual({ error: 'instance_not_allowed' }) expect(prismaMock.treeImmichConfig.upsert).not.toHaveBeenCalled() expect(prismaMock.auditLog.create).not.toHaveBeenCalled() await app.close() }) - it('accepts a listed address modulo a trailing slash', async () => { + it('stores the canonical address of the instance chosen by its identifier', async () => { const app = createApp() const token = await createUserToken(app) @@ -450,13 +455,12 @@ describe('Immich configuration: operator allowlist', () => { method: 'PUT', url: '/trees/tree-1/immich/config', headers: { authorization: `Bearer ${token}` }, - payload: { apiUrl: 'http://immich-tree-1.test/', apiKey: 'my-new-key' }, + payload: { instanceId: 'c2ec51abd0edebf3', apiKey: 'my-new-key' }, }) expect(response.statusCode).toBe(200) - // Stockée telle quelle (le client retire le slash final à l'usage) : c'est la comparaison - // avec la liste qui se fait modulo le slash final, pas le stockage. - expect(response.json().config).toMatchObject({ configured: true, apiUrl: 'http://immich-tree-1.test/' }) + 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() }) @@ -476,7 +480,7 @@ describe('Immich configuration: operator allowlist', () => { headers: { authorization: `Bearer ${token}` }, }) expect(config.statusCode).toBe(200) - expect(config.json().config).toEqual({ configured: false, apiUrl: null, updatedAt: null }) + expect(config.json().config).toEqual({ configured: false, instanceId: null, label: null, updatedAt: null }) const status = await app.inject({ method: 'GET', diff --git a/backend/test/immich-unconfigured.test.ts b/backend/test/immich-unconfigured.test.ts index 85e15c2..2a0d970 100644 --- a/backend/test/immich-unconfigured.test.ts +++ b/backend/test/immich-unconfigured.test.ts @@ -92,9 +92,9 @@ describe('Immich integration: tree without configuration', () => { headers: { authorization: `Bearer ${token}` }, }) expect(config.statusCode).toBe(200) - expect(config.json().config).toEqual({ configured: false, apiUrl: null, updatedAt: null }) + expect(config.json().config).toEqual({ configured: false, instanceId: null, label: null, updatedAt: null }) // Aucune instance autorisée par l'opérateur : le menu des adresses est vide. - expect(config.json().allowedApiUrls).toEqual([]) + expect(config.json().instances).toEqual([]) const people = await app.inject({ method: 'GET', @@ -164,11 +164,11 @@ describe('Immich integration: tree without configuration', () => { method: 'PUT', url: '/trees/tree-1/immich/config', headers: { authorization: `Bearer ${token}` }, - payload: { apiUrl: 'http://immich.example.org', apiKey: 'some-key' }, + payload: { instanceId: '2c47e4ca85342f88', apiKey: 'some-key' }, }) expect(response.statusCode).toBe(400) - expect(response.json()).toEqual({ error: 'api_url_not_allowed' }) + 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 index e96ab15..39368a8 100644 --- a/backend/test/immich.test.ts +++ b/backend/test/immich.test.ts @@ -108,7 +108,7 @@ beforeAll(async () => { 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,http://immich.test/immich' + 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 diff --git a/frontend/src/api/immichApi.js b/frontend/src/api/immichApi.js index 7253554..7da570a 100644 --- a/frontend/src/api/immichApi.js +++ b/frontend/src/api/immichApi.js @@ -20,26 +20,26 @@ export function getImmichErrorMessage(error, t) { 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 === 'api_url_not_allowed') return t('Cette adresse Immich n’est pas autorisée par l’opérateur du serveur.') + 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é) et adresses autorisées par -// l'opérateur, dont le panneau d'administration fait un menu. +// 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, apiUrl: null, updatedAt: null }, - allowedApiUrls: Array.isArray(data?.allowedApiUrls) ? data.allowedApiUrls : [], + config: data?.config || { configured: false, instanceId: null, label: null, updatedAt: null }, + instances: Array.isArray(data?.instances) ? data.instances : [], } } -export async function saveImmichConfig(treeId, { apiUrl, apiKey }, token) { +export async function saveImmichConfig(treeId, { instanceId, apiKey }, token) { const data = await apiRequest(`/trees/${encodeURIComponent(treeId)}/immich/config`, withAuth({ method: 'PUT', - body: JSON.stringify({ apiUrl, ...(apiKey ? { apiKey } : {}) }), + body: JSON.stringify({ instanceId, ...(apiKey ? { apiKey } : {}) }), }, token)) return data?.config || null } diff --git a/frontend/src/components/AdminPanel.jsx b/frontend/src/components/AdminPanel.jsx index fa72858..ee147f3 100644 --- a/frontend/src/components/AdminPanel.jsx +++ b/frontend/src/components/AdminPanel.jsx @@ -61,8 +61,8 @@ const AdminPanel = ({ // 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 [immichAllowedUrls, setImmichAllowedUrls] = useState([]) - const [immichApiUrl, setImmichApiUrl] = useState('') + 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) @@ -83,16 +83,16 @@ const AdminPanel = ({ setImportingGedcom(false) setImmichConfig(null) - setImmichAllowedUrls([]) - setImmichApiUrl('') + setImmichInstances([]) + setImmichInstanceId('') setImmichApiKey('') setImmichStatus(null) fetchImmichConfig(treeId, authToken) - .then(({ config, allowedApiUrls }) => { + .then(({ config, instances }) => { if (!active) return setImmichConfig(config) - setImmichAllowedUrls(allowedApiUrls) - setImmichApiUrl(allowedApiUrls.includes(config?.apiUrl) ? config.apiUrl : '') + setImmichInstances(instances) + setImmichInstanceId(instances.some((instance) => instance.id === config?.instanceId) ? config.instanceId : '') }) .catch(() => { // Configuration non chargée : l'onglet Immich affichera l'état inconnu @@ -303,15 +303,15 @@ const AdminPanel = ({ event.preventDefault() if (!treeId || !authToken || immichBusy) return - const apiUrl = immichApiUrl - if (!apiUrl) { - setErrorMessage(t('Choisissez l’adresse de l’instance Immich.')) + 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.apiUrl && immichConfig.apiUrl !== apiUrl) + 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 @@ -325,8 +325,8 @@ const AdminPanel = ({ setErrorMessage('') setSuccessMessage('') try { - const config = await saveImmichConfig(treeId, { apiUrl, apiKey }, authToken) - setImmichConfig(config || { configured: true, apiUrl, updatedAt: null }) + 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() @@ -348,8 +348,8 @@ const AdminPanel = ({ setSuccessMessage('') try { await removeImmichConfig(treeId, authToken) - setImmichConfig({ configured: false, apiUrl: null, updatedAt: null }) - setImmichApiUrl('') + setImmichConfig({ configured: false, instanceId: null, label: null, updatedAt: null }) + setImmichInstanceId('') setImmichApiKey('') setImmichStatus(null) setSuccessMessage(t('Connexion Immich supprimée.')) @@ -567,7 +567,7 @@ const AdminPanel = ({ )}
- {immichAllowedUrls.length === 0 ? ( + {immichInstances.length === 0 ? (

{immichConfig === null ? t('État inconnu') @@ -576,16 +576,16 @@ const AdminPanel = ({ ) : (

- +
@@ -600,7 +600,7 @@ const AdminPanel = ({ autoComplete="new-password" onChange={(event) => setImmichApiKey(event.target.value)} placeholder={immichConfig?.configured - ? (immichConfig.apiUrl && immichApiUrl !== immichConfig.apiUrl + ? (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)')} diff --git a/frontend/src/i18n/en/compte.js b/frontend/src/i18n/en/compte.js index e08ff1b..617a51c 100644 --- a/frontend/src/i18n/en/compte.js +++ b/frontend/src/i18n/en/compte.js @@ -134,9 +134,9 @@ export default { 'Test impossible.': 'Test failed.', 'Connexion non testée depuis l’ouverture.': 'Connection not tested since the panel opened.', 'Tester la connexion': 'Test the connection', - 'Adresse de l’instance Immich': 'Immich instance URL', + 'Instance Immich': 'Immich instance', 'Choisir une instance…': 'Choose an instance…', - 'Choisissez l’adresse de l’instance Immich.': 'Choose the Immich instance address.', + 'Choisissez l’instance Immich.': 'Choose the Immich instance.', 'Aucune instance Immich n’est autorisée par l’opérateur de ce serveur. La reconnaissance des visages reste désactivée.': 'No Immich instance has been authorized by this server’s operator. Face recognition stays disabled.', 'Clé d’accès Immich': 'Immich access key', 'Laisser vide pour conserver la clé actuelle': 'Leave empty to keep the current key', diff --git a/frontend/src/i18n/en/fiche.js b/frontend/src/i18n/en/fiche.js index cdacc3f..e13441c 100644 --- a/frontend/src/i18n/en/fiche.js +++ b/frontend/src/i18n/en/fiche.js @@ -274,7 +274,7 @@ export default { '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 adresse Immich n’est pas autorisée par l’opérateur du serveur.': 'This Immich address is not authorized by the server operator.', + '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.', From c8df8df9371a9ae40167433af6357ac4cfa46338 Mon Sep 17 00:00:00 2001 From: IliesAllali Date: Fri, 16 Oct 2026 18:11:17 +0200 Subject: [PATCH 15/22] =?UTF-8?q?Immich=20:=20une=20cl=C3=A9=20illisible?= =?UTF-8?q?=20n'est=20plus=20signal=C3=A9e=20comme=20configur=C3=A9e?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Le résumé ne lisait que l'adresse : après un changement de JWT_SECRET, l'onglet affichait « Configurée » alors que chaque appel échouait. Le résumé déchiffre désormais la clé (configured: false, keyNeedsReentry: true, instance gardée pour préremplir le menu). L'onglet Immich affiche « Clé à ressaisir », garde le bouton de suppression, et un PUT sans clé est refusé tant que la clé en place ne se lit pas. Tests : résumé avec clé illisible, refus de conserver la clé. Co-Authored-By: Claude Opus 5.5 --- backend/src/routes/immich.ts | 29 +++++++---- backend/test/immich-config.test.ts | 64 ++++++++++++++++++++++-- backend/test/immich-unconfigured.test.ts | 2 +- frontend/src/components/AdminPanel.jsx | 13 +++-- frontend/src/i18n/en/compte.js | 2 + 5 files changed, 93 insertions(+), 17 deletions(-) diff --git a/backend/src/routes/immich.ts b/backend/src/routes/immich.ts index 1ac3894..6d713a1 100644 --- a/backend/src/routes/immich.ts +++ b/backend/src/routes/immich.ts @@ -15,7 +15,7 @@ import { ImmichUnavailableError, type ImmichPersonSummary, } from '../lib/immich.js' -import { encryptImmichApiKey } from '../lib/immich-secret.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' @@ -71,13 +71,21 @@ function replyImmichError(request: FastifyRequest, reply: FastifyReply, error: u // 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. -function immichConfigSummary(config: { apiUrl: string; updatedAt: Date } | null) { +// 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, instanceId: null, label: null, updatedAt: null } + 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, } - return { configured: true, instanceId: instance.id, label: instance.label, updatedAt: config.updatedAt } } // Portraits venus d'Immich : même nommage que les envois manuels (« avatar- »), avec le @@ -107,7 +115,7 @@ export const immichRoutes: FastifyPluginAsync = async (app) => { const config = await app.prisma.treeImmichConfig.findUnique({ where: { treeId: params.data.id }, - select: { apiUrl: true, updatedAt: true }, + select: { apiUrl: true, apiKeyEnc: true, updatedAt: true }, }) return reply.send({ @@ -150,8 +158,9 @@ export const immichRoutes: FastifyPluginAsync = async (app) => { }) // Sans nouvelle clé, la clé en place est conservée — mais il en faut une pour une - // première configuration : on ne devine jamais d'identifiants ailleurs. - if (!payload.data.apiKey && !existing) { + // 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' }) } @@ -170,7 +179,7 @@ export const immichRoutes: FastifyPluginAsync = async (app) => { where: { treeId }, create: { treeId, apiUrl: instance.apiUrl, apiKeyEnc }, update: { apiUrl: instance.apiUrl, apiKeyEnc }, - select: { apiUrl: true, updatedAt: true }, + select: { apiUrl: true, apiKeyEnc: true, updatedAt: true }, }) // Journal d'audit : jamais la clé, seulement le fait qu'elle a changé. @@ -220,7 +229,7 @@ export const immichRoutes: FastifyPluginAsync = async (app) => { }) } - return reply.send({ config: { configured: false, instanceId: null, label: null, updatedAt: null } }) + return reply.send({ config: { configured: false, keyNeedsReentry: false, instanceId: null, label: null, updatedAt: null } }) }) app.get('/trees/:id/immich/status', async (request, reply) => { diff --git a/backend/test/immich-config.test.ts b/backend/test/immich-config.test.ts index 0a5a7ed..46b7175 100644 --- a/backend/test/immich-config.test.ts +++ b/backend/test/immich-config.test.ts @@ -110,6 +110,7 @@ beforeEach(async () => { 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 }) @@ -142,6 +143,63 @@ describe('Immich configuration: read', () => { 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) @@ -155,7 +213,7 @@ describe('Immich configuration: read', () => { // 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, instanceId: null, label: null, updatedAt: null }) + 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' }, @@ -334,7 +392,7 @@ describe('Immich configuration: removal', () => { }) expect(response.statusCode).toBe(200) - expect(response.json().config).toEqual({ configured: false, instanceId: null, label: null, updatedAt: null }) + 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: { @@ -480,7 +538,7 @@ describe('Immich configuration: operator allowlist', () => { headers: { authorization: `Bearer ${token}` }, }) expect(config.statusCode).toBe(200) - expect(config.json().config).toEqual({ configured: false, instanceId: null, label: null, updatedAt: null }) + expect(config.json().config).toEqual({ configured: false, keyNeedsReentry: false, instanceId: null, label: null, updatedAt: null }) const status = await app.inject({ method: 'GET', diff --git a/backend/test/immich-unconfigured.test.ts b/backend/test/immich-unconfigured.test.ts index 2a0d970..5c0695f 100644 --- a/backend/test/immich-unconfigured.test.ts +++ b/backend/test/immich-unconfigured.test.ts @@ -92,7 +92,7 @@ describe('Immich integration: tree without configuration', () => { headers: { authorization: `Bearer ${token}` }, }) expect(config.statusCode).toBe(200) - expect(config.json().config).toEqual({ configured: false, instanceId: null, label: null, updatedAt: null }) + 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([]) diff --git a/frontend/src/components/AdminPanel.jsx b/frontend/src/components/AdminPanel.jsx index ee147f3..aea3aa7 100644 --- a/frontend/src/components/AdminPanel.jsx +++ b/frontend/src/components/AdminPanel.jsx @@ -338,7 +338,7 @@ const AdminPanel = ({ } const handleRemoveImmichConfig = async () => { - if (!treeId || !authToken || immichBusy || !immichConfig?.configured) return + 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 } @@ -545,8 +545,15 @@ const AdminPanel = ({ ? t('État inconnu') : immichConfig.configured ? t('Configurée') - : t('Non 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.')} @@ -611,7 +618,7 @@ const AdminPanel = ({ - {immichConfig?.configured && ( + {(immichConfig?.configured || immichConfig?.keyNeedsReentry) && ( - ))} + {filteredPeople.map((immichPerson) => { + const isSelected = selected?.id === immichPerson.id + const isLinked = linkedId === immichPerson.id + return ( + + ) + })}
)} -
- {thumbnailUrl - ? {selected?.name - :
} -
{selected?.name || t('Aucune sélection')}
-
+ {selected && ( +
+ +
{selected.name || t('Sans nom')}
+
+ )} {error &&
{error}
} diff --git a/frontend/src/i18n/en/fiche.js b/frontend/src/i18n/en/fiche.js index e13441c..515c3ee 100644 --- a/frontend/src/i18n/en/fiche.js +++ b/frontend/src/i18n/en/fiche.js @@ -285,7 +285,7 @@ export default { 'Aucune personne trouvée.': 'No people found.', 'Personnes Immich': 'Immich people', 'Sans nom': 'Unnamed', - 'Aucune sélection': 'No selection', + '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.', From d93710a00d96482f86691635b1bcc0a0f5a5ac12 Mon Sep 17 00:00:00 2001 From: IliesAllali Date: Fri, 16 Oct 2026 18:15:26 +0200 Subject: [PATCH 21/22] Tests Immich : la suppression d'une personne efface aussi son lien Immich Co-Authored-By: Claude Opus 5.5 --- backend/test/immich.test.ts | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/backend/test/immich.test.ts b/backend/test/immich.test.ts index e999935..a715001 100644 --- a/backend/test/immich.test.ts +++ b/backend/test/immich.test.ts @@ -1031,3 +1031,31 @@ describe('Immich integration: lien d’une fiche', () => { 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 }, + }) + }) +}) From c819027f9ba81012524a1294a6c512564ea387c3 Mon Sep 17 00:00:00 2001 From: IliesAllali Date: Fri, 16 Oct 2026 18:44:45 +0200 Subject: [PATCH 22/22] =?UTF-8?q?Immich=20:=20connexion=20d=C3=A9plac?= =?UTF-8?q?=C3=A9e=20dans=20l'onglet=20Avanc=C3=A9,=20affich=C3=A9e=20seul?= =?UTF-8?q?ement=20si=20une=20instance=20est=20autoris=C3=A9e?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit L'onglet Immich des paramètres de l'arbre est supprimé. Sa section passe dans l'onglet Avancé, au-dessus de la zone de suppression, et n'apparaît que si le serveur déclare au moins une instance. La config Immich n'est lue que pour les administrateurs, et le panneau attend cette réponse avant de s'afficher pour que la zone de suppression ne bouge pas. Co-Authored-By: Claude Opus 5.5 --- frontend/src/App.jsx | 1 + frontend/src/components/AdminPanel.jsx | 59 ++++++++++++-------------- frontend/src/i18n/en/compte.js | 5 +-- 3 files changed, 29 insertions(+), 36 deletions(-) diff --git a/frontend/src/App.jsx b/frontend/src/App.jsx index 3af018d..b2649a7 100644 --- a/frontend/src/App.jsx +++ b/frontend/src/App.jsx @@ -2932,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/components/AdminPanel.jsx b/frontend/src/components/AdminPanel.jsx index aea3aa7..42d4158 100644 --- a/frontend/src/components/AdminPanel.jsx +++ b/frontend/src/components/AdminPanel.jsx @@ -34,6 +34,7 @@ const AdminPanel = ({ visible, treeId, authToken, + isAdmin = false, onClose, onTreeDeleted, onGedcomImported, @@ -87,16 +88,20 @@ const AdminPanel = ({ setImmichInstanceId('') setImmichApiKey('') setImmichStatus(null) - 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 : l'onglet Immich affichera l'état inconnu - }) + // 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) => { @@ -107,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 @@ -119,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 @@ -388,7 +394,6 @@ const AdminPanel = ({ -
@@ -534,20 +539,18 @@ const AdminPanel = ({
)} - {section === 'immich' && ( + {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 === null - ? t('État inconnu') - : immichConfig.configured - ? t('Configurée') - : immichConfig.keyNeedsReentry - ? t('Clé à ressaisir') - : t('Non configurée')} + {immichConfig.configured + ? t('Configurée') + : immichConfig.keyNeedsReentry + ? t('Clé à ressaisir') + : t('Non configurée')} {immichConfig?.keyNeedsReentry && ( @@ -574,13 +577,6 @@ const AdminPanel = ({ )}
- {immichInstances.length === 0 ? ( -

- {immichConfig === null - ? t('État inconnu') - : t('Aucune instance Immich n’est autorisée par l’opérateur de ce serveur. La reconnaissance des visages reste désactivée.')} -

- ) : (
@@ -626,7 +622,6 @@ const AdminPanel = ({ )}
- )}
)} diff --git a/frontend/src/i18n/en/compte.js b/frontend/src/i18n/en/compte.js index 90e6957..d90300c 100644 --- a/frontend/src/i18n/en/compte.js +++ b/frontend/src/i18n/en/compte.js @@ -123,10 +123,8 @@ 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.", - // Onglet Immich (AdminPanel, connexion Immich propre à l'arbre) - 'Immich': 'Immich', + // 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.', - 'État inconnu': 'Unknown state', 'Configurée': 'Configured', 'Non configurée': 'Not configured', 'Clé à ressaisir': 'Key to re-enter', @@ -139,7 +137,6 @@ export default { 'Instance Immich': 'Immich instance', 'Choisir une instance…': 'Choose an instance…', 'Choisissez l’instance Immich.': 'Choose the Immich instance.', - 'Aucune instance Immich n’est autorisée par l’opérateur de ce serveur. La reconnaissance des visages reste désactivée.': 'No Immich instance has been authorized by this server’s operator. Face recognition stays disabled.', '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',