mirror of
https://github.com/IliesAllali/parenthese.git
synced 2026-11-07 15:42:02 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
92e3c74673 | ||
|
|
4a447c7aef | ||
|
|
79df032f10 | ||
|
|
97966054ac | ||
|
|
e787e4488e | ||
|
|
1256f09c8f | ||
|
|
5eb1d9e7bd | ||
|
|
4544edde6f | ||
|
|
b89ceb4e00 | ||
|
|
61d9bcc328 | ||
|
|
8f770371fb | ||
|
|
8cbe5ce262 | ||
|
|
9b77cca771 | ||
|
|
82ae5e289d | ||
|
|
642b6020c3 | ||
|
|
09b2acf4fe | ||
|
|
51924229da | ||
|
|
64979ef66a | ||
|
|
ef620c9cb5 | ||
|
|
332b5711ff | ||
|
|
9bf55a16f3 | ||
|
|
2c7e5361cc | ||
|
|
98de13aaa0 | ||
|
|
1558b0dc6b | ||
|
|
ce82aa5f3b | ||
|
|
43dda9c962 | ||
|
|
69b08116cf | ||
|
|
419fa4cda0 | ||
|
|
68ab7924f2 | ||
|
|
d5f9da6777 | ||
|
|
0ef5d08fec | ||
|
|
7b7a589062 | ||
|
|
0cf851475f | ||
|
|
db09620a58 | ||
|
|
374fa35fbd | ||
|
|
bb6ad7d5d2 | ||
|
|
7fee10478d | ||
|
|
f990e1c5de | ||
|
|
1565552141 | ||
|
|
568db606da | ||
|
|
24e7ea1994 | ||
|
|
e0f7eb4913 | ||
|
|
e2468f6d39 | ||
|
|
e596887a44 | ||
|
|
473414744d | ||
|
|
0269b97efd | ||
|
|
cd6dfc6955 | ||
|
|
f595af581a | ||
|
|
b803f6291d | ||
|
|
1b13b093ba | ||
|
|
c1734501ae | ||
|
|
b444c1ad39 | ||
|
|
04dc7f0e88 | ||
|
|
1c78c043bd | ||
|
|
cd93a470b8 | ||
|
|
b39d1f68e8 | ||
|
|
d013c8b8fc | ||
|
|
3dfc8625e9 | ||
|
|
1a65f28b21 | ||
|
|
cc59b7190f | ||
|
|
ba6f63ff09 | ||
|
|
4e9c0171dd | ||
|
|
1fae061a2d | ||
|
|
e39c33f977 | ||
|
|
cdb75655dd | ||
|
|
c47f0ee459 | ||
|
|
8c2c740efe | ||
|
|
0762602cdb | ||
|
|
51ac0de755 | ||
|
|
983c50159d | ||
|
|
f8a0826dfb | ||
|
|
4375fb6ba3 | ||
|
|
379102d3fe | ||
|
|
debe51c313 | ||
|
|
dbc811d722 | ||
|
|
7b08996b09 | ||
|
|
fcfb7d1494 | ||
|
|
c45bcb0463 | ||
|
|
2b81a2a2d8 | ||
|
|
e2199b0445 | ||
|
|
3327a344ff | ||
|
|
8ef87c7163 | ||
|
|
154f8219c5 | ||
|
|
0f98b8b507 | ||
|
|
a11b71a1f4 | ||
|
|
1925624e2a | ||
|
|
5b9e4e2685 | ||
|
|
a8f37b33d2 | ||
|
|
048ce96f9d | ||
|
|
291dde8073 | ||
|
|
ec4b0a1428 | ||
|
|
d7eac40cff | ||
|
|
53737b0718 | ||
|
|
c78a102d08 | ||
|
|
14f62aee90 | ||
|
|
d5d446bc32 | ||
|
|
c712ca8a15 | ||
|
|
16e765c231 | ||
|
|
b978b96864 | ||
|
|
0132ecb342 | ||
|
|
b866b36ca9 | ||
|
|
e1b25265dd | ||
|
|
a0afcfeafe | ||
|
|
2aab008766 | ||
|
|
dbc6338f9b | ||
|
|
913de99f9e | ||
|
|
0b429e78a9 | ||
|
|
00b880708d | ||
|
|
3a18ac9eab | ||
|
|
a2a2a81a12 | ||
|
|
59d3c89b1c | ||
|
|
42e4ed63bb | ||
|
|
b9f301619b | ||
|
|
20aded7ee0 | ||
|
|
3aad835908 | ||
|
|
1af0e6842e | ||
|
|
cc01059c47 | ||
|
|
ef503c570d | ||
|
|
f1b4ad8db2 | ||
|
|
856a80d111 | ||
|
|
3bfacc5b1a | ||
|
|
124ceb1c3e | ||
|
|
00aff350f1 | ||
|
|
dcc5fe74f7 | ||
|
|
a6b37bca22 | ||
|
|
bb6ec09fd1 | ||
|
|
0f06f5a9f0 | ||
|
|
bc5ab7899e | ||
|
|
01ed08d26f | ||
|
|
5b21021aca | ||
|
|
b6eaa6da78 | ||
|
|
cb1dfb39a6 | ||
|
|
8875f2baf0 | ||
|
|
fdc4254cdd | ||
|
|
3c4eef1c92 | ||
|
|
52a3ccd466 | ||
|
|
b753e91fb4 | ||
|
|
f49875f821 | ||
|
|
cd844f12a7 | ||
|
|
1f7ed7d96f | ||
|
|
c530875775 | ||
|
|
7ed0117890 | ||
|
|
4829fd77f4 | ||
|
|
f034adf761 | ||
|
|
ba6e4cbdf2 | ||
|
|
54535cb596 | ||
|
|
1d04f9ac3d | ||
|
|
2f60df2ed9 | ||
|
|
82c895d10a | ||
|
|
73be6a7cfd | ||
|
|
5ebfa8337d | ||
|
|
6e42a1f12d | ||
|
|
0c74adb012 | ||
|
|
0feb6c55ab | ||
|
|
ddc2231a8a | ||
|
|
eebb8f2cb1 | ||
|
|
d89da4c7f8 | ||
|
|
01aeb69aff | ||
|
|
da680bceea | ||
|
|
c207d25b60 | ||
|
|
b9faa2a4b4 | ||
|
|
83e8282d94 | ||
|
|
b61ce5c8ad | ||
|
|
f192665f17 | ||
|
|
3814a192f4 | ||
|
|
7c9ea3c95e | ||
|
|
f9fefd83e1 | ||
|
|
d0ab96d634 | ||
|
|
bff3f54b00 | ||
|
|
aa50123e9f | ||
|
|
9221f8b63f | ||
|
|
07d69896ae | ||
|
|
ac9c33d43f | ||
|
|
5be134e0e6 | ||
|
|
befe8fe19a | ||
|
|
230ec2ae05 | ||
|
|
3c9031e6b2 | ||
|
|
387029f4e7 | ||
|
|
c35d13885a | ||
|
|
ccd9cd0936 | ||
|
|
07b10559e6 | ||
|
|
6030b1ff6f | ||
|
|
aa22ff1422 | ||
|
|
2345dd5505 | ||
|
|
8fe2f53b34 | ||
|
|
4817cea93b | ||
|
|
93a5e41794 | ||
|
|
e91c3206f2 | ||
|
|
fb176c0cc6 | ||
|
|
d579c4a34b | ||
|
|
4ff34705c1 | ||
|
|
09c1d2337d | ||
|
|
2e5db68969 | ||
|
|
e9d57e5954 | ||
|
|
64821c9c99 | ||
|
|
03f172b59b | ||
|
|
831aa4c0ac | ||
|
|
4796d921a2 | ||
|
|
5a7cb03a01 | ||
|
|
dd0eb93965 | ||
|
|
754fd62689 | ||
|
|
06d0404903 | ||
|
|
bf1d1c1a3e | ||
|
|
01b6f47b1f | ||
|
|
f65273e95a | ||
|
|
8c684847ca | ||
|
|
bfda31f2b4 | ||
|
|
af9f81bbc2 | ||
|
|
e064ee5040 | ||
|
|
0a0668410e | ||
|
|
bfa8d2e01a | ||
|
|
0ff143f2c1 | ||
|
|
1d57c64f70 | ||
|
|
e6bb549be5 | ||
|
|
f07903c0be | ||
|
|
0fb4aeec0d | ||
|
|
25b33ca056 | ||
|
|
6bb0a832d2 | ||
|
|
65a1333d56 | ||
|
|
d55ea6ce4a | ||
|
|
fb791b6752 | ||
|
|
3b08fc1dce | ||
|
|
07e4fb11f9 | ||
|
|
441693bf43 | ||
|
|
9ba1aee96f | ||
|
|
504411adf3 | ||
|
|
65900a4372 | ||
|
|
72a3869d52 | ||
|
|
7a43fe4aaf | ||
|
|
0ad44fbaa7 | ||
|
|
352951979a | ||
|
|
111a5d3df5 | ||
|
|
c46cc747f6 | ||
|
|
34454abc18 | ||
|
|
eaecac8fa5 | ||
|
|
4dd0db9699 | ||
|
|
1b2d8ed6e2 | ||
|
|
5f115322e2 | ||
|
|
caa940f4ca | ||
|
|
da5c87d002 | ||
|
|
b7b67e76b9 | ||
|
|
b057733f64 | ||
|
|
ff078fd2bf | ||
|
|
eb8e717638 | ||
|
|
e6aa6d7fda | ||
|
|
bfa85f83fc | ||
|
|
a1203fa767 | ||
|
|
a562ad9c6e | ||
|
|
10815498b7 | ||
|
|
33718470ee | ||
|
|
3df9abe63f | ||
|
|
e23618806b | ||
|
|
65049658a1 | ||
|
|
8637d7f323 | ||
|
|
2fab1edbef | ||
|
|
ef46733329 | ||
|
|
c29610ee14 | ||
|
|
77eef8e8a0 | ||
|
|
e2af4fb580 | ||
|
|
c3d0ac30e4 | ||
|
|
71c8e1a93d | ||
|
|
fb02139929 | ||
|
|
5a069c25c5 | ||
|
|
b4df1a6b69 | ||
|
|
6950a9c21d | ||
|
|
02177d93b3 | ||
|
|
c0d057a675 | ||
|
|
e4ee286920 | ||
|
|
1664fc0771 | ||
|
|
3be95b1a0f | ||
|
|
d1e87d0eec | ||
|
|
ae8b473a25 | ||
|
|
c3bf4d2f64 | ||
|
|
5adc48ba27 | ||
|
|
1ceec79d4f | ||
|
|
a88d06c513 | ||
|
|
4483c88185 | ||
|
|
fcd8ed51af | ||
|
|
a2ce3117da | ||
|
|
92c1f25efb | ||
|
|
6c787fb0b8 | ||
|
|
eb3db5f7c5 | ||
|
|
6faaefebee | ||
|
|
0d08b0f148 | ||
|
|
dfc73858af | ||
|
|
86e1d959a7 | ||
|
|
a54bcf9f18 | ||
|
|
29324252a7 | ||
|
|
7fbf5beab0 | ||
|
|
ae77105cd0 | ||
|
|
6fd76ff7a4 | ||
|
|
68ac2fa8f8 | ||
|
|
d4416ef2ee | ||
|
|
a25f263451 | ||
|
|
7d123d66ef | ||
|
|
e98125b796 | ||
|
|
bc5c31f594 | ||
|
|
b1a7a2f489 | ||
|
|
d44aae933b | ||
|
|
14b5f0e99f | ||
|
|
6fa86d6716 | ||
|
|
85edf9ce2a | ||
|
|
6c5cacab0f | ||
|
|
217d503e20 | ||
|
|
1504a1e124 | ||
|
|
9c84bd0efc | ||
|
|
51232d8150 | ||
|
|
93307e41ab | ||
|
|
f20b58be32 | ||
|
|
82f888b1dc | ||
|
|
721c8111f2 | ||
|
|
edbbf7b163 | ||
|
|
3d5d9fea21 | ||
|
|
b013f0f40c | ||
|
|
53e4dc326a | ||
|
|
ac3cd6aec2 | ||
|
|
c6f62dc907 | ||
|
|
6a9034cf98 | ||
|
|
c24be211e1 | ||
|
|
178a932f0d | ||
|
|
942310d30f | ||
|
|
4d03864824 | ||
|
|
9dce288678 | ||
|
|
63f5b63f12 | ||
|
|
a36b287a32 | ||
|
|
e75ff5e040 | ||
|
|
b09f915662 | ||
|
|
8e1b244a4a | ||
|
|
cde9c3d44d | ||
|
|
0f6ce774e7 | ||
|
|
97b92e3f84 | ||
|
|
c2ad11df2e | ||
|
|
f0196eec54 | ||
|
|
c43fdbff4f | ||
|
|
ab6564af41 | ||
|
|
efca97d9cd | ||
|
|
1cf3dd0bc3 | ||
|
|
6bcbcb1dfd | ||
|
|
af61f91511 | ||
|
|
d0be3e9165 | ||
|
|
d234171abb | ||
|
|
92ceea6565 | ||
|
|
7752b96e3d | ||
|
|
9d9e375f58 | ||
|
|
f1ecb3951c | ||
|
|
adb2b930dd | ||
|
|
d58b7b779c | ||
|
|
ac5997659b | ||
|
|
3d709ec015 | ||
|
|
f8d4b4113d | ||
|
|
2dec945fa3 | ||
|
|
9ccd5a2e30 | ||
|
|
1e8f8f923a | ||
|
|
991a9625a2 | ||
|
|
c881863fc1 | ||
|
|
5447965243 | ||
|
|
8f866d1bd3 | ||
|
|
5740582cde | ||
|
|
9d34796d11 | ||
|
|
cd147e9387 | ||
|
|
557956fedd | ||
|
|
8372d3f29b | ||
|
|
f47ef8ecac | ||
|
|
f6affa81d6 | ||
|
|
87c564fd3c | ||
|
|
e24c8c86d6 | ||
|
|
4e900f1c30 | ||
|
|
dd738c483a | ||
|
|
2d35bddf27 | ||
|
|
7e7641dc19 | ||
|
|
6d78aa5d10 | ||
|
|
7488254cc9 | ||
|
|
2db048aad6 | ||
|
|
69598ce116 | ||
|
|
f36d59fcee | ||
|
|
bd8ba8ffaa | ||
|
|
265ae1d9f3 | ||
|
|
6a366416ef | ||
|
|
62727658dc | ||
|
|
1c065a8db4 | ||
|
|
63d997b8cf | ||
|
|
5454549ab0 | ||
|
|
bca0543803 | ||
|
|
0e96ffc020 | ||
|
|
2fccf287b3 | ||
|
|
3097768af5 | ||
|
|
897ada2665 | ||
|
|
c556e84610 | ||
|
|
12ccb520f5 | ||
|
|
768fdf1b0b | ||
|
|
e3bfe9c2a6 | ||
|
|
e327cc223d | ||
|
|
8556d32bce | ||
|
|
5f968a9f22 | ||
|
|
588ac0c4e9 | ||
|
|
1caa090efd | ||
|
|
8574dfed9e | ||
|
|
c819027f9b | ||
|
|
d93710a00d | ||
|
|
6b1f4c067e | ||
|
|
8fa2808b5d | ||
|
|
b27b5e9737 | ||
|
|
6ff99337d2 | ||
|
|
7f159d5111 | ||
|
|
697c0e3897 | ||
|
|
de897070db | ||
|
|
ca23dfa318 | ||
|
|
f2ca980950 | ||
|
|
f37fc329ba | ||
|
|
c8df8df937 | ||
|
|
d17cee20df | ||
|
|
265b3b30a0 | ||
|
|
420bda5e38 | ||
|
|
fbcac3afd4 | ||
|
|
63b9761ec4 | ||
|
|
44dd203069 | ||
|
|
43441f31e1 | ||
|
|
cf946be617 | ||
|
|
8803463ce4 | ||
|
|
3a5fa42670 | ||
|
|
310f2fb597 | ||
|
|
8d36a08b11 | ||
|
|
0bda88920d | ||
|
|
a3386824d3 | ||
|
|
50873a4f9e | ||
|
|
c703a34165 | ||
|
|
2f64ceb41d | ||
|
|
47083ec274 | ||
|
|
378071bf13 | ||
|
|
abee3c6e19 | ||
|
|
a91474f0e6 | ||
|
|
8103154e02 | ||
|
|
83443ac9dc | ||
|
|
2a510bf474 | ||
|
|
7becb821a3 | ||
|
|
333a11e84b | ||
|
|
b774b1dff8 | ||
|
|
30d015f083 | ||
|
|
cea8d1db8f | ||
|
|
91abe47614 | ||
|
|
5a11d00af9 | ||
|
|
c564ebeb05 | ||
|
|
ada823ab47 | ||
|
|
2e638d8a43 |
No files matched your search
@@ -34,6 +34,51 @@ CORS_ORIGIN=http://localhost
|
||||
# MEDIA_QUOTA_PER_TREE_MB=5120
|
||||
# MEDIA_PENDING_QUOTA_PER_TREE_MB=500
|
||||
|
||||
# ── Comptes ───────────────────────────────────────────────────────────────────
|
||||
# À false, plus personne ne peut créer de compte : les comptes existants se connectent et
|
||||
# créent leurs arbres, la famille ouvre toujours les arbres partagés avec le lien et le mot
|
||||
# de passe. Une instance sans aucun compte accepte quand même le premier (le vôtre) :
|
||||
# créez-le juste après le premier démarrage, avant de donner l'adresse.
|
||||
# ALLOW_REGISTRATION=true
|
||||
# À true, l'app invite à créer son propre arbre : « Faire le mien » dans le menu Ajouter de la
|
||||
# famille, l'inscription proposée dans les messages de la démo, un message d'invitation pour Noël
|
||||
# (du 1er décembre au 6 janvier). Éteint par défaut, allumé sur app.parenthese.io.
|
||||
# SIGNUP_PROMPTS=false
|
||||
|
||||
# ── Chercher quelqu'un dans des sources publiques ────────────────────────────
|
||||
# Sources que le serveur interroge pour le panneau « Quelqu'un ailleurs » (menu +) :
|
||||
# deces (décès en France depuis 1970, fichier de l'INSEE par matchID), wikitree.
|
||||
# Vide : aucun nom ne quitte l'instance, le panneau ne propose que des liens ouverts
|
||||
# par le navigateur. Seuls le prénom, le nom et l'année de naissance sont envoyés.
|
||||
# SEARCH_SOURCES=deces,wikitree
|
||||
# Clé gratuite de deces.matchid.io (valable 30 jours) : sans elle, les recherches
|
||||
# anonymes s'arrêtent après une centaine.
|
||||
# MATCHID_TOKEN=
|
||||
|
||||
# ── Connexion par un fournisseur d'identité (OIDC : Authentik, Authelia, Keycloak…) ──
|
||||
# Éteinte sans OIDC_ISSUER. Chez le fournisseur, adresse de retour = adresse publique + /auth/oidc/callback.
|
||||
# Détails dans le README, section « Connexion par votre fournisseur d'identité ».
|
||||
# OIDC_ISSUER=https://auth.votre-domaine.fr/application/o/parenthese/
|
||||
# OIDC_CLIENT_ID=parenthese
|
||||
# OIDC_CLIENT_SECRET=
|
||||
# OIDC_REDIRECT_URI=https://arbre.votre-domaine.fr/auth/oidc/callback
|
||||
# OIDC_PROVIDER_NAME=Authentik
|
||||
# Email accepté seulement s'il est vérifié chez le fournisseur (email_verified).
|
||||
# OIDC_REQUIRE_VERIFIED_EMAIL=true
|
||||
# À false, plus de mot de passe Parenthèse : connexion par le fournisseur seulement.
|
||||
# PASSWORD_LOGIN=true
|
||||
|
||||
# ── Immich (reconnaissance des visages, désactivé par défaut) ────────────────
|
||||
# Instances Immich autorisées sur ce serveur, séparées par des virgules. Chaque entrée
|
||||
# peut recevoir un libellé, « Libellé=https://adresse » ; sans libellé, c'est le nom
|
||||
# d'hôte qui sert (un même nom d'hôte ne peut pas servir à deux instances : donnez-leur
|
||||
# un libellé). Les administrateurs de chaque arbre choisissent l'instance par son nom
|
||||
# et donnent leur propre clé d'API (créée dans Immich, Paramètres > Clés d'API) ; la
|
||||
# clé est chiffrée en base. L'adresse n'est jamais montrée aux administrateurs : seul
|
||||
# le libellé l'est. Sans cette liste, la fonction reste éteinte, et une adresse retirée
|
||||
# de la liste coupe aussitôt les arbres qui l'utilisent.
|
||||
# IMMICH_ALLOWED_API_URLS=Maison=http://immich.maison.lan:2283,https://immich.example.org
|
||||
|
||||
# ── Images ────────────────────────────────────────────────────────────────────
|
||||
# Version des images ghcr.io/iliesallali/parenthese-api et parenthese-web : latest (dernière
|
||||
# version de main), ou une version figée, par exemple 1.0.
|
||||
|
||||
@@ -2,3 +2,5 @@
|
||||
* text=auto
|
||||
# Scripts lancés sous Linux (serveur, conteneurs, CI) : fins de ligne LF même sur un clone Windows
|
||||
*.sh text eol=lf
|
||||
# Témoins texte du placement : comparés octet pour octet par vitest, toujours en LF
|
||||
frontend/src/components/galaxy/__snapshots__/** text eol=lf
|
||||
@@ -29,7 +29,7 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
@@ -63,7 +63,7 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
@@ -118,7 +118,7 @@ jobs:
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5.0.0
|
||||
- uses: actions/setup-node@949feb2413d6458794dcd2491c4babbbce0c15c1 # v7.1.0
|
||||
with:
|
||||
node-version: 24
|
||||
cache: npm
|
||||
@@ -141,7 +141,7 @@ jobs:
|
||||
run: npx prisma migrate deploy
|
||||
|
||||
- name: Schéma Prisma aligné sur les migrations
|
||||
run: npx prisma migrate diff --from-url "$DATABASE_URL" --to-schema-datamodel prisma/schema.prisma --exit-code
|
||||
run: npx prisma migrate diff --from-config-datasource --to-schema prisma/schema.prisma --exit-code
|
||||
|
||||
- name: Tests
|
||||
run: npm test
|
||||
@@ -182,12 +182,77 @@ jobs:
|
||||
- name: Test de fumée par le port web
|
||||
run: bash tools/docker-smoke.sh http://localhost:8080
|
||||
|
||||
# Les commandes de sauvegarde et de restauration du README, jouées pour de vrai
|
||||
- name: Sauvegarde puis restauration
|
||||
run: |
|
||||
set -euo pipefail
|
||||
bash tools/docker-restore-check.sh http://localhost:8080
|
||||
bash tools/docker-smoke.sh http://localhost:8080
|
||||
|
||||
# Un second front qui joint l'API par le nom de son conteneur (API_UPSTREAM), comme sur Umbrel.
|
||||
- name: Front avec une autre adresse d'API
|
||||
run: |
|
||||
WEB_IMAGE="$(docker compose config --images | grep parenthese-web)"
|
||||
API_CONTAINER="$(docker compose ps -q api | xargs docker inspect -f '{{.Name}}' | tr -d /)"
|
||||
docker run -d --name web-upstream --network parenthese_default -p 8081:80 \
|
||||
-e API_UPSTREAM="$API_CONTAINER:4000" "$WEB_IMAGE"
|
||||
sleep 3
|
||||
docker exec web-upstream grep -q "http://$API_CONTAINER:4000" /etc/nginx/conf.d/default.conf
|
||||
bash tools/docker-smoke.sh http://localhost:8081
|
||||
|
||||
- name: État et journaux en cas d'échec
|
||||
if: failure()
|
||||
run: |
|
||||
docker compose ps -a
|
||||
docker compose logs --no-color --timestamps
|
||||
docker logs web-upstream || true
|
||||
|
||||
- name: Arrêt et suppression des volumes
|
||||
if: always()
|
||||
run: docker compose down -v --remove-orphans
|
||||
run: |
|
||||
docker rm -f web-upstream || true
|
||||
docker compose down -v --remove-orphans
|
||||
|
||||
docker-aio:
|
||||
name: Docker tout-en-un (Unraid, NAS)
|
||||
runs-on: ubuntu-latest
|
||||
timeout-minutes: 30
|
||||
env:
|
||||
SMOKE_WAIT_SECONDS: 180
|
||||
steps:
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
with:
|
||||
persist-credentials: false
|
||||
|
||||
- name: Construction
|
||||
run: DOCKER_BUILDKIT=1 docker build -f Dockerfile.aio -t parenthese-aio:test .
|
||||
|
||||
- name: Démarrage, sans aucune variable
|
||||
run: docker run -d --name aio -p 8080:80 -v aio-data:/data parenthese-aio:test
|
||||
|
||||
- name: Test de fumée par le port web
|
||||
run: bash tools/docker-smoke.sh http://localhost:8080
|
||||
|
||||
# Les secrets et la base de /data doivent servir tels quels au démarrage suivant (mise à jour, reboot).
|
||||
- name: Redémarrage puis nouveau test
|
||||
run: |
|
||||
set -euo pipefail
|
||||
docker restart aio
|
||||
bash tools/docker-smoke.sh http://localhost:8080
|
||||
docker logs aio 2>&1 | grep -c "première installation" | grep -qx 1
|
||||
# Base à jour au redémarrage : pas de sauvegarde avant migration, mais pg_dump marche dans l'image
|
||||
[ -z "$(docker exec aio ls -A /data/backups 2>/dev/null)" ]
|
||||
[ "$(docker exec aio runuser -u postgres -- pg_dump -Fc parenthese | wc -c)" -gt 1000 ]
|
||||
|
||||
- name: Journaux en cas d'échec
|
||||
if: failure()
|
||||
run: |
|
||||
docker ps -a
|
||||
docker logs --timestamps aio || true
|
||||
docker run --rm -v aio-data:/data busybox cat /data/postgres/postgres.log || true
|
||||
|
||||
- name: Arrêt et suppression du volume
|
||||
if: always()
|
||||
run: |
|
||||
docker rm -f aio || true
|
||||
docker volume rm aio-data || true
|
||||
@@ -58,7 +58,7 @@ jobs:
|
||||
|
||||
- name: Upload screenshots
|
||||
if: always()
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2
|
||||
uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2
|
||||
with:
|
||||
name: fresh-install-shots
|
||||
path: parenthese/shots
|
||||
|
||||
@@ -53,22 +53,31 @@ jobs:
|
||||
- image: parenthese-web
|
||||
context: .
|
||||
file: Dockerfile.web
|
||||
# Tout-en-un (base, API, front) pour Unraid et les NAS
|
||||
- image: parenthese-aio
|
||||
context: .
|
||||
file: Dockerfile.aio
|
||||
steps:
|
||||
# Sur workflow_run, le commit exact que la CI a validé, pas la tête de main au moment du run.
|
||||
- uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0
|
||||
with:
|
||||
ref: ${{ github.event.workflow_run.head_sha || github.sha }}
|
||||
persist-credentials: false
|
||||
# Tout l'historique et les tags, pour lire la version (git describe)
|
||||
fetch-depth: 0
|
||||
|
||||
- name: Short commit
|
||||
# Version lisible dans le label OCI (#207) : 1.5.9 sur un tag, 1.5.9-11-gd5f9da6 sur main après la 1.5.9
|
||||
- name: Short commit and version
|
||||
id: commit
|
||||
run: echo "sha=$(git rev-parse --short=7 HEAD)" >> "$GITHUB_OUTPUT"
|
||||
run: |
|
||||
echo "sha=$(git rev-parse --short=7 HEAD)" >> "$GITHUB_OUTPUT"
|
||||
echo "version=$(git describe --tags --match 'v*' | sed 's/^v//')" >> "$GITHUB_OUTPUT"
|
||||
|
||||
- uses: docker/setup-qemu-action@99012661954931238ded8c8b007157a8430204e1 # v4.4.0
|
||||
|
||||
- uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1
|
||||
|
||||
- uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
|
||||
- uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
@@ -85,6 +94,7 @@ jobs:
|
||||
type=raw,value=latest,enable=${{ github.event_name == 'workflow_run' }}
|
||||
type=raw,value=sha-${{ steps.commit.outputs.sha }}
|
||||
labels: |
|
||||
org.opencontainers.image.version=${{ steps.commit.outputs.version }}
|
||||
org.opencontainers.image.revision=${{ github.event.workflow_run.head_sha || github.sha }}
|
||||
org.opencontainers.image.licenses=PolyForm-Noncommercial-1.0.0
|
||||
|
||||
@@ -116,7 +126,7 @@ jobs:
|
||||
persist-credentials: false
|
||||
|
||||
# Tant que les paquets ne sont pas publics, le pull demande une connexion.
|
||||
- uses: docker/login-action@dbcb813823bdd20940b903addbd779551569679f # v4.6.0
|
||||
- uses: docker/login-action@81c6f93d4bc991e510b342a00b419b3bb4efc5c6 # v4.7.0
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
|
||||
+388
@@ -2,6 +2,394 @@
|
||||
|
||||
Notable changes to Parenthèse. Dates are in YYYY-MM-DD format.
|
||||
|
||||
## 1.6.0 (2026-11-04)
|
||||
|
||||
### Adding people
|
||||
|
||||
- Several first names in the First name field, separated by commas, add several children or siblings at once. "Paul, Marie, Jean" creates three people with the same links, last name and dates. Empty names and duplicates are skipped, up to 20 names. For a parent or a partner the field still takes one name. On a phone no profile opens after a group add, and the view frames the whole family (#203).
|
||||
|
||||
### Life tab
|
||||
|
||||
- Photos of a marriage show for both partners. The marriage was already in both Life tabs, but its photos only showed on the profile they were added from. A partner's photo opens in their name (#209).
|
||||
|
||||
### Words
|
||||
|
||||
- English relationship names go as far as the tree does. Great-great-grandfather, great-great-uncle, grandnephew, second cousin, first cousin twice removed, 4th cousin. "Partner" replaces "Spouse" everywhere, on the profile and the tree too, and "Nibling" is the neutral form of nephew and niece. Thanks to Arc676 (#204).
|
||||
|
||||
### Photos
|
||||
|
||||
- Portrait thumbnails follow the saved crop everywhere, not only on the tree and the profile. That covers the viewer, "In this photo", search, the profile links, adding a relative, the account and memory picking (#205).
|
||||
|
||||
### Shared links
|
||||
|
||||
- A link to the app pasted in WhatsApp, Messenger or iMessage shows a title, a sentence and an image. They are the same for every address, so no name or photo from a tree reaches the preview bots (#201).
|
||||
- A link with `?source=` and no session opens the demo again, not the welcome screen (#211).
|
||||
|
||||
### Hosted instance
|
||||
|
||||
- New `SIGNUP_PROMPTS` setting for the API, off by default. When it's on and registration is open, the app invites people to make their own tree in places that already exist: the Add menu of a shared tree, the demo messages, a "Create my tree" button in the demo bar, and a Christmas wording in the family invitation from December 1 to January 6. A self-hosted instance sees none of this unless it turns it on (#202, #212).
|
||||
- In the demo, the dialog that closes editing no longer says changes stay on this device. The demo saves nothing and the sentence now says so (#202).
|
||||
|
||||
### Docker
|
||||
|
||||
- `org.opencontainers.image.version` carries the real version: `1.6.0` on a release tag, and for example `1.5.9-11-gd5f9da6` on `latest` between releases. Container watchers like What's Up Docker can show it instead of a digest (#207).
|
||||
|
||||
## 1.5.9 (2026-10-29)
|
||||
|
||||
### Tree
|
||||
|
||||
- A child added to someone who has a single partner becomes the couple's child, next to their brothers and sisters, instead of hanging under one parent and an "Unknown" one. With no partner, several partners, or an adoption, the child stays with the parent chosen (#200).
|
||||
|
||||
### Phone
|
||||
|
||||
- No more zoom slider: it opened by itself and covered a corner of the tree. Pinch to zoom, the magnifier zooms in one step. On a computer the slider still shows on hover (#199).
|
||||
|
||||
### Profile
|
||||
|
||||
- "– 1995" no longer breaks after the dash at the end of a line. The magnifier button is labelled "Zoom in" for screen readers.
|
||||
|
||||
## 1.5.8 (2026-10-29)
|
||||
|
||||
### Family tabs
|
||||
|
||||
- A tab is named after the surname most of its members carry (birth name, otherwise current name), not after the person it starts from. When two tabs would share a name, the smaller one takes its next most common surname (#192).
|
||||
- Switching tabs keeps the person who joins the two families at the same place and zoom, only the families around change. Hovering a tab lights that person up in the tree (#192).
|
||||
- The tab bar follows the shape of the tree, grouped by branch, with a line between a tab and the one it comes from. The way-back badge sits where the way-in badge was (#192).
|
||||
|
||||
### Profile
|
||||
|
||||
- The age counts the birthday: with a full birth date, a person born in December is not a year older from January. Same for the age at death and the ages in the Life tab. With only a year, the age stays the difference between the years (#198).
|
||||
|
||||
### Dependencies
|
||||
|
||||
- `@node-rs/bcrypt` 2.0: the cost is passed as an option. Stored passwords still verify, new hashes are `$2b$` with the same cost (#197).
|
||||
- Minor updates for the frontend, the landing, the backend and the CI (#193, #194, #195, #196).
|
||||
|
||||
## 1.5.7 (2026-10-28)
|
||||
|
||||
### Phone
|
||||
|
||||
- Opening a tree no longer opens the start person's profile, which covered the bottom of the screen and the start person with it. The start person now sits at 40% of the height instead of 56% (#189, closes #188).
|
||||
- Tapping someone in the tree moves them into the top third, above their profile (#189).
|
||||
|
||||
### Life tab
|
||||
|
||||
- A couple reads "Together with X", and "Married X" only when it is said: a date, a place, marriage documents, or the box ticked. Before, every couple read "Marries X", because a couple is stored as a marriage as soon as a child has two parents (#190).
|
||||
- The date and place of a couple can be set from the Life tab: tap the couple's line, then "They were married", "When?" (year, "about", exact date) and "Where?". `PATCH /trees/:id/unions/:unionId` accepts `startPlace` and `startDatePrecision` (#190).
|
||||
- The names of a partner, a child, a brother or sister, or a parent open that person's profile and move the tree to them (#190).
|
||||
|
||||
## 1.5.6 (2026-10-28)
|
||||
|
||||
### Tree
|
||||
|
||||
- Optional last name under the first name: the maiden name when it is known, otherwise the current last name. In the tree settings, under Display. Saved in this browser (#186, closes #168).
|
||||
- Opening a tree: the camera now stops close enough to read the names, and on a phone the tree is centred in the space beside the zoom slider (#187).
|
||||
|
||||
### Undo bar
|
||||
|
||||
- The message agrees with the person's sex in French ("supprimée", "supprimé"), and "supprimé·e" only when it is unknown (#185).
|
||||
- On phones and tablets the bar no longer covers the zoom slider. On a computer the zoom button is hidden while a profile is open (#185).
|
||||
|
||||
### Shortcuts
|
||||
|
||||
- Ctrl+K (⌘K on Mac) opens the person search from anywhere. The search tooltip and the Edit menu show their shortcuts (#184).
|
||||
|
||||
## 1.5.5 (2026-10-27)
|
||||
|
||||
### Undo instead of confirm
|
||||
|
||||
- Deleting a person no longer asks for confirmation. A bar with "Undo" stays for 6 seconds, and Ctrl+Z works too (#169).
|
||||
- Same for a memory and for a moment in the Life tab. Two fixes to #169 on the way: an open profile no longer closes when the deletion starts, and the tree's internal lists are up to date after an undo (#172).
|
||||
|
||||
### Motion
|
||||
|
||||
- Profile card: it appears at once on a computer, with no fade or blur. On a phone it still rises as a sheet in 240 ms, resists when pulled up, and has continuous corners where the browser supports `corner-shape` (#170).
|
||||
- A memory grows from its thumbnail when it opens (280 ms, transform only). The viewer now respects reduced motion (#171).
|
||||
- On a phone, dragging a memory's photo down closes it, like the profile card (#176).
|
||||
- Opening a tree for the first time, the camera starts on the start person and pulls back to the family in 1.1 s while the tree draws. After an edit or a tab change, the tree shows without animation. With reduced motion, a plain fade (#181).
|
||||
|
||||
### Faces on photos
|
||||
|
||||
- Face markers are hidden by default. They show on hover with a mouse, when a name is hovered in the list, in tagging mode, or after a tap on the photo. The circles are thinner (#173).
|
||||
|
||||
### Phone
|
||||
|
||||
- Edit mode: the family tabs move to the top so the "You suggest" bar no longer covers them. The exit button reads "Done", at the height of the "+", and the bar's own close button is gone (#175).
|
||||
- The family bar only moves aside when the profile card reaches it (#180).
|
||||
- Tap targets of at least 44 px on touch screens, with no visible change (#182).
|
||||
|
||||
### Loading
|
||||
|
||||
- Big trees open faster with the same placement, and the list of family tabs is computed in a worker. A 3,010-person tree is usable in 1.6 s instead of 8.7 s. Tools in `tools/layout-bench` (`layout-time.mjs`, `load-probe.mjs`) (#179).
|
||||
- Blurred previews (BlurHash) of photos and portraits while they load. Migration `20261027_001_apercus_flous` adds two optional columns, and a background task fills them for existing photos when the API starts (#177).
|
||||
- Grey blocks while loading, instead of "Loading…" or a false empty state: the Life tab of a person with no known date, and the tree's panels (#178).
|
||||
|
||||
### Reliability
|
||||
|
||||
- Uploads from the family no longer create duplicates on a weak connection, through an `Idempotency-Key` header (#174).
|
||||
|
||||
### Landing
|
||||
|
||||
- Pages are prefetched when a link is hovered (`speculationrules`). The landing CSP in `deploy/nginx.conf` gets a second script hash for it (#183).
|
||||
|
||||
## 1.5.4 (2026-10-26)
|
||||
|
||||
### A link per family tab (#167)
|
||||
|
||||
- `?famille=<hinge person id>` opens the tree on that family's tab. The tab opens once the tree and its tabs are known, and again if the start person arrives later (as it does for a visitor), unless the person already picked a tab. With tabs turned off in that browser, the whole tree opens framed on the hinge person. An unknown key is ignored.
|
||||
- The page address follows the open tab. In the share panel, the link to send and the invitation message follow it too, and the title names the family ("The link to send to the Garnier family").
|
||||
- Same password and same access: the link picks the landing tab and restricts nothing.
|
||||
|
||||
## 1.5.3 (2026-10-26)
|
||||
|
||||
### Videos in Safari (#162)
|
||||
|
||||
- Media files are streamed and answer byte-range requests (`Accept-Ranges: bytes`, `206` with `Content-Range`, `416` outside the file). Safari on iOS, iPadOS and macOS needs this to play a video. Before, the whole file was read into memory and sent in one block.
|
||||
|
||||
### Accounts
|
||||
|
||||
- A password account on an OIDC instance can link its provider identity from its account ("Also sign in with …"), through a two-minute, single-use ticket (`POST /auth/oidc/link`, then `/auth/oidc/start?link=`). The identity joins that account whatever its email, and an identity already linked to another account is never moved. This is the way to switch an instance to `PASSWORD_LOGIN=false` without locking out password accounts. `/auth/me` returns `oidcLinked` (#161).
|
||||
- Signing out, or deleting the account, now survives an API restart: closed sessions are kept in the `revoked_sessions` table until their token expires, and the API refuses to start if it can't load them. Migration `20261026_001_deconnexions` (#163).
|
||||
|
||||
### Security
|
||||
|
||||
- A media waiting for review is readable only by a tree admin or by the account that uploaded it. Anyone else gets the same 404 as a missing media (#160).
|
||||
- Passwords are hashed with native bcrypt (`@node-rs/bcrypt`) off the event loop. Existing hashes keep working, no migration (#160).
|
||||
- Frontend lockfile: zod 4.6.7, a dev dependency (#166).
|
||||
|
||||
### Under the hood
|
||||
|
||||
- Prisma 7 with the pg driver adapter. The client is generated in `backend/src/generated` and `backend/prisma.config.ts` holds the database URL for the CLI. Without Docker, Node must be ^20.19, ^22.12 or 24+, and `deploy/deploy.sh` stops early on an older Node (#164).
|
||||
- Tailwind 4 for the app and the landing, through the Vite plugin. The v3 base styles the app relied on are kept, and nothing changes on screen (#165).
|
||||
|
||||
## 1.5.2 (2026-10-26)
|
||||
|
||||
### Dates follow the browser's region (#152)
|
||||
|
||||
- Dates follow the browser's regional variant of the interface language (en-US, en-AU, fr-CA…), falling back to fr-FR or en-GB. Before, English always used the British format. This covers every date and time shown in the app, e.g. `10/26/2026, 10:57 AM` in the review panel on an en-US browser.
|
||||
- Typed dates follow the region's order and separator: `06/12/1924` in en-US, `1924-06-12` in fr-CA, `12/06/1924` in France and the UK. A year-first date is read everywhere.
|
||||
- The date field also accepts a written month, in French or English: `12 juin 1924`, `1er août 1950`, `June 12, 1924`, `3 sept. 1901`. An ambiguous month (`jui`) is refused.
|
||||
|
||||
### Names in non-Latin scripts
|
||||
|
||||
- Initials for scripts without capital letters (Chinese, Japanese, Korean, Arabic, Hebrew…) are a single character: the family name for Chinese, Japanese and Korean, the first name for Arabic and Hebrew. Latin and Cyrillic keep two initials. This applies to profiles, suggestion cards, the first-photos panel and the tree.
|
||||
- A birth place or a nickname in a right-to-left script no longer flips the order of the line under the name.
|
||||
|
||||
### Suggestion cards
|
||||
|
||||
- The action label (New, Edit, Delete) sits on the top edge of the card, so the name keeps the full width and both buttons stay inside the card on a phone.
|
||||
- A change whose profile changed after the suggestion was sent shows "Needs checking" in place of "Edit". Any other action keeps its word ("Delete, needs checking").
|
||||
|
||||
### Fixes
|
||||
|
||||
- The quick buttons to add a parent, partner, child or sibling in a profile's Info tab are dashed chips, like "+ Nickname" in edit mode (#154).
|
||||
- The notice after adding someone or sending changes takes the width it needs on a phone, instead of four lines in a pill, and appears without animation (#156).
|
||||
- The counter of pending suggestions on the account picture is round for a single digit.
|
||||
- Backend dependencies: ip-address 10.7.4 (#144) and fast-uri (#155), for known security issues.
|
||||
|
||||
### For self-hosters
|
||||
|
||||
- No database change.
|
||||
|
||||
## 1.5.1 (2026-10-25)
|
||||
|
||||
### Suggestions show on the tree
|
||||
|
||||
- A suggestion waiting for review now shows on the tree, where it will go: a suggested person is drawn faded, with a dotted circle and a "Suggested" tag, and their links are dotted. Words, drawings and photos placed on the tree show see-through. A person with a suggested change gets a small dot.
|
||||
- Whoever manages the tree opens a suggested person to see who suggested it and what else the suggestion holds, and accepts or rejects it right there. A person with a suggested change shows the fields in their profile, with the same buttons. "See details" opens the review panel to sort change by change.
|
||||
- The family sees what they are adding as a "Draft" before sending it, then as "Waiting" until it is reviewed. This is kept in their browser only, and cleared once the suggestion is reviewed.
|
||||
- After adding a person, the send window no longer opens by itself. The family can add several people, then send once with Send.
|
||||
|
||||
### Photos placed on the tree by the family
|
||||
|
||||
- A family member can now place a photo on the tree. Before, the upload was refused without a word and the photo never showed. The photo waits for review: it is kept if accepted, deleted if rejected, and an upload never sent is deleted after 7 days. At most 50 photos wait on a tree at once.
|
||||
- Accepted words, drawings and photos are now placed by the server when the suggestion is accepted. Before, the reviewer's browser placed them afterwards and could lose them, and none appeared when the family's changes apply directly.
|
||||
|
||||
### Adding relatives from a profile
|
||||
|
||||
- "Someone elsewhere": relatives can add a person found in public records too. It goes into their changes and the tree manager reviews it, like any other proposal. Places, the "needs checking" mark and the source link now travel with a proposed new person.
|
||||
- In a profile's Links tab, searching for a parent, child or partner who is not in the tree yet now offers "Create …", which opens the add panel already filled in.
|
||||
- Profiles have a Siblings section, with "Add a sibling".
|
||||
- The Info tab has quick buttons to add a parent, partner, child or sibling without going into edit mode first.
|
||||
- The add panel opened from a profile comes with the link already set, and suggests the family name for a child or a sibling.
|
||||
- Adding someone whose first and last name match a person already in the tree shows a warning, with a button to open that person's profile.
|
||||
|
||||
### Fixes
|
||||
|
||||
- The "needs checking" mark sits on the corner of the portrait, half outside, so it no longer covers the face.
|
||||
- "Update the tree" no longer clears your changes when part of them fails to save: what failed stays in your edits, with a message.
|
||||
- A suggestion already reviewed elsewhere (another tab, a co-manager) now says so, instead of a message about emails, and the tree updates.
|
||||
- After the family sends their changes, the tree reloads: a photo just sent no longer looks accepted.
|
||||
- Zooming with the mouse wheel no longer logs an error in the browser console.
|
||||
|
||||
### For self-hosters
|
||||
|
||||
- New table `annotation_photo_uploads` (migration `20261025_003`, additive).
|
||||
- New route `GET /trees/:id/contributions/sessions/:sessionId/status`, which returns only the status of a suggestion to someone who can read the tree.
|
||||
- Anonymous counters for editing (person added and from where, suggestion sent or reviewed, edits saved), with no content from the tree. As before, nothing is sent without `VITE_POSTHOG_KEY`.
|
||||
|
||||
## 1.5.0 (2026-10-25)
|
||||
|
||||
### Several managers for one tree
|
||||
|
||||
- The owner can invite co-managers from the tree settings, in a new Managers tab. Parenthèse sends no email: the owner gets a link to pass on. The link works once, lasts 14 days, and can be cancelled. Copying it again creates a new link and the old one stops working (#145, asked by @milan616).
|
||||
- A co-manager edits the tree and reviews the family's suggestions like the owner. Only the owner invites or removes a co-manager and deletes the tree. A co-manager can leave from the Advanced tab.
|
||||
- Immich stays with the owner. Its key opens the owner's whole library, so co-managers do not see it or change it.
|
||||
- With a password account, the link is needed and the account must use the invited address. With OIDC, a co-manager whose provider marks the invited address as verified is added at sign-in, without the link. An unverified address is never matched.
|
||||
- An invitation opens an account even when `ALLOW_REGISTRATION=false`, at the invited address only.
|
||||
- Removing a co-manager takes effect on their next request, and also drops any access they had saved with the sharing password. The settings then offer to change that password, since they may have seen it.
|
||||
- Deleting your account now names the co-managers of the trees you own, which are deleted for them too.
|
||||
- In the tree menu, "Admin" is now "Co-manager".
|
||||
|
||||
### Search for someone elsewhere
|
||||
|
||||
- "Someone elsewhere" in the bottom-right menu opens a panel on the right of the tree: type a name, birth year and place, and search public records. Links to Gallica (old newspapers), FranceArchives (military registers), Mémoire des hommes, Léonore, Geneanet, Open Archives, WikiTree, FreeBMD and FamilySearch open in the browser with the name typed in when the site allows it.
|
||||
- The server can query deaths in France since 1970 (INSEE records via matchID) and WikiTree, once listed in `SEARCH_SOURCES`. Each source says what it covers and what is sent. The owner adds a result to a person in the tree: empty fields only, marked as needing checking, source kept in the note.
|
||||
|
||||
### Trees
|
||||
|
||||
- A tree can have an icon, picked from fifteen emoji in Settings > Your tree. It replaces the first letter in the tree menu, on the account page and on the invitation page.
|
||||
- For whoever manages the tree, the button at the bottom right now reads Edit, with a pencil. The family keeps Add.
|
||||
- A tree name starting with an emoji no longer shows a broken letter in the menus.
|
||||
|
||||
### Fixes
|
||||
|
||||
- An admin can switch a person's profile to edit mode from a new Edit button on the profile.
|
||||
- The "?" of "needs checking" shows whole on round portraits. It was cut by the frame.
|
||||
- On iPad, the tree no longer stops short of the bottom of the screen. The canvas follows its real size instead of the window height read at load.
|
||||
|
||||
## 1.4.0 (2026-10-23)
|
||||
|
||||
### Family tabs
|
||||
|
||||
- In another family's tab, the person you marked as "That's me" stays on screen, linked to that family by their direct line (the shortest kinship path, both parents at each step, no siblings around), drawn faded. Without a choice, the tree's starting person is used (#138).
|
||||
- Visitors without an account can say who they are in the tree from their menu. The choice is kept in their browser for that tree (#138).
|
||||
|
||||
### Notes on the tree
|
||||
|
||||
- A note is attached to the nearest person when it is placed. It only shows in the tabs where that person is drawn, and stays next to them when the layout changes. Notes placed before this version are attached the first time the tree opens (#141).
|
||||
- A placed text can be edited again. With the select tool, click it twice (#141).
|
||||
|
||||
### People
|
||||
|
||||
- A person can be marked as needing checking, for a date or a link you are not sure of. A "?" shows on the portrait and a pill on the profile, the family can propose it like any other field, and searching for "à vérifier" lists them (French only for now) (#140).
|
||||
|
||||
### Fixes and maintenance
|
||||
|
||||
- Memory thumbnails around a portrait are cropped instead of stretched to a square (#142).
|
||||
- DOMPurify 3.4.17, pulled in by posthog-js, for a critical advisory published on 2026-10-23 (GHSA-cg2g-xh64-v4q7) (#139).
|
||||
- Minor dependency updates for the app, the API and the landing page (#133, #134, #136).
|
||||
|
||||
## 1.3.0 (2026-10-21)
|
||||
|
||||
### Memories from Immich
|
||||
|
||||
- Admins with Immich configured can add photos and videos from their library, from a person's memories or when adding a moment. Search by context, filter by photos or videos or by face, open a larger preview and pick several at once (#103 by @Askrosm, #128).
|
||||
- Photos come in as Immich's preview, so iPhone HEIC pictures work, and downloads stop as soon as they pass the size limit (#103).
|
||||
- Several memories picked at once are added in one go, each titled from its file name (#128).
|
||||
|
||||
## 1.2.1 (2026-10-21)
|
||||
|
||||
### Fixes
|
||||
|
||||
- Clicking a person without a photo opens their profile again. The file picker only opens from "+ photo" in edit mode (#124, reported by @coutadeurf, #125).
|
||||
- GEDCOM export stays valid 5.5.1. Sex "other" is written as `SEX U`, and `SEX X` is still read on import (#126).
|
||||
|
||||
### Self-hosting
|
||||
|
||||
- With `PASSWORD_LOGIN=false`, an account that had a password and was linked to OIDC can delete itself by retyping its email after a recent sign-in (#126).
|
||||
- An email already linked to an OIDC identity can't be claimed by a different subject at the provider (#126).
|
||||
- HEIC and AVIF files are recognised as images instead of video, and are refused cleanly until they can be converted (#126).
|
||||
|
||||
## 1.2.0 (2026-10-20)
|
||||
|
||||
### Tree layout
|
||||
|
||||
- Rows follow the kinship generation from the tree's starting person: spouses on the same row, parents one row up, children one row down. A shorter branch married into a deeper one no longer sits several rows too high (#67, reported by @SpaceOptimist, #111).
|
||||
- One tree, never islands. An in-law family attaches to its child at the end of the sibling row, never between two siblings, and each union of a remarriage sits above its own children (#105, #116).
|
||||
- In-law families wider than a screen open in their own tab, the same tree drawn from the spouse. A pill above the spouse leads there and back, and tabs with the same name show the couple's first names. Search opens the tab holding the person. Tree settings can turn tabs off (#116, #81 reported by @coutadeurf).
|
||||
- Lines between families are full lines when they cross no other family, with one trunk per sibling row (#83, #90).
|
||||
|
||||
### People
|
||||
|
||||
- Sex can be set to female, male or other, and is unspecified by default. Relationship names follow it in French and English, with neutral or double forms when unknown. GEDCOM `SEX X` is read and written (#114, suggested by @Arc676, #118).
|
||||
- Nicknames show under the name in the tree and the profile (#85). The last name is optional and an unknown first name can be ticked (#87, #89).
|
||||
- Profiles: pills for facts, place of death, adoption, autosave when leaving, a cleared field stays cleared, close by swiping down on phones (#91, #93, #98, #101, #106).
|
||||
- Portraits can be cropped with the full photo kept, in a round or square frame, and "+ photo" opens the picker right away (#95, #108, #109). Admins can edit a memory (#94).
|
||||
|
||||
### Sharing and family
|
||||
|
||||
- Guests can propose changes with the pencil, and the owner sees pending proposals on their avatar as soon as the tree opens (#96, #121).
|
||||
- A simpler start page with two choices, one door for shared trees, and a clearer login (#86, #88, #92).
|
||||
- The bottom bar is one pill with Add or correct and the account menu (#100, #104, #107). Search results can be tapped in edit mode on phones (#110).
|
||||
|
||||
### Self-hosting
|
||||
|
||||
- `ALLOW_REGISTRATION=false` closes sign-up. Existing accounts log in and the first account of an empty instance is still allowed (#113, suggested by @milan616, #117).
|
||||
- OIDC login (experimental) with `OIDC_ISSUER`, `OIDC_CLIENT_ID`, `OIDC_CLIENT_SECRET` and `OIDC_REDIRECT_URI`. An existing account is linked by verified email only, and never an account that has a password (sign-up does not verify the address). `PASSWORD_LOGIN=false` turns passwords off (#115, suggested by @Arc676, #122).
|
||||
|
||||
### Fixes and maintenance
|
||||
|
||||
- GEDCOM import in transactions and much faster on large files, backups restore tested in CI, and other points from the 18/10 audit (#97). A union without a date sits at its logical place in the Life tab (#102).
|
||||
- Mobile: separated parents drawn as a dotted line, lighter edit bar, dates on the number pad (#82).
|
||||
- Eleven unused interface modules removed (#119).
|
||||
|
||||
## 1.1.0 (2026-10-17)
|
||||
|
||||
### Life tab
|
||||
|
||||
- Each profile has a new Life tab, a timeline of the person's life. Birth, marriages and death are the milestones, other events sit between them with their place and the person's age, and the close family the tree already knows (children and siblings born, parents, partner or a child dying) shows in grey. A profile with no recorded event still gets a timeline. Sources stay folded until clicked.
|
||||
- Admins add a moment from the bottom of the tab with what, when (a year, "about"), where, and files. Tapping a moment edits or deletes it.
|
||||
- A moment can carry several files of any kind, photos, videos, recordings or documents such as a birth record as a PDF. New files join the person's memories, and existing memories can be picked instead.
|
||||
- Birth, marriage and death accept their own documents, source and note.
|
||||
- Family members with the sharing link can propose a moment. It waits for the owner's review with its files, in the same proposal, and shows once accepted.
|
||||
|
||||
### Dates
|
||||
|
||||
- Date fields take a year alone (1950) or a full date, and a year alone reads "1950" instead of "1 January 1950" (#77, reported by @Akasiek).
|
||||
- A person can be marked as deceased without a date. The tree shows "1908–?" and the profile "Date unknown" (#77).
|
||||
- Dates imported as "about", "before", "between" or "from … to" keep their wording, and editing a date by hand drops it.
|
||||
|
||||
### GEDCOM import and export
|
||||
|
||||
- A zip holding the .ged file and its photos (or a GEDZIP .gdz) imports in one go. Portraits and other files are matched with the paths the GEDCOM cites, with no folder to pick.
|
||||
- Life events are imported and exported (baptism, occupations, residences, military service, custom events, divorce…), with place, notes and sources. Republican calendar dates, adoptions (`PEDI adopted`), nicknames and `1 DEAT Y` are read too. An import then an export keeps them.
|
||||
- Files cited by the GEDCOM, under a person, an event, a source or a family, become memories with their title and source (#59, reported by @zycker). Heredis places ("Town,INSEE code,département,…") are cleaned up, at import and for trees already imported.
|
||||
- All notes are kept, shared notes included, and dates are read in full instead of by year.
|
||||
|
||||
### Family
|
||||
|
||||
- Immich face recognition can fill portraits from an Immich server, set up in Settings > Advanced (#58 by @coutadeurf).
|
||||
- Siblings can be reordered by dragging one past another in edit mode, or with the arrows on the profile (#60 by @py5932). A new child goes after its siblings.
|
||||
|
||||
### First photos
|
||||
|
||||
- Tree creation offers "I already have a tree": the .ged file is imported right away, without creating a "you" entry that would end up duplicated.
|
||||
- GEDCOM import reads the photos each person had in the original software (`OBJE` / `FILE`, inline or by reference, primary photo first). After an import, the owner picks the folder where those photos live and Parenthèse places each portrait by file name. Paths stay on the device, nothing is stored on the server.
|
||||
- After an import, a window suggests five faces to start with: the close family of the person marked "Me", otherwise the most recent generations.
|
||||
- For the owner, an empty portrait invites a photo: the empty frame on a profile is a button outside edit mode, and hovering an empty portrait in the tree shows "+ photo".
|
||||
- Phone photos over 5 MB are scaled down to 2000 px before upload instead of being refused.
|
||||
- Owner portrait uploads are limited to 120 per minute (was 30), still within the tree's storage quota.
|
||||
- Anonymous events: `gedcom_imported`, `portraits_bulk_placed`, `portrait_added` (rounded counts, no names, paths or tree address).
|
||||
|
||||
### Fixes
|
||||
|
||||
- Docker: on a first `docker compose up`, the API now gets 120 s to run its migrations before its health check counts (was 30 s). The web container waits for a healthy API and used to give up, so it had to be started again by hand.
|
||||
- Children of a family with only one known parent (common in GEDCOM files) are linked to that parent, under a single "Unknown" partner, instead of floating in the tree without a link.
|
||||
- Importing a GEDCOM file into a tree that already holds it no longer duplicates everyone: people with the same first name, last name, birth and death dates are reused, and existing unions and parent links are kept.
|
||||
- Parents no longer show "(null)" next to their names when the union has no type.
|
||||
|
||||
### Dependencies
|
||||
|
||||
- Grouped minor and patch updates for the app, the API and the landing, and GitHub Actions upload-artifact 7 and setup-node 7.
|
||||
|
||||
## 1.0.3 (2026-10-10)
|
||||
|
||||
### Self-hosting
|
||||
|
||||
- Single-container image `ghcr.io/iliesallali/parenthese-aio` (PostgreSQL, API and front end), for Unraid and NAS systems that install one container per app. It needs no configuration: the database, its password and the session key are created in `/data` on first start. Tested in CI by a fresh start, a restart and the smoke test.
|
||||
- The `parenthese-web` image reads the API address from `API_UPSTREAM` (`api:4000` by default, unchanged for existing installs). Set it when the name `api` is already taken on the Docker network, for example on Umbrel where apps share one network.
|
||||
|
||||
## 1.0.2 (2026-10-09)
|
||||
|
||||
### Self-hosting
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
# Parenthèse en un seul conteneur : PostgreSQL, API et front servi par nginx. Contexte de build : la racine du dépôt.
|
||||
# Pour les systèmes qui installent une application par conteneur (Unraid, NAS). docker-compose.yml reste
|
||||
# l'installation de référence, avec un conteneur par service.
|
||||
#
|
||||
# docker run -d --name parenthese -p 8080:80 -v parenthese-data:/data ghcr.io/iliesallali/parenthese-aio
|
||||
#
|
||||
# Tout ce qui doit survivre à une mise à jour vit dans /data : base (postgres/), photos et vidéos (media/),
|
||||
# secrets générés au premier démarrage (secrets/). Voir deploy/aio/entrypoint.sh.
|
||||
|
||||
# Étape 1 : API (mêmes étapes que backend/Dockerfile).
|
||||
FROM node:24-bookworm-slim AS api-build
|
||||
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends openssl ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY backend/package.json backend/package-lock.json ./
|
||||
RUN npm ci --no-audit --no-fund
|
||||
|
||||
COPY backend/prisma ./prisma
|
||||
COPY backend/prisma.config.ts backend/tsconfig.json ./
|
||||
COPY backend/src ./src
|
||||
RUN npx prisma generate
|
||||
RUN npm run build
|
||||
|
||||
|
||||
# Étape 2 : front (mêmes étapes que Dockerfile.web).
|
||||
FROM node:24-alpine AS web-build
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY frontend/package.json frontend/package-lock.json ./
|
||||
RUN npm ci
|
||||
|
||||
COPY frontend/ ./
|
||||
|
||||
ENV VITE_API_BASE_URL=""
|
||||
RUN npm run build
|
||||
|
||||
|
||||
# Étape 3 : image finale.
|
||||
FROM node:24-bookworm-slim
|
||||
|
||||
# postgresql-common d'abord, pour qu'il ne crée pas de base par défaut à l'installation de PostgreSQL :
|
||||
# la base vit dans /data et naît au premier démarrage.
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends postgresql-common \
|
||||
&& sed -i 's/^#\?\s*create_main_cluster.*/create_main_cluster = false/' /etc/postgresql-common/createcluster.conf \
|
||||
&& apt-get install -y --no-install-recommends postgresql-15 nginx openssl ca-certificates tini \
|
||||
&& rm -rf /var/lib/apt/lists/* \
|
||||
&& rm -f /etc/nginx/sites-enabled/default \
|
||||
&& mkdir -p /run/postgresql && chown postgres:postgres /run/postgresql
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY backend/package.json backend/package-lock.json ./
|
||||
RUN npm ci --omit=dev --no-audit --no-fund \
|
||||
&& npm cache clean --force
|
||||
|
||||
# CLI Prisma à part, à la version du package-lock (voir backend/Dockerfile).
|
||||
RUN PRISMA_VERSION="$(node -p "require('./package-lock.json').packages['node_modules/prisma'].version")" \
|
||||
&& mkdir -p /opt/prisma \
|
||||
&& cd /opt/prisma \
|
||||
&& echo '{"private":true}' > package.json \
|
||||
&& npm install --no-audit --no-fund "prisma@${PRISMA_VERSION}" \
|
||||
&& npm cache clean --force
|
||||
|
||||
COPY backend/prisma ./prisma
|
||||
COPY backend/prisma.config.ts ./
|
||||
COPY --from=api-build /app/dist ./dist
|
||||
|
||||
# nginx : la configuration du conteneur web de compose, l'API étant ici sur la même machine.
|
||||
COPY deploy/nginx.docker.conf /etc/nginx/conf.d/default.conf
|
||||
RUN sed -i 's|http://api:4000|http://127.0.0.1:4000|g' /etc/nginx/conf.d/default.conf \
|
||||
&& ! grep -q 'api:4000' /etc/nginx/conf.d/default.conf
|
||||
COPY --from=web-build /app/dist /usr/share/nginx/html
|
||||
|
||||
COPY deploy/aio/entrypoint.sh /usr/local/bin/parenthese-aio
|
||||
RUN chmod 755 /usr/local/bin/parenthese-aio
|
||||
|
||||
ENV NODE_ENV=production \
|
||||
CHECKPOINT_DISABLE=1 \
|
||||
PATH=/opt/prisma/node_modules/.bin:/usr/lib/postgresql/15/bin:$PATH
|
||||
|
||||
VOLUME /data
|
||||
EXPOSE 80
|
||||
|
||||
HEALTHCHECK --interval=15s --timeout=5s --start-period=60s --retries=5 \
|
||||
CMD node -e "fetch('http://127.0.0.1/health').then((r) => process.exit(r.ok ? 0 : 1)).catch(() => process.exit(1))"
|
||||
|
||||
ENTRYPOINT ["tini", "--", "/usr/local/bin/parenthese-aio"]
|
||||
@@ -0,0 +1,21 @@
|
||||
# Contexte de build de Dockerfile.aio (BuildKit lit ce fichier à la place de .dockerignore) :
|
||||
# l'API, le front, la configuration nginx et le script de démarrage
|
||||
*
|
||||
!backend
|
||||
!frontend
|
||||
!deploy/nginx.docker.conf
|
||||
!deploy/aio
|
||||
backend/node_modules
|
||||
backend/dist
|
||||
backend/src/generated
|
||||
backend/.local
|
||||
backend/storage
|
||||
backend/test
|
||||
backend/openapi
|
||||
backend/.env
|
||||
backend/.env.*
|
||||
frontend/node_modules
|
||||
frontend/dist
|
||||
frontend/.env
|
||||
frontend/.env.*
|
||||
**/*.log
|
||||
+8
-1
@@ -19,7 +19,14 @@ RUN npm run build
|
||||
|
||||
FROM nginx:1.30-alpine
|
||||
|
||||
COPY deploy/nginx.docker.conf /etc/nginx/conf.d/default.conf
|
||||
# Adresse de l'API lue au démarrage du conteneur, `api:4000` par défaut (le service de docker-compose.yml).
|
||||
# À changer quand le nom `api` est déjà pris sur le réseau, comme sur Umbrel où les apps partagent un réseau.
|
||||
# L'image nginx passe les fichiers de /etc/nginx/templates par envsubst et n'y remplace que les variables
|
||||
# d'environnement définies : $host, $uri et les autres variables de nginx restent telles quelles.
|
||||
ENV API_UPSTREAM=api:4000
|
||||
COPY deploy/nginx.docker.conf /etc/nginx/templates/default.conf.template
|
||||
RUN sed -i 's|http://api:4000|http://${API_UPSTREAM}|g' /etc/nginx/templates/default.conf.template \
|
||||
&& ! grep -q 'api:4000' /etc/nginx/templates/default.conf.template
|
||||
COPY --from=build /app/dist /usr/share/nginx/html
|
||||
|
||||
EXPOSE 80
|
||||
+52
-4
@@ -53,10 +53,48 @@ docker compose up -d
|
||||
|
||||
Le premier démarrage télécharge les images (ou les construit depuis les sources si elles sont introuvables), applique les migrations de la base, puis sert l'application sur [http://localhost](http://localhost). Créez votre compte depuis l'écran d'accueil : le premier compte est un compte comme les autres, il n'y a pas d'administrateur global.
|
||||
|
||||
Trois conteneurs tournent : `db` (PostgreSQL 16), `api` (l'API Node) et `web` (nginx qui sert le front et relaie l'API). Seul `web` est exposé, sur le port choisi par `WEB_PORT` (80 par défaut). Si ce port est déjà pris, changez `WEB_PORT` dans `.env` et adaptez `CORS_ORIGIN` en conséquence.
|
||||
Trois conteneurs tournent : `db` (PostgreSQL 16), `api` (l'API Node) et `web` (nginx qui sert le front et relaie l'API). Seul `web` est exposé, sur le port choisi par `WEB_PORT` (80 par défaut). Si ce port est déjà pris, changez `WEB_PORT` dans `.env` et adaptez `CORS_ORIGIN` en conséquence. Le conteneur `web` trouve l'API à `api:4000` ; si vous lancez les images sous d'autres noms de service, donnez `API_UPSTREAM` à `web` (par exemple `API_UPSTREAM=monapi:4000`).
|
||||
|
||||
Pour ouvrir l'instance à la famille depuis Internet, placez un reverse proxy HTTPS devant le port `web` (Caddy, Traefik, nginx) et mettez l'adresse publique dans `CORS_ORIGIN`, par exemple `https://arbre.votre-domaine.fr`.
|
||||
|
||||
Pour qu'une personne qui tombe sur l'adresse ne puisse pas s'inscrire et y créer ses arbres, mettez `ALLOW_REGISTRATION=false` dans `.env`, puis lancez `docker compose up -d`. Les comptes existants se connectent et créent leurs arbres comme avant, la famille ouvre toujours les arbres partagés avec le lien et le mot de passe, et l'application ne propose plus de créer de compte. Une instance sans aucun compte accepte quand même le premier, la variable peut donc être posée avant le tout premier démarrage : créez votre compte tout de suite, avant de donner l'adresse.
|
||||
|
||||
Votre instance ne pousse personne à y créer un compte. Sur app.parenthese.io, l'instance hébergée, l'application invite à créer son propre arbre : la famille qui ouvre un arbre partagé trouve « Faire le mien » dans le menu Ajouter, les messages de la démo proposent l'inscription, et du 1er décembre au 6 janvier le message d'invitation parle de Noël. Ces invitations sont éteintes par défaut. Pour les allumer, mettez `SIGNUP_PROMPTS=true` dans `.env` (elles restent coupées si l'inscription est fermée).
|
||||
|
||||
#### Chercher quelqu'un dans des sources publiques
|
||||
|
||||
Le menu « + » propose « Quelqu'un ailleurs » : un panneau à droite de l'arbre où l'on tape un nom pour voir ce que les sources publiques disent de cette personne. Les liens vers des sites sans recherche interrogeable d'ici (presse ancienne sur Gallica, registres matricules sur FranceArchives, Geneanet, FamilySearch et quelques autres, la France d'abord) marchent toujours : votre navigateur ouvre le site avec le nom déjà tapé, et rien ne passe par le serveur.
|
||||
|
||||
Le serveur peut aussi interroger lui-même deux sources et afficher leurs résultats dans le panneau. Elles restent éteintes tant que vous ne les nommez pas dans `.env` :
|
||||
|
||||
```
|
||||
# deces : décès en France depuis 1970 (fichier de l'INSEE, cherché par matchID)
|
||||
# wikitree : profils publics de WikiTree
|
||||
SEARCH_SOURCES=deces,wikitree
|
||||
# Facultatif, gratuit sur deces.matchid.io : sans clé, les recherches s'arrêtent après une centaine
|
||||
MATCHID_TOKEN=
|
||||
```
|
||||
|
||||
Seuls le prénom, le nom et l'année de naissance quittent le serveur, et le panneau l'écrit à côté de chaque source. Un résultat ajouté à l'arbre ne remplit que les champs vides, passe la personne « à vérifier » et garde le lien de la source dans sa note. Le propriétaire de l'arbre ajoute directement ; la famille voit les résultats et les liens. Une clé matchID vaut 30 jours : renouvelez-la depuis votre compte matchID.
|
||||
|
||||
#### Connexion par votre fournisseur d'identité (OIDC)
|
||||
|
||||
*Expérimental dans la 1.2.0 : testé contre un fournisseur OpenID certifié, vos retours sur de vraies installations sont les bienvenus dans les issues.*
|
||||
|
||||
Parenthèse peut confier la connexion à un fournisseur OpenID Connect que vous faites déjà tourner (Authentik, Authelia, Keycloak, Pocket ID, Zitadel…) : la famille garde un seul compte et sa double authentification. Créez chez lui une application OIDC (client confidentiel, flux « authorization code ») dont l'adresse de retour est l'adresse publique de Parenthèse suivie de `/auth/oidc/callback`, puis renseignez dans `.env` :
|
||||
|
||||
```bash
|
||||
OIDC_ISSUER=https://auth.votre-domaine.fr/application/o/parenthese/ # exactement comme le fournisseur l'annonce
|
||||
OIDC_CLIENT_ID=parenthese
|
||||
OIDC_CLIENT_SECRET=... # vide pour un client public (PKCE seul)
|
||||
OIDC_REDIRECT_URI=https://arbre.votre-domaine.fr/auth/oidc/callback
|
||||
OIDC_PROVIDER_NAME=Authentik # nom affiché sur le bouton
|
||||
```
|
||||
|
||||
L'écran de connexion affiche alors « Se connecter avec Authentik ». À la première connexion, Parenthèse relie le compte du fournisseur au compte Parenthèse qui a le même email, ou en crée un si `ALLOW_REGISTRATION` le permet. Inscription fermée, le fournisseur ne connecte que les personnes qui ont déjà un compte (le premier compte d'une instance vide reste accepté). Un email n'est pris en compte que si le fournisseur le dit vérifié (`email_verified`) ; `OIDC_REQUIRE_VERIFIED_EMAIL=false` lève ce contrôle, pour un fournisseur qui ne l'envoie pas et où personne ne choisit lui-même son adresse. Une fois relié, un compte suit l'identifiant de l'utilisateur chez le fournisseur, pas son email.
|
||||
|
||||
`PASSWORD_LOGIN=false` retire les mots de passe Parenthèse : la connexion passe par le fournisseur seulement (l'API refuse de démarrer sans `OIDC_ISSUER`). Un compte créé par le fournisseur n'a pas de mot de passe ; pour le supprimer, on retape son email. `OIDC_SCOPES` (par défaut `openid email profile`) et `OIDC_APP_URL` (où l'app s'ouvre après la connexion, par défaut l'origine de `OIDC_REDIRECT_URI`) se changent rarement.
|
||||
|
||||
Une instance auto-hébergée n'envoie aucune mesure d'audience : le suivi d'usage de parenthese.io ne s'active que si une clé PostHog est fournie au build, ce que cette configuration ne fait pas.
|
||||
|
||||
Les liens d'aide et de vie privée de l'application mènent à parenthese.io. Pour pointer vers vos propres pages, renseignez `VITE_HELP_URL` et `VITE_PRIVACY_URL` quand vous construisez vous-même le front (voir `frontend/.env.example`).
|
||||
@@ -69,7 +107,17 @@ docker compose ps # état des conteneurs
|
||||
docker compose down # arrêt, les données sont conservées
|
||||
```
|
||||
|
||||
Pour vérifier qu'une installation fonctionne de bout en bout, lancez `bash tools/docker-smoke.sh http://localhost` (avec le port si `WEB_PORT` n'est pas 80). Le script a besoin de `curl` et `jq`. Il passe par le port web comme un navigateur : page d'accueil, santé de l'API, création d'un compte, connexion, création puis suppression d'un arbre de test. Le compte de test (`smoke-...@example.com`) reste en base.
|
||||
Pour vérifier qu'une installation fonctionne de bout en bout, lancez `bash tools/docker-smoke.sh http://localhost` (avec le port si `WEB_PORT` n'est pas 80). Le script a besoin de `curl` et `jq`. Il passe par le port web comme un navigateur : page d'accueil, santé de l'API, création d'un compte, connexion, création puis suppression d'un arbre de test. Le compte de test (`smoke-...@example.com`) reste en base. Avec `ALLOW_REGISTRATION=false`, le script s'arrête à la création du compte, c'est le refus attendu.
|
||||
|
||||
### Un seul conteneur (Unraid, NAS)
|
||||
|
||||
Pour les systèmes qui installent un conteneur par application, `ghcr.io/iliesallali/parenthese-aio` fait tourner la base, l'API et le front ensemble :
|
||||
|
||||
```bash
|
||||
docker run -d --name parenthese --restart unless-stopped -p 8080:80 -v /chemin/vers/appdata/parenthese:/data ghcr.io/iliesallali/parenthese-aio
|
||||
```
|
||||
|
||||
Rien à remplir. Au premier démarrage, le conteneur crée dans `/data` la base, son mot de passe et la clé des sessions, puis les réutilise. Les photos et vidéos vont dans `/data/media`. Pour fermer la création de compte, ajoutez `-e ALLOW_REGISTRATION=false` (sur Unraid, « Allow registration » à `false`). Sauvegardez tout le dossier `/data` conteneur arrêté, ou exportez la base pendant qu'il tourne avec `docker exec parenthese runuser -u postgres -- pg_dump parenthese > parenthese.sql`. La base est ici PostgreSQL 15, l'installation compose utilise la 16.
|
||||
|
||||
### Où sont les données
|
||||
|
||||
@@ -89,7 +137,7 @@ docker run --rm -v parenthese_media:/data -v "$PWD":/backup alpine tar -czf /bac
|
||||
|
||||
La première commande sauvegarde la base. Elle contient les personnes, leurs liens, les comptes et les contributions, et elle sait à qui appartient chaque photo, vidéo ou enregistrement. La seconde sauvegarde les fichiers eux-mêmes. Il faut les deux. Restaurez la base seule et les souvenirs pointent vers des fichiers disparus. Restaurez l'archive seule et vous avez un dossier de fichiers rattachés à personne. L'export GEDCOM n'est pas une sauvegarde non plus. Il sert à emmener l'arbre vers un autre logiciel de généalogie et laisse de côté les médias et les annotations.
|
||||
|
||||
Adaptez `-U parenthese` et le nom de base si vous avez changé `POSTGRES_USER` ou `POSTGRES_DB`. Pour restaurer la base : `docker compose exec -T db pg_restore -U parenthese -d parenthese --clean < parenthese-db-AAAA-MM-JJ.dump`, puis décompressez l'archive des médias dans le volume avec la même commande `docker run`, `tar -xzf` à la place de `-czf`.
|
||||
Adaptez `-U parenthese` et le nom de base si vous avez changé `POSTGRES_USER` ou `POSTGRES_DB`. Pour restaurer la base : `docker compose exec -T db pg_restore -U parenthese -d parenthese --clean --if-exists < parenthese-db-AAAA-MM-JJ.dump`, puis décompressez l'archive des médias dans le volume avec la même commande `docker run`, `tar -xzf` à la place de `-czf`.
|
||||
|
||||
Le script `deploy/backup.sh` fait la même chose (dump PostgreSQL, archive des médias, sommes de contrôle, rotation, envoi S3 optionnel) pour une installation sans Docker : il lit `backend/.env` et a besoin de `pg_dump` sur la machine. Ses réglages passent par les variables `BACKUP_ROOT`, `BACKUP_RETENTION_DAYS` et `BACKUP_S3_BUCKET`.
|
||||
|
||||
@@ -101,7 +149,7 @@ docker compose pull && docker compose up -d
|
||||
|
||||
`latest` suit la branche main. Pour rester sur une version, renseignez `PARENTHESE_VERSION` dans `.env` (par exemple `1.0`). Depuis un clone, `git pull && docker compose up -d --build` reconstruit depuis les sources.
|
||||
|
||||
Les migrations de base de données s'appliquent toutes seules au démarrage de l'API. Faites une sauvegarde avant, par habitude.
|
||||
Les migrations de base de données s'appliquent toutes seules au démarrage de l'API, et une migration ne se défait pas. Lancez les deux commandes de sauvegarde ci-dessus avant chaque mise à jour. L'image tout-en-un le fait seule : avant d'appliquer une migration, elle copie la base dans `/data/backups` et garde les cinq dernières copies.
|
||||
|
||||
## Développer
|
||||
|
||||
|
||||
@@ -4,12 +4,12 @@
|
||||
|
||||
A family tree you explore like a map, with the photos, videos and voices of each person. Share it with one link and a password: relatives look around without an account and add what they know.
|
||||
|
||||
Website: [parenthese.io/en](https://parenthese.io/en/) · Demo, no account needed: [app.parenthese.io](https://app.parenthese.io/?lang=en) · [Version française](README.fr.md)
|
||||
Website: [parenthese.io/en](https://parenthese.io/en/) · Demo, no account needed: [app.parenthese.io](https://app.parenthese.io/?demo&lang=en) · [Version française](README.fr.md)
|
||||
|
||||

|
||||
|
||||
- **License:** source-available under [PolyForm Noncommercial 1.0.0](LICENSE). Free to read, modify and self-host for non-commercial use. Not an OSI open source license, see [License](#license).
|
||||
- **How it was made:** designed and directed by Ilies Allali. Most of the code was written with Claude Code (Anthropic), then reviewed and tested before being published.
|
||||
- **How it was made:** designed and directed by [Ilies Allali](https://iliesallali.design/). Most of the code was written with Claude Code (Anthropic), then reviewed and tested before being published.
|
||||
|
||||
## What it does
|
||||
|
||||
@@ -59,10 +59,50 @@ docker compose up -d
|
||||
|
||||
The first start downloads the images (or builds them from the source when they can't be pulled), applies the database migrations, then serves the app on [http://localhost](http://localhost). Create your account from the home screen. The first account is an account like any other, there is no global administrator.
|
||||
|
||||
Three containers run: `db` (PostgreSQL 16), `api` (the Node API) and `web` (nginx, which serves the front end and proxies the API). Only `web` is exposed, on the port set by `WEB_PORT` (80 by default). If that port is taken, change `WEB_PORT` in `.env` and update `CORS_ORIGIN` to match.
|
||||
Three containers run: `db` (PostgreSQL 16), `api` (the Node API) and `web` (nginx, which serves the front end and proxies the API). Only `web` is exposed, on the port set by `WEB_PORT` (80 by default). If that port is taken, change `WEB_PORT` in `.env` and update `CORS_ORIGIN` to match. The `web` container finds the API at `api:4000`; if you run the images under other service names, set `API_UPSTREAM` on `web` (for example `API_UPSTREAM=myapi:4000`).
|
||||
|
||||
To open the instance to your family over the Internet, put an HTTPS reverse proxy in front of the `web` port (Caddy, Traefik, nginx) and set the public address in `CORS_ORIGIN`, for example `https://tree.your-domain.com`.
|
||||
|
||||
So that people who come across the address can't sign up and start their own trees, set `ALLOW_REGISTRATION=false` in `.env`, then run `docker compose up -d`. Existing accounts keep signing in and creating trees, relatives still open shared trees with the link and password, and the app no longer offers to create an account. An instance with no account at all still accepts the first one, so the variable can be set before the very first start: create your own account right away, before you give out the address.
|
||||
|
||||
Your instance doesn't push anyone to create an account. On app.parenthese.io, the hosted instance, the app suggests starting your own tree: relatives who open a shared tree find « Faire le mien » ("Make my own") in the Add menu, the demo's messages offer to sign up, and from December 1 to January 6 the invitation message mentions Christmas. These prompts are off by default. To turn them on, set `SIGNUP_PROMPTS=true` in `.env` (they stay off while registration is closed).
|
||||
|
||||
#### Search for someone in public records
|
||||
|
||||
The "+" menu offers "Someone elsewhere": a panel on the right of the tree where you type a name and see what public records hold about that person. Links to sites without a search we can query from here (old newspapers on Gallica, military registers on FranceArchives, Geneanet, FamilySearch and a few others, France first) always work: your browser opens the site with the name already typed in, and nothing goes through the server.
|
||||
|
||||
The server can also query two sources itself and show the results in the panel. They stay off until you list them in `.env`:
|
||||
|
||||
```
|
||||
# deces: deaths in France since 1970 (INSEE death records, searched through matchID)
|
||||
# wikitree: WikiTree public profiles
|
||||
SEARCH_SOURCES=deces,wikitree
|
||||
# Optional, free from deces.matchid.io: anonymous searches stop after about a hundred
|
||||
MATCHID_TOKEN=
|
||||
```
|
||||
|
||||
Only the first name, last name and birth year leave the server, and the panel says so next to each source. A result added to the tree only fills empty fields, marks the person as needing checking and keeps the source link in their note. The tree owner adds directly; relatives see the results and the links. A matchID key is valid for 30 days: renew it from your matchID account.
|
||||
|
||||
#### Sign in with your identity provider (OIDC)
|
||||
|
||||
*Used with Pocket ID on a real setup (#153).*
|
||||
|
||||
Parenthèse can hand sign-in to an OpenID Connect provider you already run (Authentik, Authelia, Keycloak, Pocket ID, Zitadel…), so your family reuses one account and its two-factor settings. Create an OIDC application (confidential client, authorization code flow) whose redirect URI is the public address of Parenthèse followed by `/auth/oidc/callback`, then set in `.env`:
|
||||
|
||||
```bash
|
||||
OIDC_ISSUER=https://auth.your-domain.com/application/o/parenthese/ # exactly as the provider announces it
|
||||
OIDC_CLIENT_ID=parenthese
|
||||
OIDC_CLIENT_SECRET=... # empty for a public client (PKCE only)
|
||||
OIDC_REDIRECT_URI=https://tree.your-domain.com/auth/oidc/callback
|
||||
OIDC_PROVIDER_NAME=Authentik # shown on the button
|
||||
```
|
||||
|
||||
The `api` container talks to the provider itself, to read its configuration and exchange the sign-in code. If your Docker network is marked `internal`, give `api` a network that can reach the provider, not just `web`.
|
||||
|
||||
The sign-in screen then shows "Sign in with Authentik". On a first sign-in, Parenthèse links the provider account to the Parenthèse account with the same email, or creates one when `ALLOW_REGISTRATION` allows it. With registration closed, the provider only signs in people who already have an account (the first account of an empty instance is still accepted). Emails are only trusted when the provider marks them verified (`email_verified`); `OIDC_REQUIRE_VERIFIED_EMAIL=false` lifts that check, for a provider that doesn't send the claim and where nobody picks their own address. Once linked, an account stays tied to the provider's user id, not to the email.
|
||||
|
||||
`PASSWORD_LOGIN=false` removes Parenthèse passwords altogether: sign-in goes through the provider only (the API refuses to start without `OIDC_ISSUER`). Accounts created through the provider have no password; to delete one, its owner types their email instead. Accounts that already have a password are not linked to the provider by email: before switching, each owner opens their account and clicks « Se connecter aussi avec … » ("Also sign in with …"), then signs in with the provider once. `OIDC_SCOPES` (default `openid email profile`) and `OIDC_APP_URL` (where the app opens after sign-in, by default the origin of `OIDC_REDIRECT_URI`) rarely need changing.
|
||||
|
||||
A self-hosted instance sends no analytics. Usage tracking on parenthese.io only turns on when a PostHog key is provided at build time, which this setup does not do.
|
||||
|
||||
The help and privacy links in the app point to parenthese.io. To use your own pages, set `VITE_HELP_URL` and `VITE_PRIVACY_URL` when you build the front end yourself (see `frontend/.env.example`).
|
||||
@@ -75,7 +115,17 @@ docker compose ps # container status
|
||||
docker compose down # stop, data is kept
|
||||
```
|
||||
|
||||
To check that an installation works end to end, run `bash tools/docker-smoke.sh http://localhost` (add the port if `WEB_PORT` is not 80). The script needs `curl` and `jq`. It goes through the web port like a browser: home page, API health, account creation, sign-in, creating then deleting a test tree. The test account (`smoke-...@example.com`) stays in the database.
|
||||
To check that an installation works end to end, run `bash tools/docker-smoke.sh http://localhost` (add the port if `WEB_PORT` is not 80). The script needs `curl` and `jq`. It goes through the web port like a browser: home page, API health, account creation, sign-in, creating then deleting a test tree. The test account (`smoke-...@example.com`) stays in the database. With `ALLOW_REGISTRATION=false` the script stops at account creation, which is the expected refusal.
|
||||
|
||||
### Single container (Unraid, NAS)
|
||||
|
||||
For systems that install one container per app, `ghcr.io/iliesallali/parenthese-aio` runs the database, the API and the front end together:
|
||||
|
||||
```bash
|
||||
docker run -d --name parenthese --restart unless-stopped -p 8080:80 -v /path/to/appdata/parenthese:/data ghcr.io/iliesallali/parenthese-aio
|
||||
```
|
||||
|
||||
There is nothing to fill in. On first start the container creates the database, its password and the session key in `/data`, and reuses them afterwards. Photos and videos go to `/data/media`. To close account creation, add `-e ALLOW_REGISTRATION=false` (on Unraid, set "Allow registration" to `false`). Back up the whole `/data` folder with the container stopped, or dump the database while it runs with `docker exec parenthese runuser -u postgres -- pg_dump parenthese > parenthese.sql`. The database is PostgreSQL 15 here, the compose setup uses 16.
|
||||
|
||||
### Where the data lives
|
||||
|
||||
@@ -95,7 +145,7 @@ docker run --rm -v parenthese_media:/data -v "$PWD":/backup alpine tar -czf /bac
|
||||
|
||||
The first command saves the database. It holds the people, their links, the accounts and the contributions, plus the record of which photo, video or recording belongs to whom. The second saves the files themselves. You need both. Restore only the database and the memories point to files that are gone. Restore only the archive and you get a folder of files with no names attached. The GEDCOM export is not a backup either. It moves the tree to another genealogy program and leaves the media and the annotations behind.
|
||||
|
||||
Adjust `-U parenthese` and the database name if you changed `POSTGRES_USER` or `POSTGRES_DB`. To restore the database, run `docker compose exec -T db pg_restore -U parenthese -d parenthese --clean < parenthese-db-YYYY-MM-DD.dump`, then extract the media archive into the volume with the same `docker run` command, using `tar -xzf` instead of `-czf`.
|
||||
Adjust `-U parenthese` and the database name if you changed `POSTGRES_USER` or `POSTGRES_DB`. To restore the database, run `docker compose exec -T db pg_restore -U parenthese -d parenthese --clean --if-exists < parenthese-db-YYYY-MM-DD.dump`, then extract the media archive into the volume with the same `docker run` command, using `tar -xzf` instead of `-czf`.
|
||||
|
||||
The `deploy/backup.sh` script does the same (PostgreSQL dump, media archive, checksums, rotation, optional S3 upload) for an installation without Docker. It reads `backend/.env` and needs `pg_dump` on the machine. It is configured through the `BACKUP_ROOT`, `BACKUP_RETENTION_DAYS` and `BACKUP_S3_BUCKET` variables.
|
||||
|
||||
@@ -107,7 +157,7 @@ docker compose pull && docker compose up -d
|
||||
|
||||
`latest` follows the main branch. To stay on a version, set `PARENTHESE_VERSION` in `.env` (for example `1.0`). From a clone, `git pull && docker compose up -d --build` builds from the source instead.
|
||||
|
||||
Database migrations apply on their own when the API starts. Make a backup first, as a habit.
|
||||
Database migrations apply on their own when the API starts, and a migration cannot be undone. Run the two backup commands above before each update. The all-in-one image does it by itself: before applying a migration, it copies the database to `/data/backups` and keeps the last five copies.
|
||||
|
||||
## Development
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
node_modules
|
||||
dist
|
||||
src/generated
|
||||
.local
|
||||
storage
|
||||
test
|
||||
|
||||
@@ -6,3 +6,23 @@ JWT_EXPIRES_IN="7d"
|
||||
JWT_TREE_ACCESS_EXPIRES_IN="24h"
|
||||
CORS_ORIGIN="http://localhost:5173,http://localhost:5174,http://localhost:5175,http://localhost:5176"
|
||||
MEDIA_STORAGE_PATH="./storage/media"
|
||||
# Reconnaissance des visages : instances Immich autorisées sur ce serveur, séparées par des
|
||||
# virgules. Entrée « Libellé=https://adresse » ou « https://adresse » (nom d'hôte comme libellé,
|
||||
# donc un libellé si deux instances partagent un nom). Les administrateurs de chaque arbre choisissent
|
||||
# l'instance par son nom et donnent leur propre clé d'API. Sans cette liste, la fonction reste éteinte.
|
||||
IMMICH_ALLOWED_API_URLS=""
|
||||
# Création de compte. À false, seuls les comptes existants se connectent ; une instance sans aucun
|
||||
# compte accepte quand même le premier, celui du propriétaire.
|
||||
ALLOW_REGISTRATION=true
|
||||
# Invitations à créer son propre arbre (famille, démo, message de Noël). Éteintes par défaut, allumées sur
|
||||
# l'instance hébergée.
|
||||
SIGNUP_PROMPTS=false
|
||||
# Connexion par un fournisseur OIDC, éteinte sans OIDC_ISSUER (voir le README). PASSWORD_LOGIN=false retire
|
||||
# les mots de passe Parenthèse.
|
||||
OIDC_ISSUER=""
|
||||
OIDC_CLIENT_ID=""
|
||||
OIDC_CLIENT_SECRET=""
|
||||
OIDC_REDIRECT_URI=""
|
||||
OIDC_PROVIDER_NAME="SSO"
|
||||
OIDC_REQUIRE_VERIFIED_EMAIL=true
|
||||
PASSWORD_LOGIN=true
|
||||
@@ -23,3 +23,27 @@ CORS_ORIGIN="https://arbre.example.org"
|
||||
|
||||
# Dossier des médias envoyés. Un chemin relatif part du dossier backend/.
|
||||
MEDIA_STORAGE_PATH="/var/lib/parenthese/media"
|
||||
|
||||
# Reconnaissance des visages : instances Immich autorisées sur ce serveur, séparées par des
|
||||
# virgules. Entrée « Libellé=https://adresse » ou « https://adresse » (nom d'hôte comme libellé,
|
||||
# donc un libellé si deux instances partagent un nom). Les administrateurs de chaque arbre choisissent
|
||||
# l'instance par son nom et donnent leur propre clé d'API. Sans cette liste, la fonction reste éteinte.
|
||||
IMMICH_ALLOWED_API_URLS=""
|
||||
|
||||
# Panneau « Quelqu'un ailleurs » : sources interrogées par le serveur (deces, wikitree), vide = aucune.
|
||||
# MATCHID_TOKEN : clé gratuite de deces.matchid.io, indispensable au-delà d'une centaine de recherches.
|
||||
SEARCH_SOURCES=""
|
||||
MATCHID_TOKEN=""
|
||||
|
||||
# Création de compte. À false, seuls les comptes existants se connectent ; une instance sans aucun
|
||||
# compte accepte quand même le premier, celui du propriétaire.
|
||||
ALLOW_REGISTRATION=true
|
||||
# Connexion par un fournisseur OIDC, éteinte sans OIDC_ISSUER (voir le README). PASSWORD_LOGIN=false retire
|
||||
# les mots de passe Parenthèse.
|
||||
OIDC_ISSUER=""
|
||||
OIDC_CLIENT_ID=""
|
||||
OIDC_CLIENT_SECRET=""
|
||||
OIDC_REDIRECT_URI=""
|
||||
OIDC_PROVIDER_NAME="SSO"
|
||||
OIDC_REQUIRE_VERIFIED_EMAIL=true
|
||||
PASSWORD_LOGIN=true
|
||||
@@ -3,3 +3,6 @@ dist/
|
||||
.env
|
||||
.local/
|
||||
*.log
|
||||
|
||||
# Client Prisma généré (prisma generate)
|
||||
src/generated/
|
||||
+7
-8
@@ -1,12 +1,12 @@
|
||||
# syntax=docker/dockerfile:1
|
||||
# API Parenthèse (Fastify + Prisma). Contexte de build : le dossier backend/.
|
||||
# Étape 1 : dépendances complètes, client Prisma, compilation TypeScript.
|
||||
# Étape 1 : dépendances complètes, client Prisma (généré dans src/generated), compilation TypeScript.
|
||||
# Étape 2 : image finale avec les seules dépendances de production, plus la CLI Prisma
|
||||
# installée à part (nécessaire à `prisma migrate deploy` au démarrage).
|
||||
|
||||
FROM node:24-bookworm-slim AS build
|
||||
|
||||
# openssl : requis par les moteurs Prisma (cible debian-openssl-3.0.x).
|
||||
# openssl : requis par le moteur de migration de Prisma (cible debian-openssl-3.0.x).
|
||||
RUN apt-get update \
|
||||
&& apt-get install -y --no-install-recommends openssl ca-certificates \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
@@ -14,12 +14,12 @@ RUN apt-get update \
|
||||
WORKDIR /app
|
||||
|
||||
COPY package.json package-lock.json ./
|
||||
COPY prisma ./prisma
|
||||
RUN npm ci --no-audit --no-fund
|
||||
RUN npx prisma generate
|
||||
|
||||
COPY tsconfig.json ./
|
||||
COPY prisma ./prisma
|
||||
COPY prisma.config.ts tsconfig.json ./
|
||||
COPY src ./src
|
||||
RUN npx prisma generate
|
||||
RUN npm run build
|
||||
|
||||
|
||||
@@ -46,10 +46,9 @@ RUN PRISMA_VERSION="$(node -p "require('./package-lock.json').packages['node_mod
|
||||
&& npm install --no-audit --no-fund "prisma@${PRISMA_VERSION}" \
|
||||
&& npm cache clean --force
|
||||
|
||||
# Client Prisma généré à l'étape 1 (même image de base, même cible de moteur).
|
||||
COPY --from=build /app/node_modules/.prisma ./node_modules/.prisma
|
||||
# Schéma + migrations : indispensables à `prisma migrate deploy`.
|
||||
# Schéma, migrations et configuration : indispensables à `prisma migrate deploy`. Le client Prisma est compilé dans dist.
|
||||
COPY prisma ./prisma
|
||||
COPY prisma.config.ts ./
|
||||
COPY --from=build /app/dist ./dist
|
||||
|
||||
RUN mkdir -p /app/storage/media && chown -R node:node /app/storage
|
||||
|
||||
@@ -289,6 +289,27 @@ components:
|
||||
displayOrder:
|
||||
type: integer
|
||||
required: [parentPersonId, childPersonId]
|
||||
ChildrenOrderRequest:
|
||||
type: object
|
||||
required: [order]
|
||||
properties:
|
||||
order:
|
||||
type: array
|
||||
minItems: 2
|
||||
maxItems: 200
|
||||
description: Children in the wanted order, each with the links that attach it to its parents
|
||||
items:
|
||||
type: object
|
||||
required: [childId, linkIds]
|
||||
properties:
|
||||
childId:
|
||||
type: string
|
||||
linkIds:
|
||||
type: array
|
||||
minItems: 1
|
||||
maxItems: 4
|
||||
items:
|
||||
type: string
|
||||
PatchParentChildLinkRequest:
|
||||
type: object
|
||||
properties:
|
||||
@@ -517,6 +538,89 @@ components:
|
||||
required: [decision]
|
||||
|
||||
paths:
|
||||
/auth/options:
|
||||
get:
|
||||
tags: [Auth]
|
||||
summary: What the sign-in screen can offer on this instance
|
||||
responses:
|
||||
'200':
|
||||
description: Instance options
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
registration:
|
||||
type: boolean
|
||||
description: false when ALLOW_REGISTRATION=false and the instance already has an account
|
||||
passwordLogin:
|
||||
type: boolean
|
||||
description: false when PASSWORD_LOGIN=false (sign-in through the OIDC provider only)
|
||||
oidc:
|
||||
type: object
|
||||
nullable: true
|
||||
description: OIDC provider shown on the sign-in screen, null when OIDC_ISSUER is not set
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
signupPrompts:
|
||||
type: boolean
|
||||
description: true when SIGNUP_PROMPTS=true and accounts can be created. The app then suggests starting one's own tree to relatives and demo visitors
|
||||
required: [registration, passwordLogin, oidc, signupPrompts]
|
||||
|
||||
/auth/oidc/start:
|
||||
get:
|
||||
tags: [Auth]
|
||||
summary: Start an OIDC sign-in (browser navigation)
|
||||
description: Sets a signed, httpOnly cookie holding state, nonce and PKCE verifier, then redirects to the provider. Only exists when OIDC_ISSUER is set.
|
||||
parameters:
|
||||
- name: returnTo
|
||||
in: query
|
||||
required: false
|
||||
schema:
|
||||
type: string
|
||||
description: Either / or /arbre/<slug>, anything else falls back to /
|
||||
responses:
|
||||
'302':
|
||||
description: Redirect to the provider, or back to the app with "#oidc_error=oidc_unavailable"
|
||||
|
||||
/auth/oidc/callback:
|
||||
get:
|
||||
tags: [Auth]
|
||||
summary: Provider redirect target (browser navigation)
|
||||
description: Checks the cookie, then lets openid-client exchange the code and verify the ID token (signature, issuer, audience, expiry, nonce, state, PKCE). Finds the account by provider subject, links a verified email, or creates an account when registration allows it.
|
||||
responses:
|
||||
'302':
|
||||
description: Back to the app with "#oidc=<one-time handoff>" or "#oidc_error=oidc_failed|oidc_email_unverified|oidc_email_missing|registration_closed"
|
||||
|
||||
/auth/oidc/exchange:
|
||||
post:
|
||||
tags: [Auth]
|
||||
summary: Trade the one-time handoff for a session
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
type: object
|
||||
properties:
|
||||
code:
|
||||
type: string
|
||||
required: [code]
|
||||
responses:
|
||||
'200':
|
||||
description: Session
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/AuthResponse'
|
||||
'401':
|
||||
description: Handoff invalid, expired or already used (invalid_handoff)
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
|
||||
/auth/register:
|
||||
post:
|
||||
tags: [Auth]
|
||||
@@ -540,6 +644,12 @@ paths:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
'403':
|
||||
description: Registration closed on this instance (registration_closed), or PASSWORD_LOGIN=false (password_login_disabled)
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
'409':
|
||||
description: Email already exists
|
||||
content:
|
||||
@@ -576,6 +686,12 @@ paths:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
'403':
|
||||
description: PASSWORD_LOGIN=false (password_login_disabled)
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
'401':
|
||||
description: Invalid credentials
|
||||
content:
|
||||
@@ -1541,6 +1657,51 @@ paths:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
|
||||
/trees/{id}/links/order:
|
||||
put:
|
||||
tags: [Trees]
|
||||
summary: Reorder siblings (rewrites displayOrder of their parent-child links)
|
||||
security:
|
||||
- BearerAuth: []
|
||||
parameters:
|
||||
- in: path
|
||||
name: id
|
||||
required: true
|
||||
schema:
|
||||
type: string
|
||||
requestBody:
|
||||
required: true
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ChildrenOrderRequest'
|
||||
responses:
|
||||
'200':
|
||||
description: Order saved
|
||||
'400':
|
||||
description: Invalid payload, links that do not belong to their child, or children without a shared parent
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
'401':
|
||||
description: Authentication required
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
'403':
|
||||
description: Forbidden
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
'404':
|
||||
description: Link not found
|
||||
content:
|
||||
application/json:
|
||||
schema:
|
||||
$ref: '#/components/schemas/ErrorResponse'
|
||||
/trees/{id}/links/{linkId}:
|
||||
patch:
|
||||
tags: [Trees]
|
||||
|
||||
Generated
+1880
-294
File diff suppressed because it is too large.
Load diff
+15
-9
@@ -17,21 +17,27 @@
|
||||
"prisma:deploy": "prisma migrate deploy"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/cookie": "^11.1.5",
|
||||
"@fastify/cors": "^11.3.0",
|
||||
"@fastify/jwt": "^10.2.2",
|
||||
"@fastify/jwt": "^10.2.6",
|
||||
"@fastify/rate-limit": "^11.2.0",
|
||||
"@prisma/client": "^6.15.0",
|
||||
"bcryptjs": "^3.0.2",
|
||||
"dotenv": "^18.0.5",
|
||||
"fastify": "^5.6.1",
|
||||
"@node-rs/bcrypt": "^2.0.0",
|
||||
"@prisma/adapter-pg": "^7.10.1",
|
||||
"@prisma/client": "^7.10.1",
|
||||
"blurhash": "^2.0.5",
|
||||
"dotenv": "^18.0.9",
|
||||
"fastify": "^5.12.7",
|
||||
"openid-client": "^6.8.8",
|
||||
"pg": "^8.23.1",
|
||||
"sharp": "^0.35.5",
|
||||
"zod": "^4.6.5"
|
||||
"zod": "^4.6.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.3.0",
|
||||
"prisma": "^6.15.0",
|
||||
"@types/node": "^24.19.2",
|
||||
"@types/pg": "^8.23.1",
|
||||
"prisma": "^7.10.1",
|
||||
"tsx": "^4.23.15",
|
||||
"typescript": "^7.0.2",
|
||||
"vitest": "^5.0.3"
|
||||
"vitest": "^5.0.5"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { config } from 'dotenv'
|
||||
import type { PrismaConfig } from 'prisma/config'
|
||||
|
||||
// Configuration du CLI Prisma (generate, migrate). Depuis Prisma 7, le CLI ne lit plus .env tout seul. Seul un import
|
||||
// de type vient de prisma/config : dans les images, le CLI est installé à part (/opt/prisma) et ce fichier doit se
|
||||
// charger sans lui. Sans DATABASE_URL (generate pendant un build), l'adresse reste vide.
|
||||
config({ quiet: true })
|
||||
|
||||
export default {
|
||||
schema: 'prisma/schema.prisma',
|
||||
migrations: { path: 'prisma/migrations' },
|
||||
datasource: { url: process.env.DATABASE_URL ?? '' },
|
||||
} satisfies PrismaConfig
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Association d'une personne à une personne Immich (reconnaissance des visages).
|
||||
ALTER TABLE "persons" ADD COLUMN "immichPersonId" TEXT;
|
||||
@@ -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;
|
||||
@@ -0,0 +1,47 @@
|
||||
-- AlterTable
|
||||
ALTER TABLE "persons" ADD COLUMN "birthDateEnd" TIMESTAMP(3),
|
||||
ADD COLUMN "birthDatePrecision" TEXT,
|
||||
ADD COLUMN "deathDateEnd" TIMESTAMP(3),
|
||||
ADD COLUMN "deathDatePrecision" TEXT,
|
||||
ADD COLUMN "deathPlace" TEXT,
|
||||
ADD COLUMN "nickname" TEXT;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "unions" ADD COLUMN "startDatePrecision" TEXT,
|
||||
ADD COLUMN "startPlace" TEXT;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "life_events" (
|
||||
"id" TEXT NOT NULL,
|
||||
"treeId" TEXT NOT NULL,
|
||||
"personId" TEXT,
|
||||
"unionId" TEXT,
|
||||
"type" TEXT NOT NULL,
|
||||
"label" TEXT,
|
||||
"date" TIMESTAMP(3),
|
||||
"dateEnd" TIMESTAMP(3),
|
||||
"datePrecision" TEXT,
|
||||
"dateText" TEXT,
|
||||
"place" TEXT,
|
||||
"description" TEXT,
|
||||
"notes" TEXT,
|
||||
"sources" TEXT,
|
||||
"displayOrder" INTEGER NOT NULL DEFAULT 1,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"updatedAt" TIMESTAMP(3) NOT NULL,
|
||||
"deletedAt" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "life_events_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "life_events_treeId_idx" ON "life_events"("treeId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "life_events_treeId_personId_idx" ON "life_events"("treeId", "personId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "life_events_treeId_unionId_idx" ON "life_events"("treeId", "unionId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "life_events" ADD CONSTRAINT "life_events_treeId_fkey" FOREIGN KEY ("treeId") REFERENCES "trees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Photo rattachée à un événement de vie (souvenir de la personne), facultative
|
||||
ALTER TABLE "life_events" ADD COLUMN "mediaId" TEXT;
|
||||
@@ -0,0 +1,10 @@
|
||||
-- Moments proposés par la famille (relus par l'administrateur) et plusieurs souvenirs par moment
|
||||
ALTER TABLE "life_events" ADD COLUMN "status" TEXT NOT NULL DEFAULT 'approved';
|
||||
ALTER TABLE "life_events" ADD COLUMN "contributionSessionId" TEXT;
|
||||
ALTER TABLE "media_items" ADD COLUMN "lifeEventId" TEXT;
|
||||
CREATE INDEX "media_items_lifeEventId_idx" ON "media_items"("lifeEventId");
|
||||
|
||||
-- Les photos déjà rattachées par life_events.mediaId passent sur le souvenir
|
||||
UPDATE "media_items" AS m SET "lifeEventId" = e."id"
|
||||
FROM "life_events" AS e
|
||||
WHERE e."mediaId" = m."id" AND e."deletedAt" IS NULL;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Moment proposé par la famille, relu comme un souvenir
|
||||
ALTER TYPE "ContributionEntityType" ADD VALUE 'life_event';
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Personne décédée sans date connue (issue #77)
|
||||
ALTER TABLE "persons" ADD COLUMN "isDeceased" BOOLEAN NOT NULL DEFAULT false;
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Prénom du compte, facultatif (comptes existants : vide). Migration additive.
|
||||
ALTER TABLE "users" ADD COLUMN "firstName" TEXT;
|
||||
@@ -0,0 +1,3 @@
|
||||
-- Cadrage du portrait (feat/recadrage-portrait). Migration additive : colonne nullable, sans défaut.
|
||||
-- AlterTable
|
||||
ALTER TABLE "persons" ADD COLUMN "avatarCrop" JSONB;
|
||||
@@ -0,0 +1,25 @@
|
||||
-- Connexion OIDC (#115) : un compte peut naître sans mot de passe, et ses identités chez un fournisseur sont gardées
|
||||
-- à part (émetteur + sub). Migration additive : les comptes existants gardent leur mot de passe.
|
||||
-- AlterTable
|
||||
ALTER TABLE "users" ALTER COLUMN "passwordHash" DROP NOT NULL;
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "user_identities" (
|
||||
"id" TEXT NOT NULL,
|
||||
"userId" TEXT NOT NULL,
|
||||
"issuer" TEXT NOT NULL,
|
||||
"subject" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "user_identities_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "user_identities_userId_idx" ON "user_identities"("userId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "user_identities_issuer_subject_key" ON "user_identities"("issuer", "subject");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "user_identities" ADD CONSTRAINT "user_identities_userId_fkey" FOREIGN KEY ("userId") REFERENCES "users"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
-- Personnes identifiées sur un souvenir (feat/souvenirs-personnes). Migration additive : nouvelle table, nouvelle valeur d'énumération.
|
||||
-- AlterEnum
|
||||
ALTER TYPE "ContributionEntityType" ADD VALUE 'media_people';
|
||||
|
||||
-- CreateTable
|
||||
CREATE TABLE "media_person_tags" (
|
||||
"id" TEXT NOT NULL,
|
||||
"treeId" TEXT NOT NULL,
|
||||
"mediaId" TEXT NOT NULL,
|
||||
"personId" TEXT NOT NULL,
|
||||
"x" DOUBLE PRECISION,
|
||||
"y" DOUBLE PRECISION,
|
||||
"createdBy" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "media_person_tags_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "media_person_tags_treeId_idx" ON "media_person_tags"("treeId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "media_person_tags_treeId_personId_idx" ON "media_person_tags"("treeId", "personId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "media_person_tags_mediaId_personId_key" ON "media_person_tags"("mediaId", "personId");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "media_person_tags" ADD CONSTRAINT "media_person_tags_treeId_fkey" FOREIGN KEY ("treeId") REFERENCES "trees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
-- « À vérifier » sur une personne (feat/a-verifier). Migration additive : booléen à faux par défaut.
|
||||
-- AlterTable
|
||||
ALTER TABLE "persons" ADD COLUMN "toVerify" BOOLEAN NOT NULL DEFAULT false;
|
||||
@@ -0,0 +1,32 @@
|
||||
-- Co-gestion d'un arbre (issue #145) : invitations du propriétaire. Migration additive, une table neuve.
|
||||
-- CreateTable
|
||||
CREATE TABLE "tree_invitations" (
|
||||
"id" TEXT NOT NULL,
|
||||
"treeId" TEXT NOT NULL,
|
||||
"email" TEXT NOT NULL,
|
||||
"tokenHash" TEXT NOT NULL,
|
||||
"invitedByUserId" TEXT,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
"acceptedAt" TIMESTAMP(3),
|
||||
"acceptedUserId" TEXT,
|
||||
"revokedAt" TIMESTAMP(3),
|
||||
|
||||
CONSTRAINT "tree_invitations_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE UNIQUE INDEX "tree_invitations_tokenHash_key" ON "tree_invitations"("tokenHash");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "tree_invitations_treeId_idx" ON "tree_invitations"("treeId");
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "tree_invitations_email_idx" ON "tree_invitations"("email");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "tree_invitations" ADD CONSTRAINT "tree_invitations_treeId_fkey" FOREIGN KEY ("treeId") REFERENCES "trees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "tree_invitations" ADD CONSTRAINT "tree_invitations_invitedByUserId_fkey" FOREIGN KEY ("invitedByUserId") REFERENCES "users"("id") ON DELETE SET NULL ON UPDATE CASCADE;
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
-- Icône d'un arbre (un emoji), facultative. Migration additive : colonne vide par défaut.
|
||||
ALTER TABLE "trees" ADD COLUMN "icon" TEXT;
|
||||
@@ -0,0 +1,16 @@
|
||||
-- Photos posées sur l'arbre par la famille, en attente de relecture (1.5.1). Migration additive, une table neuve.
|
||||
-- CreateTable
|
||||
CREATE TABLE "annotation_photo_uploads" (
|
||||
"id" TEXT NOT NULL,
|
||||
"treeId" TEXT NOT NULL,
|
||||
"filePath" TEXT NOT NULL,
|
||||
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
CONSTRAINT "annotation_photo_uploads_pkey" PRIMARY KEY ("id")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "annotation_photo_uploads_treeId_createdAt_idx" ON "annotation_photo_uploads"("treeId", "createdAt");
|
||||
|
||||
-- AddForeignKey
|
||||
ALTER TABLE "annotation_photo_uploads" ADD CONSTRAINT "annotation_photo_uploads_treeId_fkey" FOREIGN KEY ("treeId") REFERENCES "trees"("id") ON DELETE CASCADE ON UPDATE CASCADE;
|
||||
@@ -0,0 +1,12 @@
|
||||
-- Sessions fermées (déconnexion, compte supprimé), gardées en base pour survivre au redémarrage de l'API.
|
||||
-- Migration additive, une table neuve.
|
||||
-- CreateTable
|
||||
CREATE TABLE "revoked_sessions" (
|
||||
"jti" TEXT NOT NULL,
|
||||
"expiresAt" TIMESTAMP(3) NOT NULL,
|
||||
|
||||
CONSTRAINT "revoked_sessions_pkey" PRIMARY KEY ("jti")
|
||||
);
|
||||
|
||||
-- CreateIndex
|
||||
CREATE INDEX "revoked_sessions_expiresAt_idx" ON "revoked_sessions"("expiresAt");
|
||||
@@ -0,0 +1,7 @@
|
||||
-- Aperçus flous (BlurHash) des portraits et des photos, montrés pendant le chargement.
|
||||
-- Migration additive : deux colonnes facultatives, remplies ensuite par l'API (lib/blurhash.ts).
|
||||
-- AlterTable
|
||||
ALTER TABLE "persons" ADD COLUMN "avatarBlurhash" TEXT;
|
||||
|
||||
-- AlterTable
|
||||
ALTER TABLE "media_items" ADD COLUMN "blurhash" TEXT;
|
||||
+311
-139
@@ -1,10 +1,14 @@
|
||||
// Client généré dans src/generated (ignoré par git), compilé avec le reste dans dist : rien à copier depuis
|
||||
// node_modules dans les images. L'adresse de la base vient de prisma.config.ts.
|
||||
generator client {
|
||||
provider = "prisma-client-js"
|
||||
provider = "prisma-client"
|
||||
output = "../src/generated/prisma"
|
||||
moduleFormat = "esm"
|
||||
importFileExtension = "js"
|
||||
}
|
||||
|
||||
datasource db {
|
||||
provider = "postgresql"
|
||||
url = env("DATABASE_URL")
|
||||
}
|
||||
|
||||
enum MembershipRole {
|
||||
@@ -39,6 +43,9 @@ enum ContributionEntityType {
|
||||
parent_child_link
|
||||
annotation
|
||||
media
|
||||
life_event
|
||||
// Personnes identifiées sur un souvenir (remplace la liste entière)
|
||||
media_people
|
||||
}
|
||||
|
||||
// Souvenir envoyé par la famille : en attente jusqu'à la relecture du propriétaire
|
||||
@@ -78,51 +85,77 @@ enum SharedAccessRole {
|
||||
}
|
||||
|
||||
model User {
|
||||
id String @id @default(cuid())
|
||||
email String @unique
|
||||
passwordHash String
|
||||
lastOpenedTreeId String?
|
||||
lastOpenedAccessMode String?
|
||||
lastOpenedRole String?
|
||||
lastOpenedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
ownedTrees Tree[] @relation("TreeOwner")
|
||||
memberships TreeMembership[]
|
||||
sharedTreeAccesses UserTreeAccess[]
|
||||
id String @id @default(cuid())
|
||||
email String @unique
|
||||
firstName String?
|
||||
// Vide pour un compte né d'une connexion OIDC : il n'a pas de mot de passe Parenthèse
|
||||
passwordHash String?
|
||||
lastOpenedTreeId String?
|
||||
lastOpenedAccessMode String?
|
||||
lastOpenedRole String?
|
||||
lastOpenedAt DateTime?
|
||||
createdAt DateTime @default(now())
|
||||
ownedTrees Tree[] @relation("TreeOwner")
|
||||
memberships TreeMembership[]
|
||||
sharedTreeAccesses UserTreeAccess[]
|
||||
submittedContributionSessions ContributionSession[] @relation("ContributionSubmittedBy")
|
||||
reviewedContributionSessions ContributionSession[] @relation("ContributionReviewedBy")
|
||||
treeVisits TreeVisit[]
|
||||
lastOpenedTree Tree? @relation("UserLastOpenedTree", fields: [lastOpenedTreeId], references: [id], onDelete: SetNull)
|
||||
reviewedContributionSessions ContributionSession[] @relation("ContributionReviewedBy")
|
||||
treeVisits TreeVisit[]
|
||||
identities UserIdentity[]
|
||||
sentTreeInvitations TreeInvitation[] @relation("TreeInvitationSentBy")
|
||||
lastOpenedTree Tree? @relation("UserLastOpenedTree", fields: [lastOpenedTreeId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@index([lastOpenedAt])
|
||||
@@map("users")
|
||||
}
|
||||
|
||||
// Compte d'un fournisseur OIDC relié à un compte Parenthèse : l'émetteur et le « sub » de l'ID token, jamais l'email,
|
||||
// qui peut changer chez le fournisseur.
|
||||
model UserIdentity {
|
||||
id String @id @default(cuid())
|
||||
userId String
|
||||
issuer String
|
||||
subject String
|
||||
createdAt DateTime @default(now())
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([issuer, subject])
|
||||
@@index([userId])
|
||||
@@map("user_identities")
|
||||
}
|
||||
|
||||
model Tree {
|
||||
id String @id @default(cuid())
|
||||
ownerUserId String
|
||||
slug String @unique
|
||||
name String
|
||||
description String?
|
||||
rootPersonId String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deletedAt DateTime?
|
||||
owner User @relation("TreeOwner", fields: [ownerUserId], references: [id], onDelete: Restrict)
|
||||
accessPasswords TreeAccessPasswords?
|
||||
sharePassword TreeSharePassword?
|
||||
memberships TreeMembership[]
|
||||
sharedUserAccesses UserTreeAccess[]
|
||||
settings TreeSettings?
|
||||
persons Person[]
|
||||
unions Union[]
|
||||
parentChildLinks ParentChildLink[]
|
||||
mediaItems MediaItem[]
|
||||
contributionSessions ContributionSession[]
|
||||
auditLogs AuditLog[]
|
||||
annotations Annotation[]
|
||||
visits TreeVisit[]
|
||||
lastOpenedByUsers User[] @relation("UserLastOpenedTree")
|
||||
id String @id @default(cuid())
|
||||
ownerUserId String
|
||||
slug String @unique
|
||||
name String
|
||||
description String?
|
||||
// Icône choisie pour l'arbre (un emoji), à la place de la première lettre dans les menus ; null = la lettre
|
||||
icon String?
|
||||
rootPersonId String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deletedAt DateTime?
|
||||
owner User @relation("TreeOwner", fields: [ownerUserId], references: [id], onDelete: Restrict)
|
||||
accessPasswords TreeAccessPasswords?
|
||||
sharePassword TreeSharePassword?
|
||||
memberships TreeMembership[]
|
||||
sharedUserAccesses UserTreeAccess[]
|
||||
settings TreeSettings?
|
||||
immichConfig TreeImmichConfig?
|
||||
persons Person[]
|
||||
unions Union[]
|
||||
parentChildLinks ParentChildLink[]
|
||||
mediaItems MediaItem[]
|
||||
mediaPersonTags MediaPersonTag[]
|
||||
contributionSessions ContributionSession[]
|
||||
auditLogs AuditLog[]
|
||||
annotations Annotation[]
|
||||
visits TreeVisit[]
|
||||
lifeEvents LifeEvent[]
|
||||
invitations TreeInvitation[]
|
||||
annotationPhotoUploads AnnotationPhotoUpload[]
|
||||
lastOpenedByUsers User[] @relation("UserLastOpenedTree")
|
||||
|
||||
@@index([ownerUserId])
|
||||
@@map("trees")
|
||||
@@ -150,29 +183,74 @@ model TreeSharePassword {
|
||||
}
|
||||
|
||||
model TreeMembership {
|
||||
id String @id @default(cuid())
|
||||
id String @id @default(cuid())
|
||||
treeId String
|
||||
userId String
|
||||
role MembershipRole
|
||||
contributionModeOverride ContributionPolicy?
|
||||
createdAt DateTime @default(now())
|
||||
tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
createdAt DateTime @default(now())
|
||||
tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([treeId, userId])
|
||||
@@index([userId])
|
||||
@@map("tree_memberships")
|
||||
}
|
||||
|
||||
// Invitation à co-gérer un arbre (issue #145) : le propriétaire donne une adresse, Parenthèse un lien à transmettre.
|
||||
// Seule l'empreinte du jeton est gardée ; « Copier le lien » en tire un nouveau. Acceptée, elle donne le rôle admin
|
||||
// (co-gestionnaire). Le lien sert une fois, jusqu'à expiresAt.
|
||||
model TreeInvitation {
|
||||
id String @id @default(cuid())
|
||||
treeId String
|
||||
email String
|
||||
tokenHash String @unique
|
||||
invitedByUserId String?
|
||||
createdAt DateTime @default(now())
|
||||
expiresAt DateTime
|
||||
acceptedAt DateTime?
|
||||
acceptedUserId String?
|
||||
revokedAt DateTime?
|
||||
tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade)
|
||||
invitedBy User? @relation("TreeInvitationSentBy", fields: [invitedByUserId], references: [id], onDelete: SetNull)
|
||||
|
||||
@@index([treeId])
|
||||
@@index([email])
|
||||
@@map("tree_invitations")
|
||||
}
|
||||
|
||||
// Sessions fermées (déconnexion, compte supprimé), gardées jusqu'à la fin de leur jeton
|
||||
model RevokedSession {
|
||||
jti String @id
|
||||
expiresAt DateTime
|
||||
|
||||
@@index([expiresAt])
|
||||
@@map("revoked_sessions")
|
||||
}
|
||||
|
||||
// Photo posée sur l'arbre par la famille, en attente de relecture (1.5.1). La ligne vit tant que la photo n'est
|
||||
// ni acceptée (ligne retirée, fichier gardé) ni refusée (fichier et ligne effacés). Un envoi jamais proposé est
|
||||
// effacé après 7 jours, la durée d'un brouillon. Les photos des gestionnaires n'ont pas de ligne.
|
||||
model AnnotationPhotoUpload {
|
||||
id String @id
|
||||
treeId String
|
||||
filePath String
|
||||
createdAt DateTime @default(now())
|
||||
tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([treeId, createdAt])
|
||||
@@map("annotation_photo_uploads")
|
||||
}
|
||||
|
||||
model UserTreeAccess {
|
||||
id String @id @default(cuid())
|
||||
treeId String
|
||||
userId String
|
||||
role SharedAccessRole
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @default(now()) @updatedAt
|
||||
tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
id String @id @default(cuid())
|
||||
treeId String
|
||||
userId String
|
||||
role SharedAccessRole
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @default(now()) @updatedAt
|
||||
tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade)
|
||||
user User @relation(fields: [userId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([treeId, userId])
|
||||
@@index([userId, updatedAt])
|
||||
@@ -180,103 +258,162 @@ model UserTreeAccess {
|
||||
}
|
||||
|
||||
model TreeSettings {
|
||||
treeId String @id
|
||||
memberContributionPolicy ContributionPolicy @default(pending)
|
||||
visitorPolicy VisitorPolicy @default(read_only)
|
||||
contributorPolicy ContributionPolicy @default(pending)
|
||||
updatedAt DateTime @updatedAt
|
||||
tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade)
|
||||
treeId String @id
|
||||
memberContributionPolicy ContributionPolicy @default(pending)
|
||||
visitorPolicy VisitorPolicy @default(read_only)
|
||||
contributorPolicy ContributionPolicy @default(pending)
|
||||
updatedAt DateTime @updatedAt
|
||||
tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@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
|
||||
firstName String
|
||||
lastName String
|
||||
birthName String?
|
||||
birthDate DateTime?
|
||||
deathDate DateTime?
|
||||
birthPlace String?
|
||||
profession String?
|
||||
region String?
|
||||
nationality String?
|
||||
avatarPath String?
|
||||
avatarMimeType String?
|
||||
sex String?
|
||||
notes String?
|
||||
createdBy String?
|
||||
updatedBy String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deletedAt DateTime?
|
||||
tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade)
|
||||
id String @id @default(cuid())
|
||||
treeId String
|
||||
firstName String
|
||||
lastName String
|
||||
birthName String?
|
||||
birthDate DateTime?
|
||||
deathDate DateTime?
|
||||
// Décédé(e) sans date connue (issue #77) : vrai seulement quand deathDate est vide
|
||||
isDeceased Boolean @default(false)
|
||||
// « À vérifier » : la famille n'est pas sûre de cette personne et le signale (retour d'Anaïs, 23/10)
|
||||
toVerify Boolean @default(false)
|
||||
birthPlace String?
|
||||
// Précision d'une date importée (« vers », « avant », « entre »…) et sa borne de fin pour « entre … et … »
|
||||
birthDatePrecision String?
|
||||
birthDateEnd DateTime?
|
||||
deathDatePrecision String?
|
||||
deathDateEnd DateTime?
|
||||
deathPlace String?
|
||||
nickname String?
|
||||
profession String?
|
||||
region String?
|
||||
nationality String?
|
||||
avatarPath String?
|
||||
avatarMimeType String?
|
||||
// Cadrage du portrait, appliqué à l'affichage sur l'original (jamais de fichier dérivé) :
|
||||
// { "x": 0..1, "y": 0..1, "zoom": 1..4 }, centre du cadrage en proportion de l'image, zoom 1 = image entière
|
||||
// recouvrant le cadre. Null = cadrage par défaut (centré, zoom 1).
|
||||
avatarCrop Json?
|
||||
// Aperçu flou du portrait (BlurHash), montré pendant le chargement. Null : pas encore calculé ; vide : illisible
|
||||
avatarBlurhash String?
|
||||
sex String?
|
||||
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?
|
||||
tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([treeId])
|
||||
@@map("persons")
|
||||
}
|
||||
|
||||
model Union {
|
||||
id String @id @default(cuid())
|
||||
treeId String
|
||||
partner1PersonId String
|
||||
partner2PersonId String?
|
||||
unionType String?
|
||||
startDate DateTime?
|
||||
endDate DateTime?
|
||||
displayOrder Int @default(1)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deletedAt DateTime?
|
||||
tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade)
|
||||
id String @id @default(cuid())
|
||||
treeId String
|
||||
partner1PersonId String
|
||||
partner2PersonId String?
|
||||
unionType String?
|
||||
startDate DateTime?
|
||||
endDate DateTime?
|
||||
displayOrder Int @default(1)
|
||||
startPlace String?
|
||||
startDatePrecision String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deletedAt DateTime?
|
||||
tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([treeId])
|
||||
@@map("unions")
|
||||
}
|
||||
|
||||
model ParentChildLink {
|
||||
id String @id @default(cuid())
|
||||
treeId String
|
||||
id String @id @default(cuid())
|
||||
treeId String
|
||||
parentPersonId String
|
||||
childPersonId String
|
||||
viaUnionId String?
|
||||
parentageType String?
|
||||
displayOrder Int @default(1)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deletedAt DateTime?
|
||||
tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade)
|
||||
childPersonId String
|
||||
viaUnionId String?
|
||||
parentageType String?
|
||||
displayOrder Int @default(1)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deletedAt DateTime?
|
||||
tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([treeId])
|
||||
@@map("parent_child_links")
|
||||
}
|
||||
|
||||
model MediaItem {
|
||||
id String @id @default(cuid())
|
||||
treeId String
|
||||
personId String
|
||||
type String
|
||||
mimeType String
|
||||
filePath String
|
||||
thumbPath String?
|
||||
caption String?
|
||||
source String?
|
||||
sizeBytes Int
|
||||
displayOrder Int @default(1)
|
||||
isFeatured Boolean @default(false)
|
||||
uploadedBy String?
|
||||
status MediaStatus @default(approved)
|
||||
id String @id @default(cuid())
|
||||
treeId String
|
||||
personId String
|
||||
type String
|
||||
mimeType String
|
||||
filePath String
|
||||
thumbPath String?
|
||||
// Aperçu flou d'une photo (BlurHash), montré pendant le chargement. Null : pas encore calculé ; vide : illisible
|
||||
blurhash String?
|
||||
caption String?
|
||||
source String?
|
||||
sizeBytes Int
|
||||
displayOrder Int @default(1)
|
||||
isFeatured Boolean @default(false)
|
||||
uploadedBy String?
|
||||
status MediaStatus @default(approved)
|
||||
contributionSessionId String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deletedAt DateTime?
|
||||
tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade)
|
||||
// Moment de l'onglet Vie auquel ce souvenir est rattaché (photo, vidéo, acte en PDF…)
|
||||
lifeEventId String?
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deletedAt DateTime?
|
||||
tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([treeId, personId, displayOrder])
|
||||
@@index([lifeEventId])
|
||||
@@map("media_items")
|
||||
}
|
||||
|
||||
// Personne identifiée sur un souvenir. Le souvenir reste à la personne qui le porte (media_items.personId) ;
|
||||
// il apparaît aussi sur la fiche de chaque personne identifiée. x et y : point sur le visage, en proportion
|
||||
// de l'image (0 à 1), facultatifs.
|
||||
model MediaPersonTag {
|
||||
id String @id @default(cuid())
|
||||
treeId String
|
||||
mediaId String
|
||||
personId String
|
||||
x Float?
|
||||
y Float?
|
||||
createdBy String?
|
||||
createdAt DateTime @default(now())
|
||||
tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@unique([mediaId, personId])
|
||||
@@index([treeId])
|
||||
@@index([treeId, personId])
|
||||
@@map("media_person_tags")
|
||||
}
|
||||
|
||||
model ContributionSession {
|
||||
id String @id @default(cuid())
|
||||
treeId String
|
||||
@@ -300,17 +437,17 @@ model ContributionSession {
|
||||
}
|
||||
|
||||
model ContributionChange {
|
||||
id String @id @default(cuid())
|
||||
sessionId String
|
||||
entityType ContributionEntityType
|
||||
entityId String?
|
||||
action ContributionAction
|
||||
beforeJson Json?
|
||||
afterJson Json?
|
||||
conflictState ConflictState @default(none)
|
||||
decision ContributionDecision?
|
||||
createdAt DateTime @default(now())
|
||||
session ContributionSession @relation(fields: [sessionId], references: [id], onDelete: Cascade)
|
||||
id String @id @default(cuid())
|
||||
sessionId String
|
||||
entityType ContributionEntityType
|
||||
entityId String?
|
||||
action ContributionAction
|
||||
beforeJson Json?
|
||||
afterJson Json?
|
||||
conflictState ConflictState @default(none)
|
||||
decision ContributionDecision?
|
||||
createdAt DateTime @default(now())
|
||||
session ContributionSession @relation(fields: [sessionId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([sessionId])
|
||||
@@map("contribution_changes")
|
||||
@@ -336,16 +473,16 @@ model Annotation {
|
||||
}
|
||||
|
||||
model AuditLog {
|
||||
id String @id @default(cuid())
|
||||
treeId String
|
||||
actorType String
|
||||
actorId String?
|
||||
action String
|
||||
entityType String
|
||||
entityId String
|
||||
id String @id @default(cuid())
|
||||
treeId String
|
||||
actorType String
|
||||
actorId String?
|
||||
action String
|
||||
entityType String
|
||||
entityId String
|
||||
payloadJson Json?
|
||||
createdAt DateTime @default(now())
|
||||
tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade)
|
||||
createdAt DateTime @default(now())
|
||||
tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([treeId, createdAt])
|
||||
@@map("audit_log")
|
||||
@@ -379,3 +516,38 @@ model WaitlistEntry {
|
||||
|
||||
@@map("waitlist_entries")
|
||||
}
|
||||
|
||||
// Événements de vie d'une personne (baptême, résidence, métier, études, service militaire, inhumation…) ou
|
||||
// d'un couple (divorce…). Naissance, décès et mariage gardent leur date et leur lieu sur la personne ou
|
||||
// l'union ; leur ligne ici ne porte que les sources et les notes (type birth, death, marriage).
|
||||
model LifeEvent {
|
||||
id String @id @default(cuid())
|
||||
treeId String
|
||||
personId String?
|
||||
unionId String?
|
||||
type String
|
||||
label String?
|
||||
date DateTime?
|
||||
dateEnd DateTime?
|
||||
datePrecision String?
|
||||
dateText String?
|
||||
place String?
|
||||
description String?
|
||||
notes String?
|
||||
sources String?
|
||||
// Ancien rattachement d'une seule photo (17/10), remplacé par media_items.lifeEventId
|
||||
mediaId String?
|
||||
// Moment proposé par la famille : « pending » jusqu'à la relecture de l'administrateur
|
||||
status String @default("approved")
|
||||
contributionSessionId String?
|
||||
displayOrder Int @default(1)
|
||||
createdAt DateTime @default(now())
|
||||
updatedAt DateTime @updatedAt
|
||||
deletedAt DateTime?
|
||||
tree Tree @relation(fields: [treeId], references: [id], onDelete: Cascade)
|
||||
|
||||
@@index([treeId])
|
||||
@@index([treeId, personId])
|
||||
@@index([treeId, unionId])
|
||||
@@map("life_events")
|
||||
}
|
||||
+34
-5
@@ -1,16 +1,24 @@
|
||||
import { createHmac } from 'node:crypto'
|
||||
import Fastify, { type FastifyError } from 'fastify'
|
||||
import cookie from '@fastify/cookie'
|
||||
import cors from '@fastify/cors'
|
||||
import jwt from '@fastify/jwt'
|
||||
import rateLimit from '@fastify/rate-limit'
|
||||
import { Prisma } from '@prisma/client'
|
||||
import { Prisma } from './generated/prisma/client.js'
|
||||
|
||||
import { env } from './config/env.js'
|
||||
import { prisma } from './lib/prisma.js'
|
||||
import { isUserTokenRevoked } from './lib/token-revocation.js'
|
||||
import { isUserTokenRevoked, loadRevokedTokens } from './lib/token-revocation.js'
|
||||
import { registerIdempotency } from './lib/idempotency.js'
|
||||
import { startBlurhashFiller } from './lib/blurhash.js'
|
||||
import { authRoutes } from './routes/auth.js'
|
||||
import { contributionRoutes } from './routes/contributions.js'
|
||||
import { graphRoutes } from './routes/graph.js'
|
||||
import { mediaRoutes } from './routes/media.js'
|
||||
import { immichRoutes } from './routes/immich.js'
|
||||
import { managerRoutes } from './routes/managers.js'
|
||||
import { searchSourceRoutes } from './routes/search-sources.js'
|
||||
import { getStorageRoot, mediaRoutes } from './routes/media.js'
|
||||
import { oidcRoutes } from './routes/oidc.js'
|
||||
import { publicRoutes } from './routes/public.js'
|
||||
import { annotationRoutes } from './routes/annotations.js'
|
||||
import { gedcomRoutes } from './routes/gedcom.js'
|
||||
@@ -18,9 +26,10 @@ import { treeRoutes } from './routes/trees.js'
|
||||
import { visitRoutes } from './routes/visits.js'
|
||||
import type { AnyJwtPayload } from './types/auth.js'
|
||||
|
||||
// Les adresses des médias portent un jeton (<img src> n'envoie pas d'en-tête) : jamais dans les journaux
|
||||
// Les adresses des médias portent un jeton (<img src> n'envoie pas d'en-tête), le retour OIDC un code
|
||||
// d'autorisation : jamais dans les journaux
|
||||
export function redactUrl(url: string | undefined): string | undefined {
|
||||
return url?.replace(/([?&]token=)[^&#]*/g, '$1[masqué]')
|
||||
return url?.replace(/([?&](?:token|code)=)[^&#]*/g, '$1[masqué]')
|
||||
}
|
||||
|
||||
export function createApp() {
|
||||
@@ -51,6 +60,14 @@ export function createApp() {
|
||||
})
|
||||
|
||||
app.decorate('prisma', prisma)
|
||||
// Les déconnexions d'avant le redémarrage reviennent en mémoire avant la première requête (onReady passe avant
|
||||
// listen). Sans elles, l'API ne démarre pas : chaque session fermée redeviendrait valable sans que personne le
|
||||
// voie, et pm2 comme Docker relancent l'API.
|
||||
app.addHook('onReady', async () => {
|
||||
await loadRevokedTokens(app.prisma)
|
||||
})
|
||||
// Aperçus flous des photos et portraits qui n'en ont pas encore (lib/blurhash.ts) ; pas pendant les tests
|
||||
if (env.NODE_ENV !== 'test') app.addHook('onReady', async () => startBlurhashFiller(app, getStorageRoot()))
|
||||
app.decorateRequest('actor', null)
|
||||
|
||||
app.register(cors, {
|
||||
@@ -67,6 +84,11 @@ export function createApp() {
|
||||
secret: env.JWT_SECRET,
|
||||
})
|
||||
|
||||
// Cookie signé du parcours OIDC seulement (state, nonce, PKCE entre /auth/oidc/start et le retour) : les sessions
|
||||
// restent des jetons Bearer
|
||||
// Clé propre au cookie, dérivée de JWT_SECRET : une signature de cookie ne vaut jamais signature de jeton
|
||||
app.register(cookie, { secret: createHmac('sha256', env.JWT_SECRET).update('parenthese-oidc-cookie').digest('hex') })
|
||||
|
||||
app.addHook('preHandler', async (request) => {
|
||||
request.actor = null
|
||||
|
||||
@@ -138,7 +160,11 @@ export function createApp() {
|
||||
|
||||
app.get('/health', async () => ({ ok: true }))
|
||||
|
||||
// Après l'identification : une clé d'idempotence ne vaut que pour la personne qui l'a envoyée
|
||||
registerIdempotency(app)
|
||||
|
||||
app.register(authRoutes, { prefix: '/auth' })
|
||||
app.register(oidcRoutes, { prefix: '/auth/oidc' })
|
||||
app.register(publicRoutes)
|
||||
app.register(treeRoutes)
|
||||
app.register(mediaRoutes)
|
||||
@@ -147,6 +173,9 @@ export function createApp() {
|
||||
app.register(annotationRoutes)
|
||||
app.register(gedcomRoutes)
|
||||
app.register(visitRoutes)
|
||||
app.register(immichRoutes)
|
||||
app.register(managerRoutes)
|
||||
app.register(searchSourceRoutes)
|
||||
|
||||
app.setErrorHandler((error: FastifyError | Error, request, reply) => {
|
||||
if (error instanceof Prisma.PrismaClientInitializationError) {
|
||||
|
||||
@@ -28,6 +28,16 @@ function parseTrustProxy(value: string): boolean | string {
|
||||
return value
|
||||
}
|
||||
|
||||
// « true » ou « false », sans tenir compte de la casse. z.coerce.boolean lirait « false » comme vrai.
|
||||
function parseBooleanFlag(name: string) {
|
||||
return (value: string): boolean => {
|
||||
const normalized = value.trim().toLowerCase()
|
||||
if (normalized === 'true') return true
|
||||
if (normalized === 'false') return false
|
||||
throw new Error(`${name} must be "true" or "false"`)
|
||||
}
|
||||
}
|
||||
|
||||
const envSchema = z.object({
|
||||
NODE_ENV: z.enum(['development', 'test', 'production']).default('development'),
|
||||
PORT: z.coerce.number().int().positive().default(4000),
|
||||
@@ -50,10 +60,73 @@ const envSchema = z.object({
|
||||
// Place disque par arbre, et part réservée aux envois de la famille en attente de relecture
|
||||
MEDIA_QUOTA_PER_TREE_MB: z.coerce.number().int().positive().default(5120),
|
||||
MEDIA_PENDING_QUOTA_PER_TREE_MB: z.coerce.number().int().positive().default(500),
|
||||
// Instances Immich autorisées sur ce serveur, séparées par des virgules. Les administrateurs
|
||||
// d'un arbre choisissent leur connexion parmi cette liste : sans elle, la reconnaissance
|
||||
// des visages reste éteinte et le serveur ne peut pas servir de proxy vers un service interne.
|
||||
IMMICH_ALLOWED_API_URLS: z.string().default(''),
|
||||
// Création de compte. À « false », seuls les comptes existants se connectent : une instance ouverte sur
|
||||
// Internet ne laisse pas un inconnu qui trouve l'adresse créer ses arbres. Une instance sans aucun compte
|
||||
// accepte quand même le premier, celui du propriétaire (voir lib/registration.ts).
|
||||
ALLOW_REGISTRATION: z.string().default('true').transform(parseBooleanFlag('ALLOW_REGISTRATION')),
|
||||
// Invitations à créer son propre arbre, ajoutées pour l'instance hébergée app.parenthese.io : « Faire le mien »
|
||||
// dans le menu Ajouter de la famille, l'inscription proposée dans les messages de la démo, message d'invitation
|
||||
// de Noël. Éteintes par défaut : une instance auto-hébergée n'a pas à pousser vers la création de compte.
|
||||
// L'instance hébergée les allume dans ecosystem.config.cjs.
|
||||
SIGNUP_PROMPTS: z.string().default('false').transform(parseBooleanFlag('SIGNUP_PROMPTS')),
|
||||
// Connexion par un fournisseur d'identité OIDC (#115 ; Authentik, Authelia, Keycloak, Pocket ID…). Éteinte sans
|
||||
// OIDC_ISSUER. Le fournisseur renvoie vers OIDC_REDIRECT_URI, l'adresse publique de /auth/oidc/callback.
|
||||
OIDC_ISSUER: z.string().trim().default(''),
|
||||
OIDC_CLIENT_ID: z.string().trim().default(''),
|
||||
// Vide : client public, protégé par PKCE seul
|
||||
OIDC_CLIENT_SECRET: z.string().default(''),
|
||||
OIDC_REDIRECT_URI: z.string().trim().default(''),
|
||||
// Où l'app s'ouvre après la connexion. Par défaut l'origine de OIDC_REDIRECT_URI (Docker : front et API sur la
|
||||
// même adresse) ; à renseigner quand le front a sa propre adresse (développement).
|
||||
OIDC_APP_URL: z.string().trim().default(''),
|
||||
OIDC_SCOPES: z.string().default('openid email profile'),
|
||||
// Nom du bouton « Se connecter avec … »
|
||||
OIDC_PROVIDER_NAME: z.string().trim().max(40).default('SSO'),
|
||||
// Un compte n'est créé ou relié par son email que si le fournisseur le dit vérifié (email_verified). À false
|
||||
// seulement pour un fournisseur qui ne l'envoie pas et où personne ne choisit lui-même son adresse.
|
||||
OIDC_REQUIRE_VERIFIED_EMAIL: z.string().default('true').transform(parseBooleanFlag('OIDC_REQUIRE_VERIFIED_EMAIL')),
|
||||
// À false, plus de mot de passe Parenthèse : connexion par le fournisseur OIDC seulement
|
||||
PASSWORD_LOGIN: z.string().default('true').transform(parseBooleanFlag('PASSWORD_LOGIN')),
|
||||
// Sources publiques que le panneau « Chercher quelqu'un » interroge depuis le serveur, séparées par des
|
||||
// virgules : deces (décès en France depuis 1970, INSEE par matchID), wikitree. Vide : aucun nom ne quitte
|
||||
// l'instance, le panneau ne propose que des liens vers les sites, ouverts par le navigateur.
|
||||
SEARCH_SOURCES: z.string().default(''),
|
||||
// Facultatif : jeton matchID (gratuit, après inscription) au-delà d'une centaine de recherches
|
||||
MATCHID_TOKEN: z.string().trim().default(''),
|
||||
})
|
||||
|
||||
export const env = envSchema.parse(process.env)
|
||||
|
||||
function assertHttpUrl(name: string, value: string) {
|
||||
let url: URL
|
||||
try {
|
||||
url = new URL(value)
|
||||
} catch {
|
||||
throw new Error(`${name} must be a full URL`)
|
||||
}
|
||||
if (url.protocol !== 'https:' && url.protocol !== 'http:') {
|
||||
throw new Error(`${name} must be an http(s) URL`)
|
||||
}
|
||||
}
|
||||
|
||||
if (env.OIDC_ISSUER) {
|
||||
assertHttpUrl('OIDC_ISSUER', env.OIDC_ISSUER)
|
||||
if (!env.OIDC_CLIENT_ID) throw new Error('OIDC_CLIENT_ID is required with OIDC_ISSUER')
|
||||
if (!env.OIDC_REDIRECT_URI) throw new Error('OIDC_REDIRECT_URI is required with OIDC_ISSUER (public address of /auth/oidc/callback)')
|
||||
assertHttpUrl('OIDC_REDIRECT_URI', env.OIDC_REDIRECT_URI)
|
||||
if (env.OIDC_APP_URL) assertHttpUrl('OIDC_APP_URL', env.OIDC_APP_URL)
|
||||
if (!env.OIDC_SCOPES.split(/\s+/).includes('openid')) throw new Error('OIDC_SCOPES must include openid')
|
||||
}
|
||||
|
||||
// Sans mot de passe ni fournisseur, personne ne pourrait se connecter
|
||||
if (!env.PASSWORD_LOGIN && !env.OIDC_ISSUER) {
|
||||
throw new Error('PASSWORD_LOGIN=false needs OIDC_ISSUER: otherwise nobody can sign in')
|
||||
}
|
||||
|
||||
// Corps maximal des routes qui reçoivent un fichier en base64 ou un gros envoi (le reste de l'API : 1 Mo)
|
||||
export const UPLOAD_BODY_LIMIT = 12 * 1024 * 1024
|
||||
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
import path from 'node:path'
|
||||
|
||||
import { Prisma, type PrismaClient } from '../generated/prisma/client.js'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { InvalidAnnotationContentError, sanitizeAnnotationContentForWrite } from './annotation-content.js'
|
||||
|
||||
// Annotations proposées par la famille (dessin, texte, sticker, photo posée sur l'arbre). Avant la 1.5.1, le
|
||||
// serveur les laissait au navigateur du relecteur, qui les posait après coup : une proposition acceptée pouvait
|
||||
// ne jamais apparaître (onglet fermé, erreur réseau), et rien n'apparaissait en mode « direct ». Elles sont
|
||||
// maintenant posées dans la transaction qui accepte la proposition.
|
||||
|
||||
type Tx = Prisma.TransactionClient
|
||||
type Db = PrismaClient | Tx
|
||||
|
||||
export const MAX_ANNOTATIONS_PER_TREE = 5000
|
||||
// Un envoi de photo jamais proposé vit le temps d'un brouillon de la famille
|
||||
export const PENDING_PHOTO_TTL_MS = 7 * 24 * 60 * 60 * 1000
|
||||
// Une famille pose quelques photos à la fois ; au-delà, c'est un envoi en boucle
|
||||
export const MAX_PENDING_PHOTOS_PER_TREE = 50
|
||||
|
||||
const MAX_STYLE_CHARS = 4000
|
||||
const styleSchema = z.record(z.string(), z.unknown()).refine(
|
||||
(value) => JSON.stringify(value).length <= MAX_STYLE_CHARS,
|
||||
{ message: 'style_too_large' },
|
||||
)
|
||||
|
||||
const annotationCreateSchema = z.object({
|
||||
type: z.enum(['drawing', 'sticker', 'text', 'photo']),
|
||||
x: z.number().finite(),
|
||||
y: z.number().finite(),
|
||||
content: z.string().min(1).max(50000),
|
||||
style: styleSchema.optional(),
|
||||
zIndex: z.number().int().optional(),
|
||||
})
|
||||
|
||||
const annotationUpdateSchema = z.object({
|
||||
x: z.number().finite().optional(),
|
||||
y: z.number().finite().optional(),
|
||||
content: z.string().min(1).max(50000).optional(),
|
||||
style: styleSchema.optional(),
|
||||
zIndex: z.number().int().optional(),
|
||||
})
|
||||
|
||||
export class AnnotationChangeError extends Error {
|
||||
constructor(public readonly code: string) {
|
||||
super(code)
|
||||
}
|
||||
}
|
||||
|
||||
type AnnotationChange = { action: string; entityId?: string | null; after?: unknown }
|
||||
|
||||
// Contenu vérifié comme à l'écriture directe : une photo doit être une photo de cet arbre
|
||||
function cleanContent(content: string, treeId: string): string {
|
||||
try {
|
||||
return sanitizeAnnotationContentForWrite(content, treeId)
|
||||
} catch (error) {
|
||||
if (error instanceof InvalidAnnotationContentError) throw new AnnotationChangeError('invalid_annotation_photo_path')
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// Vérifie une proposition d'annotation dès l'envoi, pour qu'une relecture n'échoue pas sur un contenu refusé
|
||||
export function validateAnnotationChange(change: AnnotationChange, treeId: string): void {
|
||||
if (change.action === 'create') {
|
||||
const parsed = annotationCreateSchema.safeParse(change.after)
|
||||
if (!parsed.success) throw new AnnotationChangeError('invalid_annotation_change')
|
||||
cleanContent(parsed.data.content, treeId)
|
||||
return
|
||||
}
|
||||
if (change.action === 'update') {
|
||||
if (!change.entityId) throw new AnnotationChangeError('invalid_annotation_change')
|
||||
const parsed = annotationUpdateSchema.safeParse(change.after)
|
||||
if (!parsed.success) throw new AnnotationChangeError('invalid_annotation_change')
|
||||
if (parsed.data.content !== undefined) cleanContent(parsed.data.content, treeId)
|
||||
return
|
||||
}
|
||||
if (change.action === 'delete') {
|
||||
if (!change.entityId) throw new AnnotationChangeError('invalid_annotation_change')
|
||||
return
|
||||
}
|
||||
throw new AnnotationChangeError('unsupported_change_action_for_annotation')
|
||||
}
|
||||
|
||||
// L'« après » d'une proposition d'annotation tel qu'il est gardé : contenu nettoyé comme à l'écriture directe
|
||||
// (photoPath canonique, sans adresse), pour qu'on le relise toujours de la même façon
|
||||
export function normalizedAnnotationAfter(change: AnnotationChange, treeId: string): unknown {
|
||||
const after = change.after
|
||||
if (!after || typeof after !== 'object' || Array.isArray(after)) return after
|
||||
const content = (after as { content?: unknown }).content
|
||||
if (typeof content !== 'string') return after
|
||||
return { ...(after as Record<string, unknown>), content: cleanContent(content, treeId) }
|
||||
}
|
||||
|
||||
// Identifiant de la photo d'une annotation (contenu JSON { photoPath }), ou null
|
||||
export function annotationPhotoId(after: unknown, treeId: string): string | null {
|
||||
if (!after || typeof after !== 'object' || Array.isArray(after)) return null
|
||||
const content = (after as { content?: unknown }).content
|
||||
if (typeof content !== 'string' || !content.startsWith('{')) return null
|
||||
try {
|
||||
const parsed = JSON.parse(content) as { photoPath?: unknown }
|
||||
const prefix = `/trees/${treeId}/annotation-photos/`
|
||||
if (typeof parsed.photoPath !== 'string' || !parsed.photoPath.startsWith(prefix)) return null
|
||||
const photoId = parsed.photoPath.slice(prefix.length)
|
||||
return /^[A-Za-z0-9-]+$/.test(photoId) ? photoId : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// Pose une annotation acceptée. La photo d'une famille devient définitive : sa ligne d'attente disparaît.
|
||||
export async function applyAnnotationChange(tx: Tx, treeId: string, change: AnnotationChange, actorUserId: string | null): Promise<{ entityId: string | null }> {
|
||||
validateAnnotationChange(change, treeId)
|
||||
|
||||
if (change.action === 'create') {
|
||||
const data = annotationCreateSchema.parse(change.after)
|
||||
const count = await tx.annotation.count({ where: { treeId, deletedAt: null } })
|
||||
if (count + 1 > MAX_ANNOTATIONS_PER_TREE) throw new AnnotationChangeError('annotation_limit_reached')
|
||||
const created = await tx.annotation.create({
|
||||
data: {
|
||||
treeId,
|
||||
type: data.type,
|
||||
x: data.x,
|
||||
y: data.y,
|
||||
content: cleanContent(data.content, treeId),
|
||||
style: (data.style ?? {}) as Prisma.InputJsonValue,
|
||||
zIndex: data.zIndex ?? 0,
|
||||
createdBy: actorUserId,
|
||||
},
|
||||
select: { id: true },
|
||||
})
|
||||
const photoId = annotationPhotoId(change.after, treeId)
|
||||
if (photoId) await tx.annotationPhotoUpload.deleteMany({ where: { id: photoId, treeId } })
|
||||
return { entityId: created.id }
|
||||
}
|
||||
|
||||
if (change.action === 'update') {
|
||||
const data = annotationUpdateSchema.parse(change.after)
|
||||
const patch: Prisma.AnnotationUpdateManyMutationInput = {}
|
||||
if (data.x !== undefined) patch.x = data.x
|
||||
if (data.y !== undefined) patch.y = data.y
|
||||
if (data.content !== undefined) patch.content = cleanContent(data.content, treeId)
|
||||
if (data.style !== undefined) patch.style = data.style as Prisma.InputJsonValue
|
||||
if (data.zIndex !== undefined) patch.zIndex = data.zIndex
|
||||
if (Object.keys(patch).length > 0) {
|
||||
await tx.annotation.updateMany({ where: { id: change.entityId as string, treeId, deletedAt: null }, data: patch })
|
||||
}
|
||||
const photoId = annotationPhotoId(change.after, treeId)
|
||||
if (photoId) await tx.annotationPhotoUpload.deleteMany({ where: { id: photoId, treeId } })
|
||||
return { entityId: change.entityId ?? null }
|
||||
}
|
||||
|
||||
await tx.annotation.updateMany({
|
||||
where: { id: change.entityId as string, treeId, deletedAt: null },
|
||||
data: { deletedAt: new Date() },
|
||||
})
|
||||
return { entityId: change.entityId ?? null }
|
||||
}
|
||||
|
||||
// Photos citées par les propositions d'annotation encore en attente sur cet arbre (hors une session donnée).
|
||||
// Lu dans le JSON décodé, pas dans son texte : un chemin échappé (\/trees\/…) reste reconnu. Un arbre a au plus
|
||||
// quelques centaines de propositions en attente.
|
||||
async function photosInPendingProposals(db: Db, treeId: string, excludeSessionId?: string): Promise<Set<string>> {
|
||||
const changes = await db.contributionChange.findMany({
|
||||
where: {
|
||||
entityType: 'annotation',
|
||||
session: { treeId, status: 'pending', ...(excludeSessionId ? { id: { not: excludeSessionId } } : {}) },
|
||||
},
|
||||
select: { afterJson: true },
|
||||
})
|
||||
const cited = new Set<string>()
|
||||
for (const change of changes) {
|
||||
const photoId = annotationPhotoId(change.afterJson, treeId)
|
||||
if (photoId) cited.add(photoId)
|
||||
}
|
||||
return cited
|
||||
}
|
||||
|
||||
// Photos d'une famille refusées pendant une relecture : effacées si leur ligne d'attente existe encore (une
|
||||
// acceptation la retire) et si aucune autre proposition en attente ne les cite. Appelé une fois, après toutes les
|
||||
// décisions. Renvoie les chemins à effacer une fois la transaction validée.
|
||||
export async function releaseRejectedPhotos(tx: Tx, treeId: string, rejectedAfters: unknown[], sessionId: string): Promise<string[]> {
|
||||
const candidates = new Set(rejectedAfters.map((after) => annotationPhotoId(after, treeId)).filter((id): id is string => Boolean(id)))
|
||||
if (candidates.size === 0) return []
|
||||
const cited = await photosInPendingProposals(tx, treeId, sessionId)
|
||||
const removed: string[] = []
|
||||
for (const photoId of candidates) {
|
||||
if (cited.has(photoId)) continue
|
||||
const upload = await tx.annotationPhotoUpload.findFirst({ where: { id: photoId, treeId }, select: { filePath: true } })
|
||||
if (!upload) continue
|
||||
await tx.annotationPhotoUpload.delete({ where: { id: photoId } })
|
||||
removed.push(upload.filePath)
|
||||
}
|
||||
return removed
|
||||
}
|
||||
|
||||
// Envois de photos jamais proposés depuis 7 jours : effacés. Appelé à chaque nouvel envoi de la famille, sur
|
||||
// cet arbre seulement. Renvoie les chemins à effacer.
|
||||
export async function sweepStalePendingPhotos(db: Db, treeId: string, now = new Date()): Promise<string[]> {
|
||||
const stale = await db.annotationPhotoUpload.findMany({
|
||||
where: { treeId, createdAt: { lt: new Date(now.getTime() - PENDING_PHOTO_TTL_MS) } },
|
||||
select: { id: true, filePath: true },
|
||||
})
|
||||
if (stale.length === 0) return []
|
||||
const cited = await photosInPendingProposals(db, treeId)
|
||||
const removed: string[] = []
|
||||
for (const upload of stale) {
|
||||
if (cited.has(upload.id)) continue
|
||||
await db.annotationPhotoUpload.delete({ where: { id: upload.id } })
|
||||
removed.push(upload.filePath)
|
||||
}
|
||||
return removed
|
||||
}
|
||||
|
||||
// Réserve une place d'envoi en attente sous un verrou par arbre : deux envois simultanés ne dépassent pas le
|
||||
// plafond. Renvoie false si l'arbre est plein. La ligne est créée avant l'écriture du fichier ; si l'écriture
|
||||
// échoue, l'appelant la retire (forgetPendingPhoto).
|
||||
export async function reservePendingPhoto(prisma: PrismaClient, treeId: string, photoId: string, filePath: string): Promise<boolean> {
|
||||
return prisma.$transaction(async (tx) => {
|
||||
await tx.$executeRaw`SELECT pg_advisory_xact_lock(hashtext(${'annotation-photos:' + treeId}))`
|
||||
if (await tx.annotationPhotoUpload.count({ where: { treeId } }) >= MAX_PENDING_PHOTOS_PER_TREE) return false
|
||||
await tx.annotationPhotoUpload.create({ data: { id: photoId, treeId, filePath } })
|
||||
return true
|
||||
})
|
||||
}
|
||||
|
||||
export async function forgetPendingPhoto(db: Db, photoId: string): Promise<void> {
|
||||
await db.annotationPhotoUpload.deleteMany({ where: { id: photoId } })
|
||||
}
|
||||
|
||||
// Chemin relatif sûr d'une photo d'annotation (sous <treeId>/annotation-photos/)
|
||||
export function annotationPhotoRelativePath(treeId: string, photoId: string, extension: string): string {
|
||||
return path.posix.join(treeId, 'annotation-photos', `${photoId}${extension}`)
|
||||
}
|
||||
+17
-5
@@ -1,11 +1,23 @@
|
||||
import bcrypt from 'bcryptjs'
|
||||
// bcrypt natif (binaire précompilé) : le calcul passe sur les fils de libuv, la boucle de l'API garde la main.
|
||||
// bcryptjs calculait en JavaScript : 8 vérifications simultanées retardaient chaque requête de 0,7 s en moyenne.
|
||||
// Mêmes empreintes $2a$/$2b$ : les mots de passe enregistrés restent valables.
|
||||
import { hash, verify } from '@node-rs/bcrypt'
|
||||
|
||||
import { env } from '../config/env.js'
|
||||
|
||||
const HASH_ROUNDS = 12
|
||||
|
||||
export async function hashPassword(value: string): Promise<string> {
|
||||
return bcrypt.hash(value, HASH_ROUNDS)
|
||||
return hash(value, { cost: HASH_ROUNDS })
|
||||
}
|
||||
|
||||
export async function verifyPassword(value: string, hash: string): Promise<boolean> {
|
||||
return bcrypt.compare(value, hash)
|
||||
}
|
||||
export async function verifyPassword(value: string, storedHash: string): Promise<boolean> {
|
||||
return verify(value, storedHash)
|
||||
}
|
||||
|
||||
// Un compte à mot de passe se confirme avec son mot de passe seulement si la connexion par mot de passe est ouverte.
|
||||
// Avec PASSWORD_LOGIN=false, un compte relié à un fournisseur OIDC (et qui avait un mot de passe) ne peut plus le
|
||||
// redonner : il se confirme par son email, comme un compte né du fournisseur, après une connexion récente.
|
||||
export function confirmsWithPassword(passwordHash: string | null | undefined): boolean {
|
||||
return Boolean(passwordHash) && env.PASSWORD_LOGIN
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
// Cadrage d'un portrait : centre (proportions de l'image), zoom, et forme du cadre si on l'a choisie.
|
||||
// Zoom 1 = l'image entière recouvre le cadre. Les bornes qui empêchent le vide sont appliquées à
|
||||
// l'affichage (frontend, portraitCrop.js), le serveur vérifie seulement la forme et les plages.
|
||||
export const FRAME_SHAPES = ['round', 'square', 'polaroid', 'portrait', 'landscape'] as const
|
||||
export type AvatarCrop = { x: number; y: number; zoom: number; shape?: (typeof FRAME_SHAPES)[number] }
|
||||
|
||||
export const AVATAR_CROP_MAX_ZOOM = 4
|
||||
|
||||
export const avatarCropInputSchema = z.object({
|
||||
crop: z
|
||||
.object({
|
||||
x: z.number().min(0).max(1),
|
||||
y: z.number().min(0).max(1),
|
||||
zoom: z.number().min(1).max(AVATAR_CROP_MAX_ZOOM),
|
||||
shape: z.enum(FRAME_SHAPES).optional(),
|
||||
})
|
||||
.nullable(),
|
||||
})
|
||||
|
||||
const round4 = (value: number) => Math.round(value * 10000) / 10000
|
||||
|
||||
// Forme à écrire en base. Le cadrage par défaut, sans forme choisie, se stocke comme absence de cadrage (null).
|
||||
export function toStoredAvatarCrop(crop: AvatarCrop | null): AvatarCrop | null {
|
||||
if (!crop) return null
|
||||
const normalized = { x: round4(crop.x), y: round4(crop.y), zoom: round4(crop.zoom) }
|
||||
if (crop.shape) return { ...normalized, shape: crop.shape }
|
||||
if (normalized.x === 0.5 && normalized.y === 0.5 && normalized.zoom === 1) return null
|
||||
return normalized
|
||||
}
|
||||
|
||||
// Lecture de la colonne JSON : tout ce qui ne respecte pas la forme est ignoré (portrait affiché tel quel).
|
||||
export function readAvatarCrop(value: unknown): AvatarCrop | null {
|
||||
const parsed = avatarCropInputSchema.shape.crop.safeParse(value)
|
||||
return parsed.success ? parsed.data : null
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import { encode } from 'blurhash'
|
||||
import sharp from 'sharp'
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
|
||||
// Aperçus flous (BlurHash) : une courte chaîne par photo, que le navigateur décode en image floue aux bonnes
|
||||
// couleurs pendant que la vraie se charge. Les photos partent en taille réelle, sans miniature : sur un réseau
|
||||
// lent, une vignette restait un carré vide.
|
||||
//
|
||||
// Calculé à l'envoi d'une photo ou d'un portrait (routes/media.ts). Les autres chemins (Immich, import GEDCOM,
|
||||
// propositions acceptées) et les photos d'avant cette version sont rattrapés en tâche de fond. Une image
|
||||
// illisible reçoit une chaîne vide, pour ne pas être relue à chaque passage.
|
||||
|
||||
// Assez petit pour un calcul rapide ; l'aperçu garde les proportions de la photo
|
||||
const SAMPLE_MAX = 32
|
||||
const COMPONENTS_X = 4
|
||||
const COMPONENTS_Y = 3
|
||||
|
||||
export async function computeBlurhash(buf: Buffer): Promise<string | null> {
|
||||
try {
|
||||
const { data, info } = await sharp(buf, { limitInputPixels: 50_000_000, failOn: 'error' })
|
||||
.rotate()
|
||||
.resize(SAMPLE_MAX, SAMPLE_MAX, { fit: 'inside' })
|
||||
.ensureAlpha()
|
||||
.raw()
|
||||
.toBuffer({ resolveWithObject: true })
|
||||
return encode(new Uint8ClampedArray(data), info.width, info.height, COMPONENTS_X, COMPONENTS_Y)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
async function hashStoredFile(storageRoot: string, relativePath: string): Promise<string> {
|
||||
const absolutePath = path.resolve(storageRoot, relativePath)
|
||||
if (!absolutePath.startsWith(storageRoot + path.sep)) return ''
|
||||
const buf = await readFile(absolutePath).catch(() => null)
|
||||
return (buf && await computeBlurhash(buf)) || ''
|
||||
}
|
||||
|
||||
const BATCH = 25
|
||||
const PAUSE_MS = 60_000
|
||||
|
||||
// Un lot de photos puis de portraits sans aperçu ; renvoie le nombre traité
|
||||
export async function fillMissingBlurhashes(app: FastifyInstance, storageRoot: string): Promise<number> {
|
||||
const medias = await app.prisma.mediaItem.findMany({
|
||||
where: { type: 'photo', blurhash: null, deletedAt: null, NOT: { mimeType: 'video/youtube' } },
|
||||
select: { id: true, filePath: true },
|
||||
take: BATCH,
|
||||
})
|
||||
for (const media of medias) {
|
||||
const blurhash = await hashStoredFile(storageRoot, media.filePath)
|
||||
await app.prisma.mediaItem.updateMany({ where: { id: media.id, blurhash: null }, data: { blurhash } })
|
||||
}
|
||||
|
||||
const persons = await app.prisma.person.findMany({
|
||||
where: { avatarPath: { not: null }, avatarBlurhash: null, deletedAt: null },
|
||||
select: { id: true, avatarPath: true },
|
||||
take: BATCH,
|
||||
})
|
||||
for (const person of persons) {
|
||||
const avatarBlurhash = await hashStoredFile(storageRoot, person.avatarPath as string)
|
||||
// Le portrait a pu changer pendant le calcul : on n'écrit que s'il est toujours le même
|
||||
await app.prisma.person.updateMany({ where: { id: person.id, avatarPath: person.avatarPath, avatarBlurhash: null }, data: { avatarBlurhash } })
|
||||
}
|
||||
|
||||
return medias.length + persons.length
|
||||
}
|
||||
|
||||
// Tâche de fond : enchaîne les lots tant qu'il en reste, puis repasse toutes les minutes
|
||||
export function startBlurhashFiller(app: FastifyInstance, storageRoot: string) {
|
||||
let timer: NodeJS.Timeout | null = null
|
||||
let stopped = false
|
||||
const run = async () => {
|
||||
let done = 0
|
||||
try {
|
||||
done = await fillMissingBlurhashes(app, storageRoot)
|
||||
} catch (error) {
|
||||
app.log.warn({ err: error }, 'aperçus flous : lot en échec')
|
||||
}
|
||||
if (!stopped) {
|
||||
timer = setTimeout(run, done >= BATCH ? 0 : PAUSE_MS)
|
||||
timer.unref()
|
||||
}
|
||||
}
|
||||
timer = setTimeout(run, 5_000)
|
||||
timer.unref()
|
||||
app.addHook('onClose', async () => {
|
||||
stopped = true
|
||||
if (timer) clearTimeout(timer)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
// Une date corrigée à la main perd la précision lue dans le GEDCOM (« vers 1879 », « entre 1914 et 1918 ») :
|
||||
// elle décrivait l'ancienne date, pas celle qu'on vient de saisir. Une date renvoyée telle quelle la garde.
|
||||
|
||||
const sameDay = (a: Date | null | undefined, b: Date | null | undefined) =>
|
||||
(a ? a.toISOString().slice(0, 10) : null) === (b ? b.toISOString().slice(0, 10) : null)
|
||||
|
||||
type PersonDates = { birthDate: Date | null; deathDate: Date | null }
|
||||
|
||||
export function personPrecisionResets(current: PersonDates | null, next: Partial<PersonDates>) {
|
||||
const out: { birthDatePrecision?: null; birthDateEnd?: null; deathDatePrecision?: null; deathDateEnd?: null } = {}
|
||||
if (!current) return out
|
||||
if (next.birthDate !== undefined && !sameDay(current.birthDate, next.birthDate)) {
|
||||
out.birthDatePrecision = null
|
||||
out.birthDateEnd = null
|
||||
}
|
||||
if (next.deathDate !== undefined && !sameDay(current.deathDate, next.deathDate)) {
|
||||
out.deathDatePrecision = null
|
||||
out.deathDateEnd = null
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
export function unionPrecisionResets(current: { startDate: Date | null } | null, next: { startDate?: Date | null }) {
|
||||
if (!current || next.startDate === undefined || sameDay(current.startDate, next.startDate)) return {}
|
||||
return { startDatePrecision: null }
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Prisma, PrismaClient } from '@prisma/client'
|
||||
import { Prisma, type PrismaClient } from '../generated/prisma/client.js'
|
||||
|
||||
type Db = PrismaClient | Prisma.TransactionClient
|
||||
|
||||
@@ -32,7 +32,7 @@ export async function softDeletePersonCascade(
|
||||
|
||||
await db.person.updateMany({
|
||||
where: { id: personId, treeId, deletedAt: null },
|
||||
data: { deletedAt: now, updatedBy: actorUserId, avatarPath: null, avatarMimeType: null },
|
||||
data: { deletedAt: now, updatedBy: actorUserId, avatarPath: null, avatarMimeType: null, avatarCrop: Prisma.DbNull, avatarBlurhash: null, immichPersonId: null },
|
||||
})
|
||||
|
||||
const unions = await db.union.findMany({
|
||||
@@ -47,7 +47,15 @@ export async function softDeletePersonCascade(
|
||||
|
||||
const medias = await db.mediaItem.findMany({
|
||||
where: { treeId, personId, deletedAt: null },
|
||||
select: { filePath: true, thumbPath: true },
|
||||
select: { id: true, filePath: true, thumbPath: true },
|
||||
})
|
||||
|
||||
// Identifications : la personne disparaît des photos des autres, et ses souvenirs n'ont plus personne
|
||||
await db.mediaPersonTag.deleteMany({
|
||||
where: {
|
||||
treeId,
|
||||
OR: [{ personId }, ...(medias.length > 0 ? [{ mediaId: { in: medias.map((media) => media.id) } }] : [])],
|
||||
},
|
||||
})
|
||||
|
||||
const [deletedUnions, deletedLinks, deletedMedia] = await Promise.all([
|
||||
@@ -72,6 +80,15 @@ export async function softDeletePersonCascade(
|
||||
where: { treeId, personId, deletedAt: null },
|
||||
data: { deletedAt: now },
|
||||
}),
|
||||
// Événements de vie de la personne et de ses unions
|
||||
db.lifeEvent.updateMany({
|
||||
where: {
|
||||
treeId,
|
||||
deletedAt: null,
|
||||
OR: [{ personId }, ...(unionIds.length > 0 ? [{ unionId: { in: unionIds } }] : [])],
|
||||
},
|
||||
data: { deletedAt: now },
|
||||
}),
|
||||
])
|
||||
|
||||
// Racine de l'arbre supprimée : le graphe repart sans racine plutôt que sur une personne effacée
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
// Dates GEDCOM : « 15 JAN 1900 », mais aussi « ABT 1900 » (vers), « BEF », « AFT », « BET 1794 AND 1796 »,
|
||||
// « FROM … TO … », « INT 1900 (texte) », les doubles années « 12 FEB 1700/01 », le calendrier julien
|
||||
// (« @#DJULIAN@ 1563 ») et le calendrier républicain (« @#DFRENCH R@ 18 BRUM 8 », converti en grégorien).
|
||||
// On renvoie une date ISO (année, année-mois ou jour), sa précision et le texte d'origine.
|
||||
|
||||
export type GedcomDatePrecision = 'exact' | 'about' | 'estimated' | 'calculated' | 'before' | 'after' | 'between' | 'from' | 'to' | 'interpreted'
|
||||
|
||||
export type ParsedGedcomDate = {
|
||||
iso: string
|
||||
precision: GedcomDatePrecision
|
||||
endIso: string | null
|
||||
text: string
|
||||
}
|
||||
|
||||
const MONTHS: Record<string, number> = {
|
||||
JAN: 1, FEB: 2, MAR: 3, APR: 4, MAY: 5, JUN: 6, JUL: 7, AUG: 8, SEP: 9, OCT: 10, NOV: 11, DEC: 12,
|
||||
}
|
||||
|
||||
// Calendrier républicain : début de chaque année (an I à XIV), années sextiles III, VII et XI
|
||||
const FRENCH_YEAR_START: Record<number, string> = {
|
||||
1: '1792-09-22', 2: '1793-09-22', 3: '1794-09-22', 4: '1795-09-23', 5: '1796-09-22', 6: '1797-09-22',
|
||||
7: '1798-09-22', 8: '1799-09-23', 9: '1800-09-23', 10: '1801-09-23', 11: '1802-09-23', 12: '1803-09-24',
|
||||
13: '1804-09-23', 14: '1805-09-23',
|
||||
}
|
||||
const FRENCH_MONTHS: Record<string, number> = {
|
||||
VEND: 1, BRUM: 2, FRIM: 3, NIVO: 4, PLUV: 5, VENT: 6, GERM: 7, FLOR: 8, PRAI: 9, MESS: 10, THER: 11, FRUC: 12, COMP: 13,
|
||||
}
|
||||
|
||||
const pad = (n: number) => String(n).padStart(2, '0')
|
||||
|
||||
function frenchToIso(day: number | null, month: number | null, year: number): string | null {
|
||||
const start = FRENCH_YEAR_START[year]
|
||||
if (!start) return null
|
||||
if (!month) return start.slice(0, 4)
|
||||
const offset = (month - 1) * 30 + ((day ?? 1) - 1)
|
||||
const date = new Date(`${start}T00:00:00Z`)
|
||||
date.setUTCDate(date.getUTCDate() + offset)
|
||||
const iso = date.toISOString().slice(0, 10)
|
||||
return day ? iso : iso.slice(0, 7)
|
||||
}
|
||||
|
||||
// Une date simple, après le qualificatif : jour, mois, année, avec son calendrier
|
||||
function parseSimple(raw: string): string | null {
|
||||
let text = raw.trim().toUpperCase()
|
||||
let calendar = 'GREGORIAN'
|
||||
const escape = text.match(/^@#D([A-Z ]+?)@\s*/)
|
||||
if (escape) {
|
||||
calendar = escape[1].trim()
|
||||
text = text.slice(escape[0].length)
|
||||
}
|
||||
text = text.replace(/\s+B\.?C\.?$/, '').trim()
|
||||
const parts = text.split(/\s+/).filter(Boolean)
|
||||
if (parts.length === 0 || parts.length > 3) return null
|
||||
|
||||
if (calendar === 'FRENCH R') {
|
||||
const year = Number(parts[parts.length - 1])
|
||||
const month = parts.length >= 2 ? FRENCH_MONTHS[parts[parts.length - 2]] ?? null : null
|
||||
const day = parts.length === 3 ? Number(parts[0]) : null
|
||||
if (!Number.isInteger(year) || (parts.length >= 2 && !month) || (day !== null && !(day >= 1 && day <= 30))) return null
|
||||
return frenchToIso(day, month, year)
|
||||
}
|
||||
if (calendar !== 'GREGORIAN' && calendar !== 'JULIAN') return null
|
||||
|
||||
// Double année : « 1700/01 » = 1701 en style moderne
|
||||
const yearMatch = parts[parts.length - 1].match(/^(\d{3,4})(?:\/(\d{1,2}))?$/)
|
||||
if (!yearMatch) return null
|
||||
let year = Number(yearMatch[1])
|
||||
if (yearMatch[2]) {
|
||||
const suffix = yearMatch[2]
|
||||
year = Number(String(year).slice(0, String(year).length - suffix.length) + suffix)
|
||||
if (year < Number(yearMatch[1])) year += 10 ** suffix.length
|
||||
}
|
||||
const yearText = String(year).padStart(4, '0')
|
||||
if (parts.length === 1) return yearText
|
||||
const month = MONTHS[parts[parts.length - 2]]
|
||||
if (!month) return null
|
||||
if (parts.length === 2) return `${yearText}-${pad(month)}`
|
||||
const day = Number(parts[0])
|
||||
if (!(day >= 1 && day <= 31)) return null
|
||||
return `${yearText}-${pad(month)}-${pad(day)}`
|
||||
}
|
||||
|
||||
export function parseGedcomDate(value: string | null | undefined): ParsedGedcomDate | null {
|
||||
const text = (value ?? '').trim()
|
||||
if (!text) return null
|
||||
const upper = text.toUpperCase()
|
||||
|
||||
const range = upper.match(/^BET\s+(.+?)\s+AND\s+(.+)$/) ?? upper.match(/^FROM\s+(.+?)\s+TO\s+(.+)$/)
|
||||
if (range) {
|
||||
const iso = parseSimple(range[1])
|
||||
const endIso = parseSimple(range[2])
|
||||
if (!iso && !endIso) return null
|
||||
return { iso: (iso ?? endIso)!, endIso: iso ? endIso : null, precision: upper.startsWith('BET') ? 'between' : 'from', text }
|
||||
}
|
||||
|
||||
const qualifiers: Record<string, GedcomDatePrecision> = {
|
||||
ABT: 'about', EST: 'estimated', CAL: 'calculated', BEF: 'before', AFT: 'after', FROM: 'from', TO: 'to', INT: 'interpreted',
|
||||
}
|
||||
const qualified = upper.match(/^(ABT|EST|CAL|BEF|AFT|FROM|TO|INT)\.?\s+(.+)$/)
|
||||
if (qualified) {
|
||||
const rest = qualified[1] === 'INT' ? qualified[2].replace(/\s*\(.*\)\s*$/, '') : qualified[2]
|
||||
const iso = parseSimple(rest)
|
||||
return iso ? { iso, endIso: null, precision: qualifiers[qualified[1]], text } : null
|
||||
}
|
||||
|
||||
const iso = parseSimple(upper.replace(/\s*\(.*\)\s*$/, ''))
|
||||
return iso ? { iso, endIso: null, precision: 'exact', text } : null
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
// Événements de vie lus dans un GEDCOM. Naissance, décès et mariage gardent leur date et leur lieu sur la
|
||||
// personne ou l'union : on n'en tire ici que la précision, le lieu de décès, les sources et les notes.
|
||||
// Les autres événements (baptême, résidence, métier, inhumation, divorce…) deviennent des LifeEvent.
|
||||
|
||||
import { parseGedcomDate } from './gedcom-dates.js'
|
||||
import { joinedText, noteText, sourceLabel } from './gedcom-photos.js'
|
||||
import type { GedcomPhotoNode, GedcomRecords } from './gedcom-photos.js'
|
||||
|
||||
type Node = GedcomPhotoNode
|
||||
|
||||
export type ImportedEvent = {
|
||||
type: string
|
||||
label: string | null
|
||||
date: Date | null
|
||||
dateEnd: Date | null
|
||||
datePrecision: string | null
|
||||
dateText: string | null
|
||||
place: string | null
|
||||
description: string | null
|
||||
notes: string | null
|
||||
sources: string | null
|
||||
}
|
||||
|
||||
// Balises de la norme et variantes courantes (Gramps, Heredis, Geneatique, RootsMagic)
|
||||
export const PERSON_EVENT_TYPES: Record<string, string> = {
|
||||
BAPM: 'baptism', CHR: 'baptism', BURI: 'burial', CREM: 'cremation', RESI: 'residence', OCCU: 'occupation',
|
||||
EDUC: 'education', GRAD: 'graduation', RELI: 'religion', CONF: 'confirmation', FCOM: 'first_communion',
|
||||
BARM: 'bar_mitzvah', BASM: 'bat_mitzvah', ORDN: 'ordination', ADOP: 'adoption', EMIG: 'emigration',
|
||||
IMMI: 'immigration', NATU: 'naturalization', CENS: 'census', TITL: 'title', PROP: 'property',
|
||||
RETI: 'retirement', WILL: 'will', PROB: 'probate', _MILT: 'military', _MDCL: 'medical', _DEG: 'degree',
|
||||
EVEN: 'custom', FACT: 'custom',
|
||||
}
|
||||
|
||||
export const FAMILY_EVENT_TYPES: Record<string, string> = {
|
||||
DIV: 'divorce', DIVF: 'divorce_filed', ANUL: 'annulment', ENGA: 'engagement', MARB: 'marriage_banns',
|
||||
MARC: 'marriage_contract', MARL: 'marriage_license', MARS: 'marriage_settlement', EVEN: 'custom', FACT: 'custom',
|
||||
}
|
||||
|
||||
const MAX_EVENTS_PER_OWNER = 200
|
||||
const clip = (value: string | null | undefined, max: number) => {
|
||||
const text = (value ?? '').replace(/\s+\n/g, '\n').trim()
|
||||
if (!text) return null
|
||||
return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text
|
||||
}
|
||||
|
||||
const child = (node: Node | undefined, tag: string) => node?.children.find((c) => c.tag === tag)
|
||||
|
||||
// Même règle que le lieu de naissance : noms seulement, sans case vide ni code INSEE ou postal
|
||||
export function cleanPlace(value: string | null | undefined): string | null {
|
||||
if (!value) return null
|
||||
const parts: string[] = []
|
||||
for (const raw of value.split(',')) {
|
||||
const part = raw.trim()
|
||||
if (!part || /^(\d{4,5}|2[AB]\d{3})$/i.test(part)) continue
|
||||
if (parts.length && parts[parts.length - 1].toLowerCase() === part.toLowerCase()) continue
|
||||
parts.push(part)
|
||||
}
|
||||
return parts.length ? parts.join(', ') : null
|
||||
}
|
||||
|
||||
export function isoToDbDate(iso: string | null | undefined): Date | null {
|
||||
if (!iso) return null
|
||||
if (/^\d{4}$/.test(iso)) return new Date(`${iso}-01-01T00:00:00.000Z`)
|
||||
if (/^\d{4}-\d{2}$/.test(iso)) return new Date(`${iso}-01T00:00:00.000Z`)
|
||||
return new Date(`${iso}T00:00:00.000Z`)
|
||||
}
|
||||
|
||||
function eventNotes(node: Node, records: GedcomRecords): string | null {
|
||||
const texts = node.children.filter((c) => c.tag === 'NOTE').map((n) => noteText(n, records)).filter(Boolean)
|
||||
return clip(texts.join('\n\n'), 4000)
|
||||
}
|
||||
|
||||
function eventSources(node: Node, records: GedcomRecords): string | null {
|
||||
const labels = node.children.filter((c) => c.tag === 'SOUR').map((s) => sourceLabel(s, records)).filter(Boolean) as string[]
|
||||
return clip([...new Set(labels)].join('\n'), 4000)
|
||||
}
|
||||
|
||||
// Ce qu'on lit d'un événement : date et précision, lieu (ou adresse), description, notes, sources
|
||||
export function readEvent(node: Node, type: string, records: GedcomRecords): ImportedEvent {
|
||||
const dateText = child(node, 'DATE')?.value ?? null
|
||||
const parsed = parseGedcomDate(dateText)
|
||||
const addr = child(node, 'ADDR')
|
||||
const address = [joinedText(addr).replace(/\n+/g, ', '), ...['CITY', 'STAE', 'CTRY'].map((tag) => child(addr, tag)?.value ?? '')]
|
||||
.map((part) => part.trim())
|
||||
.filter(Boolean)
|
||||
.join(', ')
|
||||
const place = cleanPlace(child(node, 'PLAC')?.value) ?? clip(address, 300)
|
||||
const typeLabel = joinedText(child(node, 'TYPE'))
|
||||
const value = node.value && node.value.toUpperCase() !== 'Y' ? node.value : ''
|
||||
return {
|
||||
type,
|
||||
label: type === 'custom' ? clip(typeLabel || value, 120) : null,
|
||||
date: isoToDbDate(parsed?.iso),
|
||||
dateEnd: isoToDbDate(parsed?.endIso),
|
||||
datePrecision: parsed && parsed.precision !== 'exact' ? parsed.precision : null,
|
||||
dateText: parsed && parsed.precision === 'exact' ? null : clip(dateText, 120),
|
||||
place: clip(place, 300),
|
||||
description: clip(type === 'custom' && !typeLabel ? '' : value, 1000),
|
||||
notes: eventNotes(node, records),
|
||||
sources: eventSources(node, records),
|
||||
}
|
||||
}
|
||||
|
||||
export type PersonExtras = {
|
||||
birthDatePrecision: string | null
|
||||
birthDateEnd: Date | null
|
||||
deathDatePrecision: string | null
|
||||
deathDateEnd: Date | null
|
||||
deathPlace: string | null
|
||||
nickname: string | null
|
||||
events: ImportedEvent[]
|
||||
}
|
||||
|
||||
const hasDetails = (e: ImportedEvent) => Boolean(e.notes || e.sources)
|
||||
|
||||
export function personExtras(indi: Node, records: GedcomRecords): PersonExtras {
|
||||
const events: ImportedEvent[] = []
|
||||
const birth = child(indi, 'BIRT')
|
||||
const death = child(indi, 'DEAT')
|
||||
const birthDate = parseGedcomDate(child(birth, 'DATE')?.value)
|
||||
const deathDate = parseGedcomDate(child(death, 'DATE')?.value)
|
||||
|
||||
// Naissance et décès : leurs sources et notes, sans recopier la date ni le lieu
|
||||
for (const [node, type] of [[birth, 'birth'], [death, 'death']] as const) {
|
||||
if (!node) continue
|
||||
const event = readEvent(node, type, records)
|
||||
if (hasDetails(event)) events.push({ ...event, date: null, dateEnd: null, datePrecision: null, dateText: null, place: null, description: null })
|
||||
}
|
||||
|
||||
// La première profession reste aussi sur la fiche (champ « profession ») et figure quand même ici
|
||||
for (const c of indi.children) {
|
||||
const type = PERSON_EVENT_TYPES[c.tag]
|
||||
if (!type || events.length >= MAX_EVENTS_PER_OWNER) continue
|
||||
const event = readEvent(c, type, records)
|
||||
if (!event.date && !event.place && !event.description && !event.label && !hasDetails(event)) continue
|
||||
events.push(event)
|
||||
}
|
||||
|
||||
const nameNode = child(indi, 'NAME')
|
||||
return {
|
||||
birthDatePrecision: birthDate && birthDate.precision !== 'exact' ? birthDate.precision : null,
|
||||
birthDateEnd: isoToDbDate(birthDate?.endIso),
|
||||
deathDatePrecision: deathDate && deathDate.precision !== 'exact' ? deathDate.precision : null,
|
||||
deathDateEnd: isoToDbDate(deathDate?.endIso),
|
||||
deathPlace: clip(cleanPlace(child(death, 'PLAC')?.value), 200),
|
||||
nickname: clip(child(nameNode, 'NICK')?.value ?? child(indi, 'NICK')?.value, 120),
|
||||
events,
|
||||
}
|
||||
}
|
||||
|
||||
export type UnionExtras = {
|
||||
startPlace: string | null
|
||||
startDatePrecision: string | null
|
||||
events: ImportedEvent[]
|
||||
}
|
||||
|
||||
export function familyExtras(fam: Node, records: GedcomRecords): UnionExtras {
|
||||
const marriage = child(fam, 'MARR')
|
||||
const date = parseGedcomDate(child(marriage, 'DATE')?.value)
|
||||
const events: ImportedEvent[] = []
|
||||
if (marriage) {
|
||||
const event = readEvent(marriage, 'marriage', records)
|
||||
if (hasDetails(event)) events.push({ ...event, date: null, dateEnd: null, datePrecision: null, dateText: null, place: null, description: null })
|
||||
}
|
||||
for (const c of fam.children) {
|
||||
const type = FAMILY_EVENT_TYPES[c.tag]
|
||||
if (!type || events.length >= MAX_EVENTS_PER_OWNER) continue
|
||||
const event = readEvent(c, type, records)
|
||||
// « 1 DIV Y » sans rien d'autre dit quand même qu'il y a eu divorce
|
||||
if (!event.date && !event.place && !event.description && !event.label && !hasDetails(event) && c.value.toUpperCase() !== 'Y') continue
|
||||
events.push(event)
|
||||
}
|
||||
return {
|
||||
startPlace: clip(cleanPlace(child(marriage, 'PLAC')?.value), 300),
|
||||
startDatePrecision: date && date.precision !== 'exact' ? date.precision : null,
|
||||
events,
|
||||
}
|
||||
}
|
||||
|
||||
// Adoption déclarée sous l'enfant : « 1 FAMC @F1@ » / « 2 PEDI adopted »
|
||||
export function adoptedFamilies(indi: Node): Set<string> {
|
||||
const out = new Set<string>()
|
||||
for (const famc of indi.children.filter((c) => c.tag === 'FAMC')) {
|
||||
const pedi = (child(famc, 'PEDI')?.value || '').toLowerCase()
|
||||
const pointer = famc.value.match(/^@([^@]+)@$/)?.[1]
|
||||
if (pointer && pedi === 'adopted') out.add(pointer)
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
// Photos et documents cités par un fichier GEDCOM. Le fichier ne contient pas les fichiers, seulement leur
|
||||
// chemin sur l'ordinateur de la personne (« C:\Généalogie\Photos\jean.jpg »). L'import renvoie ces chemins
|
||||
// pour chaque personne, et l'app les relie aux fichiers du dossier que la personne choisit, sans rien
|
||||
// garder en base : le portrait devient la photo de la fiche, le reste des souvenirs.
|
||||
|
||||
export type GedcomPhotoNode = {
|
||||
xref?: string
|
||||
tag: string
|
||||
value: string
|
||||
rawValue?: string
|
||||
children: GedcomPhotoNode[]
|
||||
}
|
||||
|
||||
const IMAGE_EXTENSIONS = new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'bmp', 'tif', 'tiff', 'heic', 'heif'])
|
||||
const MAX_PATH_LENGTH = 500
|
||||
|
||||
function child(node: GedcomPhotoNode | undefined, tag: string): GedcomPhotoNode | undefined {
|
||||
return node?.children.find((c) => c.tag === tag)
|
||||
}
|
||||
|
||||
function isImagePath(value: string): boolean {
|
||||
if (!value || /^[a-z][a-z0-9+.-]*:\/\//i.test(value)) return false
|
||||
const name = value.split(/[\\/]/).pop() || ''
|
||||
const dot = name.lastIndexOf('.')
|
||||
return dot > 0 && IMAGE_EXTENSIONS.has(name.slice(dot + 1).toLowerCase())
|
||||
}
|
||||
|
||||
// Un OBJE est soit écrit sous la personne (« 1 OBJE » puis « 2 FILE »), soit un renvoi (« 1 OBJE @M1@ »)
|
||||
// vers un enregistrement « 0 @M1@ OBJE » en fin de fichier. Les logiciels marquent la photo principale
|
||||
// par _PRIM Y (sous OBJE ou sous FILE) : elle passe devant, sinon la première image citée.
|
||||
export function photoPathForPerson(
|
||||
indi: GedcomPhotoNode,
|
||||
objeByXref: Map<string, GedcomPhotoNode>,
|
||||
): string | null {
|
||||
// Family Tree Maker désigne la photo principale par « 1 _PHOTO @O1@ » sous la personne
|
||||
const photoPointer = child(indi, '_PHOTO')?.value.match(/^@([^@]+)@$/)?.[1]
|
||||
const flagged = photoPointer ? objeByXref.get(photoPointer) : undefined
|
||||
for (const file of flagged?.children.filter((c) => c.tag === 'FILE') ?? []) {
|
||||
const filePath = file.value.trim()
|
||||
if (isImagePath(filePath) && filePath.length <= MAX_PATH_LENGTH) return filePath
|
||||
}
|
||||
let first: string | null = null
|
||||
for (const ref of indi.children) {
|
||||
if (ref.tag !== 'OBJE') continue
|
||||
const pointer = ref.value.match(/^@([^@]+)@$/)
|
||||
const obje = pointer ? objeByXref.get(pointer[1]) : ref
|
||||
if (!obje) continue
|
||||
const isPrimary = (node: GedcomPhotoNode | undefined) => child(node, '_PRIM')?.value?.toUpperCase().startsWith('Y')
|
||||
for (const file of obje.children.filter((c) => c.tag === 'FILE')) {
|
||||
const filePath = file.value.trim()
|
||||
if (!isImagePath(filePath) || filePath.length > MAX_PATH_LENGTH) continue
|
||||
if (isPrimary(ref) || isPrimary(obje) || isPrimary(file)) return filePath
|
||||
first ??= filePath
|
||||
}
|
||||
}
|
||||
return first
|
||||
}
|
||||
|
||||
export function indexObjeRecords(roots: GedcomPhotoNode[]): Map<string, GedcomPhotoNode> {
|
||||
const map = new Map<string, GedcomPhotoNode>()
|
||||
for (const node of roots) {
|
||||
if (node.tag === 'OBJE' && node.xref) map.set(node.xref, node)
|
||||
}
|
||||
return map
|
||||
}
|
||||
|
||||
// ---------- Souvenirs : tous les fichiers cités pour une personne ----------
|
||||
// Un logiciel de généalogie accroche ses fichiers à plusieurs endroits : sous la personne (« 1 OBJE »), sous
|
||||
// un événement (« 1 BIRT » / « 2 OBJE »), sous une source citée (« 2 SOUR @S1@ » / « 3 OBJE »), dans la
|
||||
// source elle-même (« 0 @S1@ SOUR » / « 1 OBJE ») ou sous la famille (actes de mariage). On les ramasse
|
||||
// tous, comme Gramps (libgedcom.py), pour que les actes, registres et photos de famille deviennent des
|
||||
// souvenirs. Le portrait reste à part (photoPathForPerson).
|
||||
|
||||
export type GedcomMediaRef = { file: string; caption: string | null; source: string | null }
|
||||
|
||||
const MEDIA_EXTENSIONS = new Set([
|
||||
...IMAGE_EXTENSIONS,
|
||||
'pdf', 'txt',
|
||||
'mp4', 'mov', 'm4v', 'webm', 'avi',
|
||||
'mp3', 'm4a', 'wav', 'ogg', 'aac', 'flac',
|
||||
])
|
||||
const MAX_MEDIA_PER_PERSON = 60
|
||||
const MAX_CAPTION_LENGTH = 280
|
||||
const MAX_SOURCE_LENGTH = 500
|
||||
|
||||
export type GedcomRecords = {
|
||||
obje: Map<string, GedcomPhotoNode>
|
||||
sour: Map<string, GedcomPhotoNode>
|
||||
note: Map<string, GedcomPhotoNode>
|
||||
fam: Map<string, GedcomPhotoNode>
|
||||
}
|
||||
|
||||
export function indexGedcomRecords(roots: GedcomPhotoNode[]): GedcomRecords {
|
||||
const records: GedcomRecords = { obje: new Map(), sour: new Map(), note: new Map(), fam: new Map() }
|
||||
for (const node of roots) {
|
||||
if (!node.xref) continue
|
||||
if (node.tag === 'OBJE') records.obje.set(node.xref, node)
|
||||
else if (node.tag === 'SOUR') records.sour.set(node.xref, node)
|
||||
else if (node.tag === 'NOTE') records.note.set(node.xref, node)
|
||||
else if (node.tag === 'FAM') records.fam.set(node.xref, node)
|
||||
}
|
||||
return records
|
||||
}
|
||||
|
||||
function pointerOf(value: string): string | null {
|
||||
return value.match(/^@([^@]+)@$/)?.[1] ?? null
|
||||
}
|
||||
|
||||
// Chemin local d'un fichier cité : les adresses web ne sont pas des fichiers de l'ordinateur ;
|
||||
// « file:///C:/… » (GEDCOM 7) redevient un chemin ordinaire.
|
||||
export function localMediaPath(value: string): string | null {
|
||||
let path = value.trim()
|
||||
if (!path || path.length > MAX_PATH_LENGTH) return null
|
||||
if (/^file:\/\//i.test(path)) {
|
||||
path = path.replace(/^file:\/\/(localhost)?/i, '')
|
||||
if (/^\/[a-z]:[\\/]/i.test(path)) path = path.slice(1)
|
||||
try { path = decodeURIComponent(path) } catch { /* chemin laissé tel quel */ }
|
||||
} else if (/^[a-z][a-z0-9+.-]+:/i.test(path)) {
|
||||
return null
|
||||
}
|
||||
const name = path.split(/[\\/]/).pop() || ''
|
||||
const dot = name.lastIndexOf('.')
|
||||
return dot > 0 && MEDIA_EXTENSIONS.has(name.slice(dot + 1).toLowerCase()) ? path : null
|
||||
}
|
||||
|
||||
export function joinedText(node: GedcomPhotoNode | undefined): string {
|
||||
if (!node) return ''
|
||||
let text = node.rawValue ?? node.value
|
||||
for (const c of node.children) {
|
||||
if (c.tag === 'CONT') text += `\n${c.rawValue ?? c.value}`
|
||||
else if (c.tag === 'CONC') text += c.rawValue ?? c.value
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
// Heredis Mac écrit certaines notes en RTF : on n'en garde que le texte
|
||||
export function plainNoteText(raw: string): string {
|
||||
let text = raw
|
||||
if (/^\s*\{\\rtf/.test(text)) {
|
||||
text = text
|
||||
.replace(/\{\\\*[^{}]*\}/g, '')
|
||||
.replace(/\{\\(fonttbl|colortbl|stylesheet|info)[^{}]*(\{[^{}]*\}[^{}]*)*\}/g, '')
|
||||
.replace(/\\'([0-9a-f]{2})/gi, (_, hex) => new TextDecoder('windows-1252').decode(new Uint8Array([parseInt(hex, 16)])))
|
||||
.replace(/\\par[d]?\b ?/g, '\n')
|
||||
.replace(/\\[a-z]+-?\d* ?/gi, '')
|
||||
.replace(/[{}]/g, '')
|
||||
}
|
||||
return text.replace(/[ \t]+/g, ' ').replace(/\s*\n\s*/g, '\n').trim()
|
||||
}
|
||||
|
||||
// Une note ou une source partagée est citée par des milliers de fiches : son texte se calcule une fois
|
||||
// par import (les nœuds sont neufs à chaque import, la WeakMap se vide avec eux)
|
||||
const noteTextCache = new WeakMap<GedcomPhotoNode, string>()
|
||||
const recordTitleCache = new WeakMap<GedcomPhotoNode, string>()
|
||||
const hasMediaCache = new WeakMap<GedcomPhotoNode, boolean>()
|
||||
const MAX_RECORD_DEPTH = 200
|
||||
const MAX_WALKED_NODES_PER_PERSON = 5000
|
||||
|
||||
export function noteText(node: GedcomPhotoNode | undefined, records: GedcomRecords): string {
|
||||
if (!node) return ''
|
||||
const pointer = pointerOf(node.value)
|
||||
const target = pointer ? records.note.get(pointer) : node
|
||||
if (!target) return ''
|
||||
let text = noteTextCache.get(target)
|
||||
if (text === undefined) {
|
||||
text = plainNoteText(joinedText(target))
|
||||
noteTextCache.set(target, text)
|
||||
}
|
||||
return text
|
||||
}
|
||||
|
||||
function recordTitle(record: GedcomPhotoNode): string {
|
||||
let title = recordTitleCache.get(record)
|
||||
if (title === undefined) {
|
||||
title = joinedText(child(record, 'TITL')) || joinedText(child(record, 'ABBR'))
|
||||
recordTitleCache.set(record, title)
|
||||
}
|
||||
return title
|
||||
}
|
||||
|
||||
// Un nœud mène-t-il à un fichier (OBJE), directement ou par une source ou une union citée ?
|
||||
// Un renvoi en boucle compte pour non pendant le calcul.
|
||||
function hasMedia(node: GedcomPhotoNode, records: GedcomRecords, depth = 0): boolean {
|
||||
const known = hasMediaCache.get(node)
|
||||
if (known !== undefined) return known
|
||||
if (depth > MAX_RECORD_DEPTH) return false
|
||||
hasMediaCache.set(node, false)
|
||||
let found = false
|
||||
for (const c of node.children) {
|
||||
const pointer = pointerOf(c.value)
|
||||
const linked = !pointer ? undefined : c.tag === 'SOUR' ? records.sour.get(pointer) : c.tag === 'FAMS' ? records.fam.get(pointer) : undefined
|
||||
if (c.tag === 'OBJE' || hasMedia(c, records, depth + 1) || (linked && hasMedia(linked, records, depth + 1))) { found = true; break }
|
||||
}
|
||||
hasMediaCache.set(node, found)
|
||||
return found
|
||||
}
|
||||
|
||||
function clipText(value: string, max: number): string | null {
|
||||
const text = value.replace(/\s+/g, ' ').trim()
|
||||
if (!text) return null
|
||||
return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text
|
||||
}
|
||||
|
||||
function baseNameWithoutExtension(path: string): string {
|
||||
const name = path.split(/[\\/]/).pop() || ''
|
||||
const dot = name.lastIndexOf('.')
|
||||
return dot > 0 ? name.slice(0, dot) : name
|
||||
}
|
||||
|
||||
// Titre d'une source citée : son titre (ou son abréviation), puis la page ou le détail de la citation
|
||||
export function sourceLabel(citation: GedcomPhotoNode, records: GedcomRecords): string | null {
|
||||
const pointer = pointerOf(citation.value)
|
||||
const record = pointer ? records.sour.get(pointer) : null
|
||||
const title = (record ? recordTitle(record) : '') || (pointer ? '' : citation.value)
|
||||
const page = joinedText(child(citation, 'PAGE'))
|
||||
return clipText([title, page].filter(Boolean).join(', '), MAX_SOURCE_LENGTH)
|
||||
}
|
||||
|
||||
export function mediaRefsForPerson(indi: GedcomPhotoNode, records: GedcomRecords, portraitPath: string | null = null): GedcomMediaRef[] {
|
||||
const refs: GedcomMediaRef[] = []
|
||||
const seenPaths = new Set<string>()
|
||||
if (portraitPath) seenPaths.add(portraitPath.toLowerCase())
|
||||
const visitedRecords = new Set<GedcomPhotoNode>()
|
||||
|
||||
const addObje = (ref: GedcomPhotoNode, source: string | null) => {
|
||||
const pointer = pointerOf(ref.value)
|
||||
const obje = pointer ? records.obje.get(pointer) : ref
|
||||
if (!obje) return
|
||||
const objeTitle = joinedText(child(obje, 'TITL')) || joinedText(child(ref, 'TITL'))
|
||||
const objeNote = noteText(child(obje, 'NOTE'), records) || noteText(child(ref, 'NOTE'), records)
|
||||
const form = (child(obje, 'FORM')?.value || '').toLowerCase()
|
||||
if (form === 'url') return
|
||||
for (const file of obje.children.filter((c) => c.tag === 'FILE')) {
|
||||
if ((child(file, 'FORM')?.value || '').toLowerCase() === 'url') continue
|
||||
const path = localMediaPath(file.value)
|
||||
if (!path || seenPaths.has(path.toLowerCase()) || refs.length >= MAX_MEDIA_PER_PERSON) continue
|
||||
seenPaths.add(path.toLowerCase())
|
||||
const title = joinedText(child(file, 'TITL')) || objeTitle || objeNote
|
||||
refs.push({
|
||||
file: path,
|
||||
caption: clipText(title || baseNameWithoutExtension(path), MAX_CAPTION_LENGTH),
|
||||
source,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
let budget = MAX_WALKED_NODES_PER_PERSON
|
||||
const walk = (node: GedcomPhotoNode, source: string | null, depth: number) => {
|
||||
if (depth > MAX_RECORD_DEPTH) return
|
||||
for (const c of node.children) {
|
||||
if (--budget < 0 || refs.length >= MAX_MEDIA_PER_PERSON) return
|
||||
if (c.tag === 'OBJE') {
|
||||
addObje(c, source)
|
||||
} else if (c.tag === 'SOUR') {
|
||||
const pointer = pointerOf(c.value)
|
||||
const record = pointer ? records.sour.get(pointer) : null
|
||||
const recordToWalk = record && !visitedRecords.has(record) && hasMedia(record, records) ? record : null
|
||||
if (!hasMedia(c, records) && !recordToWalk) continue
|
||||
const label = sourceLabel(c, records) ?? source
|
||||
walk(c, label, depth + 1)
|
||||
if (recordToWalk) {
|
||||
visitedRecords.add(recordToWalk)
|
||||
walk(recordToWalk, label, depth + 1)
|
||||
}
|
||||
} else if (c.tag === 'FAMS') {
|
||||
const pointer = pointerOf(c.value)
|
||||
const fam = pointer ? records.fam.get(pointer) : null
|
||||
if (fam && !visitedRecords.has(fam) && hasMedia(fam, records)) {
|
||||
visitedRecords.add(fam)
|
||||
walk({ ...fam, children: fam.children.filter((f) => !['HUSB', 'WIFE', 'CHIL'].includes(f.tag)) }, source, depth + 1)
|
||||
}
|
||||
} else if (!pointerOf(c.value) && c.children.length > 0 && hasMedia(c, records)) {
|
||||
walk(c, source, depth + 1)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
walk(indi, null, 0)
|
||||
return refs
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
import type { FastifyInstance, FastifyReply, FastifyRequest } from 'fastify'
|
||||
|
||||
// Envois rejoués sans doublon (en-tête Idempotency-Key). Sur un réseau faible, la famille renvoie une proposition
|
||||
// ou une photo dont la réponse s'est perdue : le serveur avait déjà tout créé, et l'arbre recevait deux fois la
|
||||
// même chose. Le navigateur tire une clé au début d'un envoi et la garde pour chaque nouvel essai ; le serveur
|
||||
// répond au second essai avec la réponse du premier, sans rien recréer. Deux essais simultanés : le second attend
|
||||
// le premier.
|
||||
//
|
||||
// En mémoire, sur une seule instance de l'API (le cas de Parenthèse et de l'auto-hébergement) : un redémarrage
|
||||
// oublie les clés, ce qui ne recrée de doublon que si un essai tombe pile pendant le redémarrage.
|
||||
|
||||
// Les créations faites par la famille : propositions, souvenirs, photos posées sur l'arbre, moments
|
||||
const IDEMPOTENT_ROUTES = new Set([
|
||||
'POST /trees/:id/contributions/sessions',
|
||||
'POST /trees/:id/persons/:personId/media',
|
||||
'POST /trees/:id/annotation-photos',
|
||||
'POST /trees/:id/persons/:personId/life/events',
|
||||
])
|
||||
|
||||
const TTL_MS = 24 * 60 * 60 * 1000
|
||||
const MAX_ENTRIES = 5000
|
||||
const KEY_PATTERN = /^[A-Za-z0-9_-]{16,100}$/
|
||||
|
||||
type Stored = { statusCode: number, contentType: string | undefined, payload: string }
|
||||
type Entry = { expires: number, done: Stored | null, settled: Promise<void>, settle: () => void }
|
||||
|
||||
const entries = new Map<string, Entry>()
|
||||
|
||||
function prune(now: number) {
|
||||
for (const [scope, entry] of entries) {
|
||||
if (entry.expires <= now) entries.delete(scope)
|
||||
}
|
||||
// Au-delà du plafond, les plus anciennes partent d'abord (la Map garde l'ordre d'insertion)
|
||||
while (entries.size > MAX_ENTRIES) {
|
||||
const oldest = entries.keys().next().value
|
||||
if (oldest === undefined) break
|
||||
entries.get(oldest)?.settle()
|
||||
entries.delete(oldest)
|
||||
}
|
||||
}
|
||||
|
||||
// Une clé ne vaut que pour la même route, la même adresse et la même personne : celle d'un autre ne rejoue rien
|
||||
function scopeOf(request: FastifyRequest, key: string) {
|
||||
const who = createHash('sha256').update(request.headers.authorization ?? `ip:${request.ip}`).digest('hex').slice(0, 32)
|
||||
return `${request.method} ${request.url} ${who} ${key}`
|
||||
}
|
||||
|
||||
function replay(reply: FastifyReply, stored: Stored) {
|
||||
if (stored.contentType) reply.header('content-type', stored.contentType)
|
||||
return reply.code(stored.statusCode).header('idempotent-replayed', 'true').send(stored.payload)
|
||||
}
|
||||
|
||||
export function registerIdempotency(app: FastifyInstance) {
|
||||
app.addHook('preHandler', async (request, reply) => {
|
||||
if (!IDEMPOTENT_ROUTES.has(`${request.method} ${request.routeOptions.url}`)) return
|
||||
const key = request.headers['idempotency-key']
|
||||
if (typeof key !== 'string' || !KEY_PATTERN.test(key)) return
|
||||
|
||||
const now = Date.now()
|
||||
prune(now)
|
||||
const scope = scopeOf(request, key)
|
||||
|
||||
// Un essai précédent est en cours : on attend sa fin, puis on rejoue sa réponse s'il a abouti
|
||||
for (let existing = entries.get(scope); existing; existing = entries.get(scope)) {
|
||||
if (existing.done) return replay(reply, existing.done)
|
||||
await existing.settled
|
||||
}
|
||||
|
||||
let settle = () => {}
|
||||
const settled = new Promise<void>((resolve) => { settle = resolve })
|
||||
entries.set(scope, { expires: now + TTL_MS, done: null, settled, settle })
|
||||
request.idempotencyScope = scope
|
||||
})
|
||||
|
||||
app.addHook('onSend', async (request, reply, payload) => {
|
||||
const scope = request.idempotencyScope
|
||||
if (!scope) return payload
|
||||
const entry = entries.get(scope)
|
||||
if (!entry) return payload
|
||||
// Seule une réussite se rejoue ; un échec laisse le prochain essai refaire la requête
|
||||
if (reply.statusCode < 300 && typeof payload === 'string') {
|
||||
const contentType = reply.getHeader('content-type')
|
||||
entry.done = { statusCode: reply.statusCode, contentType: typeof contentType === 'string' ? contentType : undefined, payload }
|
||||
} else {
|
||||
entries.delete(scope)
|
||||
}
|
||||
entry.settle()
|
||||
return payload
|
||||
})
|
||||
|
||||
// Requête coupée avant toute réponse : l'essai suivant ne doit pas attendre pour rien
|
||||
app.addHook('onResponse', async (request) => {
|
||||
const scope = request.idempotencyScope
|
||||
const entry = scope ? entries.get(scope) : undefined
|
||||
if (entry && !entry.done) {
|
||||
entries.delete(scope as string)
|
||||
entry.settle()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
declare module 'fastify' {
|
||||
interface FastifyRequest {
|
||||
idempotencyScope?: string
|
||||
}
|
||||
}
|
||||
|
||||
// Tests
|
||||
export function resetIdempotency() {
|
||||
entries.clear()
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,351 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
|
||||
import type { PrismaClient } from '../generated/prisma/client.js'
|
||||
|
||||
import { env } from '../config/env.js'
|
||||
import { decryptImmichApiKey } from './immich-secret.js'
|
||||
import { sniffMimeType } from './media-files.js'
|
||||
|
||||
// Client Immich : la reconnaissance des visages lit les personnes et leurs vignettes.
|
||||
// Contrat vérifié sur la spécification OpenAPI officielle d'Immich v3.1.0 :
|
||||
// GET /api/server/ping -> 200 {"res":"pong"}
|
||||
// GET /api/people?page=N&size=M -> 200 { people: PersonResponseDto[], total, hasNextPage, hidden } (size <= 1000)
|
||||
// GET /api/people/{id} -> 200 PersonResponseDto | 404 (id : UUID v4)
|
||||
// GET /api/people/{id}/thumbnail -> 200 image binaire | 404
|
||||
// Authentification : en-tête x-api-key ; clé refusée -> 401.
|
||||
|
||||
// Instance injoignable : réseau coupé, délai dépassé, réponse illisible.
|
||||
export class ImmichUnavailableError extends Error {
|
||||
constructor(message = 'Immich est injoignable') {
|
||||
super(message)
|
||||
this.name = 'ImmichUnavailableError'
|
||||
}
|
||||
}
|
||||
|
||||
// Clé d'API refusée par Immich (401/403).
|
||||
export class ImmichAuthError extends Error {
|
||||
constructor(message = 'Clé d’API Immich refusée') {
|
||||
super(message)
|
||||
this.name = 'ImmichAuthError'
|
||||
}
|
||||
}
|
||||
|
||||
// Personne ou vignette inexistante côté Immich (404).
|
||||
export class ImmichNotFoundError extends Error {
|
||||
constructor(message = 'Personne Immich introuvable') {
|
||||
super(message)
|
||||
this.name = 'ImmichNotFoundError'
|
||||
}
|
||||
}
|
||||
|
||||
const IMMICH_PEOPLE_PAGE_SIZE = 1000
|
||||
const IMMICH_TIMEOUT_MS = 10_000
|
||||
// Délai global de la liste complète : chaque page a son propre délai, la liste entière aussi.
|
||||
const IMMICH_LIST_DEADLINE_MS = 30_000
|
||||
|
||||
// Identifiants de personnes Immich : UUID v4 (spécification OpenAPI).
|
||||
const IMMICH_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i
|
||||
|
||||
export function isImmichPersonId(value: string): boolean {
|
||||
return IMMICH_ID_RE.test(value)
|
||||
}
|
||||
|
||||
export type ImmichPersonSummary = {
|
||||
id: string
|
||||
name: string
|
||||
hasThumbnail: boolean
|
||||
}
|
||||
|
||||
type ImmichPeoplePage = {
|
||||
people?: unknown
|
||||
hasNextPage?: unknown
|
||||
}
|
||||
|
||||
export class ImmichClient {
|
||||
private readonly apiUrl: string
|
||||
private readonly apiKey: string
|
||||
|
||||
constructor(apiUrl: string, apiKey: string) {
|
||||
this.apiUrl = apiUrl.replace(/\/$/, '')
|
||||
this.apiKey = apiKey
|
||||
}
|
||||
|
||||
// Le chemin de l'instance (ex. /immich) reste devant les chemins de l'API : on concatène,
|
||||
// on ne résout pas une URL relative (qui effacerait ce chemin).
|
||||
// Corps JSON lu hors de toute gestion d'erreur : un corps illisible est une instance
|
||||
// défaillante (503), pas une erreur serveur.
|
||||
private async readJson(response: Response): Promise<unknown> {
|
||||
try {
|
||||
return await response.json()
|
||||
} catch {
|
||||
throw new ImmichUnavailableError('Réponse Immich illisible')
|
||||
}
|
||||
}
|
||||
|
||||
private buildUrl(path: string): string {
|
||||
return `${this.apiUrl}${path}`
|
||||
}
|
||||
|
||||
private async fetch(path: string, body?: unknown): Promise<Response> {
|
||||
const url = this.buildUrl(path)
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetch(url, {
|
||||
method: body === undefined ? 'GET' : 'POST',
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
headers: { 'x-api-key': this.apiKey, Accept: 'application/json', ...(body === undefined ? {} : { 'Content-Type': 'application/json' }) },
|
||||
signal: AbortSignal.timeout(IMMICH_TIMEOUT_MS),
|
||||
// Aucune redirection suivie : la clé ne doit jamais partir vers une autre adresse.
|
||||
redirect: 'error',
|
||||
})
|
||||
} catch (error) {
|
||||
// L'URL ne contient aucun secret ; la clé voyage dans l'en-tête, jamais dans les journaux.
|
||||
console.warn(`Immich injoignable : ${url} (${(error as Error).message})`)
|
||||
throw new ImmichUnavailableError()
|
||||
}
|
||||
|
||||
if (response.ok) {
|
||||
return response
|
||||
}
|
||||
|
||||
// Journal avec le statut et l'URL (sans secret), puis remontée d'une erreur distincte par cause.
|
||||
console.warn(`Immich a répondu ${response.status} sur ${url}`)
|
||||
if (response.status === 401 || response.status === 403) {
|
||||
throw new ImmichAuthError()
|
||||
}
|
||||
if (response.status === 404) {
|
||||
throw new ImmichNotFoundError()
|
||||
}
|
||||
throw new ImmichUnavailableError(`Immich a répondu ${response.status}`)
|
||||
}
|
||||
|
||||
async ping(): Promise<boolean> {
|
||||
try {
|
||||
const response = await this.fetch('/api/server/ping')
|
||||
const payload = (await response.json()) as { res?: unknown }
|
||||
return payload?.res === 'pong'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
async listAssets(page: number, type: 'IMAGE' | 'VIDEO', filters: { query?: string; personId?: string } = {}) {
|
||||
const query = filters.query?.trim()
|
||||
const response = await this.fetch(query ? '/api/search/smart' : '/api/search/metadata', {
|
||||
page, size: 30, type, isTrashed: false,
|
||||
...(query ? { query } : {}),
|
||||
...(filters.personId ? { personIds: [filters.personId] } : {}),
|
||||
})
|
||||
const payload = await this.readJson(response) as { assets?: { items?: Array<{ id: string; type: string; originalFileName: string }>; nextPage?: string | null } }
|
||||
if (!Array.isArray(payload.assets?.items)) throw new ImmichUnavailableError('Liste de médias Immich illisible')
|
||||
return {
|
||||
assets: payload.assets.items.filter((asset) => isImmichPersonId(asset.id) && asset.type === type).map((asset) => ({
|
||||
id: asset.id, type: asset.type, name: asset.originalFileName,
|
||||
})),
|
||||
hasNextPage: Boolean(payload.assets.nextPage),
|
||||
}
|
||||
}
|
||||
|
||||
async getAssetBytes(assetId: string, thumbnail: boolean, maxBytes: number, preview = false): Promise<Buffer | null> {
|
||||
const variant = preview ? 'thumbnail?size=preview' : thumbnail ? 'thumbnail?size=thumbnail' : 'original'
|
||||
return this.readBytes(`/api/assets/${encodeURIComponent(assetId)}/${variant}`, maxBytes, 5 * 1024 * 1024)
|
||||
}
|
||||
|
||||
// Toutes les personnes (sans les masquées), en suivant la pagination d'Immich.
|
||||
async listPeople(): Promise<ImmichPersonSummary[]> {
|
||||
const people: ImmichPersonSummary[] = []
|
||||
let page = 1
|
||||
|
||||
const deadline = Date.now() + IMMICH_LIST_DEADLINE_MS
|
||||
// Garde-fou : une instance qui répondrait toujours hasNextPage ne doit pas nous faire boucler.
|
||||
for (let guard = 0; guard < 1000; guard += 1, page += 1) {
|
||||
if (Date.now() > deadline) {
|
||||
throw new ImmichUnavailableError('Liste des personnes Immich trop longue')
|
||||
}
|
||||
const response = await this.fetch(`/api/people?page=${page}&size=${IMMICH_PEOPLE_PAGE_SIZE}`)
|
||||
const payload = (await this.readJson(response)) as ImmichPeoplePage
|
||||
|
||||
if (!Array.isArray(payload.people)) {
|
||||
throw new ImmichUnavailableError('Réponse Immich inattendue sur /api/people')
|
||||
}
|
||||
|
||||
for (const person of payload.people as Array<{ id?: unknown; name?: unknown; thumbnailPath?: unknown }>) {
|
||||
if (typeof person?.id !== 'string' || typeof person?.name !== 'string') {
|
||||
throw new ImmichUnavailableError('Réponse Immich inattendue sur /api/people')
|
||||
}
|
||||
people.push({ id: person.id, name: person.name, hasThumbnail: typeof person.thumbnailPath === 'string' && person.thumbnailPath.length > 0 })
|
||||
}
|
||||
|
||||
if (payload.hasNextPage !== true || (payload.people as unknown[]).length === 0) {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return people
|
||||
}
|
||||
|
||||
// Une personne précise : 200 avec ses données, 404 si elle n'existe pas. Le 404 de la
|
||||
// vignette ne prouve rien (personne absente ou simple vignette manquante), l'existence
|
||||
// se vérifie donc ici.
|
||||
async getPerson(personId: string): Promise<ImmichPersonSummary> {
|
||||
const response = await this.fetch(`/api/people/${encodeURIComponent(personId)}`)
|
||||
const person = (await this.readJson(response)) as { id?: unknown; name?: unknown; thumbnailPath?: unknown }
|
||||
if (typeof person?.id !== 'string' || typeof person?.name !== 'string') {
|
||||
throw new ImmichUnavailableError('Réponse Immich inattendue sur /api/people/{id}')
|
||||
}
|
||||
return {
|
||||
id: person.id,
|
||||
name: person.name,
|
||||
hasThumbnail: typeof person.thumbnailPath === 'string' && person.thumbnailPath.length > 0,
|
||||
}
|
||||
}
|
||||
|
||||
// Vignette d'une personne, en octets bruts (JPEG côté Immich). Absente -> ImmichNotFoundError.
|
||||
// Lue en flux : au-delà de maxBytes, la lecture s'arrête et renvoie null sans charger le reste.
|
||||
async getPersonThumbnail(personId: string, maxBytes: number): Promise<Buffer | null> {
|
||||
return this.readBytes(`/api/people/${encodeURIComponent(personId)}/thumbnail`, maxBytes)
|
||||
}
|
||||
|
||||
private async readBytes(path: string, maxBytes: number, maxImageBytes = maxBytes): Promise<Buffer | null> {
|
||||
const response = await this.fetch(path)
|
||||
let limit = response.headers.get('content-type')?.startsWith('image/') ? Math.min(maxBytes, maxImageBytes) : maxBytes
|
||||
const declared = Number(response.headers.get('content-length'))
|
||||
if (Number.isFinite(declared) && declared > limit) {
|
||||
await response.body?.cancel().catch(() => {})
|
||||
return null
|
||||
}
|
||||
if (!response.body) {
|
||||
return Buffer.alloc(0)
|
||||
}
|
||||
|
||||
const reader = response.body.getReader()
|
||||
const chunks: Buffer[] = []
|
||||
let total = 0
|
||||
let signature = Buffer.alloc(0)
|
||||
try {
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
total += value.byteLength
|
||||
// Ne pas se fier au Content-Type : même avec une signature répartie sur
|
||||
// plusieurs chunks, une image est bornée à 5 Mo dès ses premiers octets.
|
||||
if (signature.length < 12) {
|
||||
signature = Buffer.concat([signature, Buffer.from(value.subarray(0, 12 - signature.length))])
|
||||
if (sniffMimeType(signature, 'video')?.startsWith('image/')) limit = Math.min(limit, maxImageBytes)
|
||||
}
|
||||
if (total > limit || (Number.isFinite(declared) && declared > limit)) {
|
||||
await reader.cancel().catch(() => {})
|
||||
return null
|
||||
}
|
||||
chunks.push(Buffer.from(value))
|
||||
}
|
||||
} catch {
|
||||
throw new ImmichUnavailableError('Lecture de la vignette Immich interrompue')
|
||||
}
|
||||
return Buffer.concat(chunks, total)
|
||||
}
|
||||
}
|
||||
|
||||
// Instance Immich normalisée pour comparaison : origine + chemin, sans slash final. Null si l'URL
|
||||
// est mal formée ou d'un autre protocole que http(s).
|
||||
export function normalizeImmichApiUrl(value: string): string | null {
|
||||
try {
|
||||
const url = new URL(value)
|
||||
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
||||
return null
|
||||
}
|
||||
// Ni identifiants, ni requête, ni fragment : une adresse d'instance n'en porte pas, et
|
||||
// « https://instance@autre-hote » ne doit jamais passer pour l'instance.
|
||||
if (url.username || url.password || url.search || url.hash) {
|
||||
return null
|
||||
}
|
||||
return `${url.origin}${url.pathname.replace(/\/+$/, '')}`
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export type ImmichInstance = {
|
||||
// Identifiant opaque, dérivé de l'adresse (stable même si l'opérateur réordonne la liste).
|
||||
id: string
|
||||
label: string
|
||||
apiUrl: string
|
||||
}
|
||||
|
||||
let instancesCache: ImmichInstance[] | undefined
|
||||
|
||||
export function immichInstanceId(apiUrl: string): string {
|
||||
return createHash('sha256').update(apiUrl).digest('hex').slice(0, 16)
|
||||
}
|
||||
|
||||
// Instances Immich autorisées par l'opérateur du serveur (IMMICH_ALLOWED_API_URLS). C'est la seule
|
||||
// liste d'adresses possibles : les administrateurs d'un arbre y choisissent la leur, le serveur
|
||||
// ne devient jamais un proxy vers un service interne choisi librement. Format d'une entrée :
|
||||
// « Libellé=https://adresse » ou « https://adresse ». Sans libellé, le nom d'hôte sert de nom.
|
||||
// Entrées invalides, doublons et libellés en conflit sont ignorés avec un avertissement.
|
||||
export function getImmichInstances(): ImmichInstance[] {
|
||||
if (instancesCache !== undefined) {
|
||||
return instancesCache
|
||||
}
|
||||
|
||||
const instances: ImmichInstance[] = []
|
||||
for (const entry of env.IMMICH_ALLOWED_API_URLS.split(',')) {
|
||||
const trimmed = entry.trim()
|
||||
if (!trimmed) {
|
||||
continue
|
||||
}
|
||||
const named = /^(.*?)\s*=\s*(https?:\/\/.+)$/i.exec(trimmed)
|
||||
const rawUrl = named ? named[2] : trimmed
|
||||
const apiUrl = normalizeImmichApiUrl(rawUrl)
|
||||
if (!apiUrl) {
|
||||
console.warn(`IMMICH_ALLOWED_API_URLS : entrée ignorée (URL http(s) invalide) : ${trimmed}`)
|
||||
continue
|
||||
}
|
||||
if (instances.some((instance) => instance.apiUrl === apiUrl)) {
|
||||
continue
|
||||
}
|
||||
const label = (named?.[1] ?? '').trim() || new URL(apiUrl).hostname
|
||||
if (instances.some((instance) => instance.label.toLowerCase() === label.toLowerCase())) {
|
||||
console.warn(`IMMICH_ALLOWED_API_URLS : entrée ignorée, le nom « ${label} » est déjà pris : donnez-lui un libellé (Libellé=https://…)`)
|
||||
continue
|
||||
}
|
||||
instances.push({ id: immichInstanceId(apiUrl), label, apiUrl })
|
||||
}
|
||||
instancesCache = instances
|
||||
return instances
|
||||
}
|
||||
|
||||
export function getImmichInstanceByApiUrl(value: string): ImmichInstance | undefined {
|
||||
const normalized = normalizeImmichApiUrl(value)
|
||||
return normalized === null ? undefined : getImmichInstances().find((instance) => instance.apiUrl === normalized)
|
||||
}
|
||||
|
||||
export function isImmichApiUrlAllowed(value: string): boolean {
|
||||
return getImmichInstanceByApiUrl(value) !== undefined
|
||||
}
|
||||
|
||||
// Connexion Immich d'un arbre : résolue par arbre, côté serveur, à chaque requête. Pas de client
|
||||
// global qui garderait les identifiants d'un arbre et pourrait servir un autre ; pas d'héritage
|
||||
// de configuration du serveur. Une clé illisible (JWT_SECRET changé) vaut « non configuré », et
|
||||
// une adresse retirée de la liste de l'opérateur aussi : la connexion existante cesse de marcher.
|
||||
export async function getTreeImmichClient(prisma: PrismaClient, treeId: string): Promise<ImmichClient | null> {
|
||||
const config = await prisma.treeImmichConfig.findUnique({
|
||||
where: { treeId },
|
||||
select: { apiUrl: true, apiKeyEnc: true },
|
||||
})
|
||||
if (!config) {
|
||||
return null
|
||||
}
|
||||
|
||||
const apiKey = decryptImmichApiKey(config.apiKeyEnc)
|
||||
if (!apiKey) {
|
||||
return null
|
||||
}
|
||||
|
||||
if (!isImmichApiUrlAllowed(config.apiUrl)) {
|
||||
return null
|
||||
}
|
||||
|
||||
// Le client reçoit l'adresse autorisée, normalisée : pas celle, brute, de la base.
|
||||
return new ImmichClient(getImmichInstanceByApiUrl(config.apiUrl)!.apiUrl, apiKey)
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
import { unlink } from 'node:fs/promises'
|
||||
import { createReadStream } from 'node:fs'
|
||||
import { stat, unlink } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
|
||||
import type { FastifyReply } from 'fastify'
|
||||
import type { FastifyReply, FastifyRequest } from 'fastify'
|
||||
import sharp from 'sharp'
|
||||
|
||||
// Fichiers envoyés : le type vient des premiers octets, jamais de ce que déclare le navigateur.
|
||||
@@ -59,6 +60,9 @@ const EXTENSION_BY_MIME: Record<string, string> = {
|
||||
'application/gpx+xml': '.gpx',
|
||||
}
|
||||
|
||||
// Marques ISO BMFF des images HEIF/HEIC (ISO/IEC 23008-12)
|
||||
const HEIC_BRANDS = new Set(['heic', 'heix', 'mif1', 'msf1', 'heim', 'heis'])
|
||||
|
||||
function startsWith(buf: Buffer, bytes: number[], offset = 0): boolean {
|
||||
if (buf.length < offset + bytes.length) return false
|
||||
return bytes.every((byte, index) => buf[offset + index] === byte)
|
||||
@@ -89,6 +93,10 @@ export function sniffMimeType(buf: Buffer, declaredType: BinaryMediaType, fileNa
|
||||
if (ascii(buf, 4, 8) === 'ftyp') {
|
||||
const brand = ascii(buf, 8, 12)
|
||||
if (brand === 'qt ') return 'video/quicktime'
|
||||
// HEIF (photos iPhone et Android) : pas une vidéo, et refusée à l'envoi faute de conversion (sharp ne décode
|
||||
// pas le HEVC). « hevc » peut aussi désigner une vidéo HEVC en MP4 : photo seulement si l'envoi se déclare photo.
|
||||
if (HEIC_BRANDS.has(brand) || (brand === 'hevc' && declaredType === 'photo')) return 'image/heic'
|
||||
if (brand === 'avif' || brand === 'avis') return 'image/avif'
|
||||
if (declaredType === 'audio' || brand === 'M4A ' || brand === 'M4B ') return 'audio/mp4'
|
||||
return 'video/mp4'
|
||||
}
|
||||
@@ -211,6 +219,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<void> {
|
||||
if (!relativePath || /^https?:\/\//.test(relativePath)) return
|
||||
@@ -222,3 +236,49 @@ export async function removeStoredFile(storageRoot: string, relativePath: string
|
||||
// déjà absent
|
||||
}
|
||||
}
|
||||
|
||||
// Plage demandée par « Range: bytes=début-fin » (une seule plage), bornée à la taille du fichier. null : pas de
|
||||
// plage lisible, on envoie tout ; 'unsatisfiable' : la plage tombe hors du fichier.
|
||||
export function parseByteRange(header: string | undefined, size: number): { start: number; end: number } | 'unsatisfiable' | null {
|
||||
const match = /^bytes=(\d*)-(\d*)$/.exec(String(header ?? '').trim())
|
||||
if (!match || (match[1] === '' && match[2] === '')) return null
|
||||
if (match[1] === '') {
|
||||
// Les n derniers octets
|
||||
const suffix = Number(match[2])
|
||||
if (suffix === 0 || size === 0) return 'unsatisfiable'
|
||||
return { start: Math.max(0, size - suffix), end: size - 1 }
|
||||
}
|
||||
const start = Number(match[1])
|
||||
const end = match[2] === '' ? size - 1 : Math.min(Number(match[2]), size - 1)
|
||||
if (start >= size || end < start) return 'unsatisfiable'
|
||||
return { start, end }
|
||||
}
|
||||
|
||||
// Taille d'un fichier stocké, null s'il manque
|
||||
export async function storedFileSize(absolutePath: string): Promise<number | null> {
|
||||
try {
|
||||
const info = await stat(absolutePath)
|
||||
return info.isFile() ? info.size : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
// Envoie un fichier en flux, par morceaux si le navigateur le demande. Safari ne lit une vidéo que si le serveur
|
||||
// répond aux plages (206) ; avant, le fichier entier passait en mémoire puis partait d'un bloc. À appeler après
|
||||
// applyMediaResponseHeaders.
|
||||
export function sendFileWithRanges(request: FastifyRequest, reply: FastifyReply, absolutePath: string, size: number): FastifyReply {
|
||||
reply.header('Accept-Ranges', 'bytes')
|
||||
const range = parseByteRange(request.headers.range, size)
|
||||
if (range === 'unsatisfiable') {
|
||||
return reply.code(416).header('Content-Range', `bytes */${size}`).send()
|
||||
}
|
||||
if (range) {
|
||||
reply.code(206)
|
||||
reply.header('Content-Range', `bytes ${range.start}-${range.end}/${size}`)
|
||||
reply.header('Content-Length', String(range.end - range.start + 1))
|
||||
return reply.send(createReadStream(absolutePath, { start: range.start, end: range.end }))
|
||||
}
|
||||
reply.header('Content-Length', String(size))
|
||||
return reply.send(createReadStream(absolutePath))
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Prisma } from '@prisma/client'
|
||||
import type { Prisma } from '../generated/prisma/client.js'
|
||||
|
||||
// Renumérote les souvenirs acceptés d'une personne et met en avant les trois premiers.
|
||||
// Les souvenirs en attente de relecture ne comptent pas.
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { Prisma, PrismaClient } from '../generated/prisma/client.js'
|
||||
import { z } from 'zod'
|
||||
|
||||
type Db = PrismaClient | Prisma.TransactionClient
|
||||
|
||||
// Personnes identifiées sur un souvenir. La liste envoyée remplace la précédente : retirer quelqu'un, c'est
|
||||
// renvoyer la liste sans lui. Le point (x, y) est facultatif, en proportion de l'image (0 à 1), et va par paire.
|
||||
export const MAX_PEOPLE_PER_MEDIA = 50
|
||||
|
||||
const coordinate = z.number().min(0).max(1).nullable().optional()
|
||||
|
||||
export const mediaPersonSchema = z
|
||||
.object({
|
||||
personId: z.string().min(1).max(64),
|
||||
x: coordinate,
|
||||
y: coordinate,
|
||||
})
|
||||
.refine((value) => (value.x == null) === (value.y == null), { message: 'point_requires_x_and_y' })
|
||||
|
||||
export const mediaPeopleSchema = z
|
||||
.array(mediaPersonSchema)
|
||||
.max(MAX_PEOPLE_PER_MEDIA)
|
||||
.refine((people) => new Set(people.map((person) => person.personId)).size === people.length, { message: 'duplicate_person' })
|
||||
|
||||
export type MediaPerson = { personId: string; x: number | null; y: number | null }
|
||||
|
||||
export function normalizeMediaPeople(people: z.infer<typeof mediaPeopleSchema>): MediaPerson[] {
|
||||
return people.map((person) => ({ personId: person.personId, x: person.x ?? null, y: person.y ?? null }))
|
||||
}
|
||||
|
||||
export async function readMediaPeople(db: Db, treeId: string, mediaId: string): Promise<MediaPerson[]> {
|
||||
const tags = await db.mediaPersonTag.findMany({
|
||||
where: { treeId, mediaId },
|
||||
select: { personId: true, x: true, y: true },
|
||||
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
|
||||
})
|
||||
return tags
|
||||
}
|
||||
|
||||
// Remplace les personnes d'un souvenir. Une personne supprimée entre l'envoi et la relecture est écartée
|
||||
// sans faire échouer le reste. Renvoie la liste réellement enregistrée.
|
||||
export async function replaceMediaPeople(
|
||||
db: Db,
|
||||
treeId: string,
|
||||
mediaId: string,
|
||||
people: MediaPerson[],
|
||||
actorUserId: string | null,
|
||||
): Promise<MediaPerson[]> {
|
||||
const ids = people.map((person) => person.personId)
|
||||
const existing = ids.length
|
||||
? await db.person.findMany({ where: { treeId, id: { in: ids }, deletedAt: null }, select: { id: true } })
|
||||
: []
|
||||
const alive = new Set(existing.map((person) => person.id))
|
||||
const kept = people.filter((person) => alive.has(person.personId))
|
||||
|
||||
await db.mediaPersonTag.deleteMany({ where: { treeId, mediaId } })
|
||||
if (kept.length) {
|
||||
// Une date par rang : l'ordre d'affichage suit celui de la liste envoyée
|
||||
const base = Date.now()
|
||||
await db.mediaPersonTag.createMany({
|
||||
data: kept.map((person, index) => ({
|
||||
treeId,
|
||||
mediaId,
|
||||
personId: person.personId,
|
||||
x: person.x,
|
||||
y: person.y,
|
||||
createdBy: actorUserId,
|
||||
createdAt: new Date(base + index),
|
||||
})),
|
||||
})
|
||||
}
|
||||
return kept
|
||||
}
|
||||
@@ -0,0 +1,129 @@
|
||||
import * as client from 'openid-client'
|
||||
|
||||
import { env } from '../config/env.js'
|
||||
|
||||
// Connexion par un fournisseur OIDC (#115). Tout le protocole passe par openid-client : découverte, PKCE (S256),
|
||||
// state et nonce, échange du code, puis vérification de l'ID token (signature par les clés publiées du
|
||||
// fournisseur, émetteur, audience = notre client, expiration, nonce). Aucun jeton n'est décodé à la main ici.
|
||||
|
||||
export type OidcPending = {
|
||||
state: string
|
||||
nonce: string
|
||||
codeVerifier: string
|
||||
returnTo: string
|
||||
// Rattachement demandé depuis un compte connecté (ticket de /auth/oidc/link) : l'identité du fournisseur rejoint
|
||||
// ce compte, au lieu d'en chercher un par email
|
||||
linkUserId?: string
|
||||
}
|
||||
|
||||
export type OidcIdentity = {
|
||||
issuer: string
|
||||
subject: string
|
||||
email: string | null
|
||||
emailVerified: boolean
|
||||
firstName: string | null
|
||||
}
|
||||
|
||||
export function isOidcEnabled(): boolean {
|
||||
return Boolean(env.OIDC_ISSUER)
|
||||
}
|
||||
|
||||
let configuration: Promise<client.Configuration> | null = null
|
||||
|
||||
// Découverte faite au premier besoin puis gardée ; un échec (fournisseur injoignable) sera retenté à la connexion suivante
|
||||
export function getOidcConfiguration(): Promise<client.Configuration> {
|
||||
configuration ??= discover().catch((error: unknown) => {
|
||||
configuration = null
|
||||
throw error
|
||||
})
|
||||
return configuration
|
||||
}
|
||||
|
||||
function discover(): Promise<client.Configuration> {
|
||||
const issuer = new URL(env.OIDC_ISSUER)
|
||||
// Sans secret : client public, PKCE seul. Avec : client_secret_basic, la méthode par défaut d'OIDC.
|
||||
const authentication = env.OIDC_CLIENT_SECRET ? client.ClientSecretBasic(env.OIDC_CLIENT_SECRET) : client.None()
|
||||
// Un fournisseur en http (réseau local) doit être autorisé explicitement par openid-client
|
||||
const options = issuer.protocol === 'http:' ? { execute: [client.allowInsecureRequests] } : undefined
|
||||
return client.discovery(issuer, env.OIDC_CLIENT_ID, undefined, authentication, options)
|
||||
}
|
||||
|
||||
// Adresse de l'app où revenir : OIDC_APP_URL, sinon l'origine de l'adresse de retour (front et API sur la même adresse)
|
||||
export function appBaseUrl(): string {
|
||||
return (env.OIDC_APP_URL || new URL(env.OIDC_REDIRECT_URI).origin).replace(/\/$/, '')
|
||||
}
|
||||
|
||||
// Seules la racine, l'adresse d'un arbre partagé et celle d'une invitation à co-gérer un arbre sont acceptées
|
||||
// comme retour : pas de redirection ouverte
|
||||
export function safeReturnTo(value: unknown): string {
|
||||
return typeof value === 'string' && /^\/(arbre\/[A-Za-z0-9-]{3,64}|invitation\/[A-Za-z0-9_-]{20,100})?$/.test(value) ? value : '/'
|
||||
}
|
||||
|
||||
export async function startAuthorization(returnTo: string): Promise<{ url: URL; pending: OidcPending }> {
|
||||
const config = await getOidcConfiguration()
|
||||
const codeVerifier = client.randomPKCECodeVerifier()
|
||||
const pending: OidcPending = {
|
||||
state: client.randomState(),
|
||||
nonce: client.randomNonce(),
|
||||
codeVerifier,
|
||||
returnTo,
|
||||
}
|
||||
const url = client.buildAuthorizationUrl(config, {
|
||||
redirect_uri: env.OIDC_REDIRECT_URI,
|
||||
scope: env.OIDC_SCOPES,
|
||||
code_challenge: await client.calculatePKCECodeChallenge(codeVerifier),
|
||||
code_challenge_method: 'S256',
|
||||
state: pending.state,
|
||||
nonce: pending.nonce,
|
||||
})
|
||||
return { url, pending }
|
||||
}
|
||||
|
||||
function stringClaim(value: unknown): string | null {
|
||||
return typeof value === 'string' && value.trim() ? value.trim() : null
|
||||
}
|
||||
|
||||
// Retour du fournisseur. L'adresse vérifiée est OIDC_REDIRECT_URI plus les paramètres reçus, jamais l'en-tête Host.
|
||||
export async function finishAuthorization(callbackQuery: string, pending: OidcPending): Promise<OidcIdentity> {
|
||||
const config = await getOidcConfiguration()
|
||||
const currentUrl = new URL(env.OIDC_REDIRECT_URI)
|
||||
currentUrl.search = callbackQuery
|
||||
|
||||
const tokens = await client.authorizationCodeGrant(config, currentUrl, {
|
||||
pkceCodeVerifier: pending.codeVerifier,
|
||||
expectedState: pending.state,
|
||||
expectedNonce: pending.nonce,
|
||||
idTokenExpected: true,
|
||||
})
|
||||
|
||||
const claims = tokens.claims()
|
||||
if (!claims) {
|
||||
throw new Error('oidc_missing_id_token')
|
||||
}
|
||||
|
||||
let email = stringClaim(claims.email)
|
||||
let emailVerified = claims.email_verified === true
|
||||
let firstName = stringClaim(claims.given_name) ?? stringClaim(claims.name)
|
||||
|
||||
// Certains fournisseurs (Authelia par défaut) ne mettent l'email que dans userinfo. Le sujet attendu est
|
||||
// celui de l'ID token : une réponse userinfo pour un autre compte est refusée par openid-client.
|
||||
if (!email && tokens.access_token) {
|
||||
const info = await client.fetchUserInfo(config, tokens.access_token, claims.sub)
|
||||
email = stringClaim(info.email)
|
||||
emailVerified = info.email_verified === true
|
||||
firstName ??= stringClaim(info.given_name) ?? stringClaim(info.name)
|
||||
}
|
||||
|
||||
return {
|
||||
issuer: claims.iss,
|
||||
subject: claims.sub,
|
||||
email: email?.toLowerCase() ?? null,
|
||||
emailVerified,
|
||||
firstName: firstName?.slice(0, 60) ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
// Pour les tests : oublie la configuration découverte
|
||||
export function resetOidcConfiguration() {
|
||||
configuration = null
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
// Nom de famille facultatif, prénom facultatif (prénom inconnu = vide) : une personne garde au moins un des deux
|
||||
export function hasAnyName(firstName: string, lastName: string): boolean {
|
||||
return Boolean(firstName.trim() || lastName.trim())
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
import { z } from 'zod'
|
||||
|
||||
// Sexe d'une personne : 'male', 'female', 'other' (autre), ou null (non précisé). L'import GEDCOM écrit
|
||||
// 'male'/'female'/'other' (SEX X de GEDCOM 7), d'anciens clients de l'API ont pu écrire 'M'/'F' : tout est
|
||||
// ramené à ces valeurs, à l'écriture comme à la lecture, sans migration des lignes existantes.
|
||||
export type PersonSex = 'male' | 'female' | 'other'
|
||||
|
||||
const MALE = new Set(['male', 'm', 'homme', 'h'])
|
||||
const FEMALE = new Set(['female', 'f', 'femme'])
|
||||
const OTHER = new Set(['other', 'x', 'autre'])
|
||||
const UNSPECIFIED = new Set(['', 'u', 'unknown', 'unspecified'])
|
||||
|
||||
// undefined : valeur que l'on ne sait pas lire (refusée à l'écriture)
|
||||
export function parseSex(value: string | null): PersonSex | null | undefined {
|
||||
if (value === null) return null
|
||||
const key = value.trim().toLowerCase()
|
||||
if (MALE.has(key)) return 'male'
|
||||
if (FEMALE.has(key)) return 'female'
|
||||
if (OTHER.has(key)) return 'other'
|
||||
if (UNSPECIFIED.has(key)) return null
|
||||
return undefined
|
||||
}
|
||||
|
||||
// Lecture d'une valeur déjà en base : ce qu'on ne sait pas lire vaut « non précisé »
|
||||
export function sexOrNull(value: string | null | undefined): PersonSex | null {
|
||||
return parseSex(value ?? null) ?? null
|
||||
}
|
||||
|
||||
// Champ « sex » des schémas d'écriture : facultatif, null pour « non précisé », valeur ramenée à male/female/other
|
||||
export const sexSchema = z
|
||||
.string()
|
||||
.max(20)
|
||||
.nullable()
|
||||
.refine((value) => parseSex(value) !== undefined, { message: 'invalid_sex' })
|
||||
.transform((value) => parseSex(value) ?? null)
|
||||
.optional()
|
||||
@@ -1,12 +1,9 @@
|
||||
import pkg from '@prisma/client'
|
||||
import { PrismaPg } from '@prisma/adapter-pg'
|
||||
|
||||
import { env } from '../config/env.js'
|
||||
import { PrismaClient } from '../generated/prisma/client.js'
|
||||
|
||||
const { PrismaClient } = pkg
|
||||
|
||||
// Prisma 7 passe par le pilote pg. Délai de connexion de 5 s, comme le moteur de Prisma 6 (pg attend sans fin par défaut)
|
||||
export const prisma = new PrismaClient({
|
||||
datasources: {
|
||||
db: {
|
||||
url: env.DATABASE_URL,
|
||||
},
|
||||
},
|
||||
adapter: new PrismaPg({ connectionString: env.DATABASE_URL, connectionTimeoutMillis: 5_000 }),
|
||||
})
|
||||
@@ -0,0 +1,30 @@
|
||||
import type { Prisma, PrismaClient } from '../generated/prisma/client.js'
|
||||
|
||||
import { env } from '../config/env.js'
|
||||
|
||||
// Inscription fermée (ALLOW_REGISTRATION=false) : une instance sans aucun compte accepte quand même le premier,
|
||||
// sinon personne ne pourrait jamais s'y connecter. Dès qu'un compte existe, plus aucun ne se crée.
|
||||
export async function isRegistrationOpen(prisma: PrismaClient): Promise<boolean> {
|
||||
if (env.ALLOW_REGISTRATION) return true
|
||||
return (await prisma.user.count()) === 0
|
||||
}
|
||||
|
||||
// Seul chemin de création d'un compte. Inscription fermée : le compte n'est créé que si la base n'en a aucun,
|
||||
// sous un verrou de transaction pour que deux inscriptions simultanées sur une instance neuve n'en créent pas
|
||||
// deux. Renvoie null quand la création est refusée.
|
||||
// invited : l'appelant a vérifié une invitation à co-gérer un arbre pour cette adresse (issue #145) ; le
|
||||
// propriétaire de l'arbre a été admis par l'admin du serveur, son invitation ouvre un compte.
|
||||
export async function createAccountIfAllowed<T>(
|
||||
prisma: PrismaClient,
|
||||
create: (tx: Prisma.TransactionClient) => Promise<T>,
|
||||
{ invited = false }: { invited?: boolean } = {},
|
||||
): Promise<T | null> {
|
||||
if (env.ALLOW_REGISTRATION || invited) return create(prisma)
|
||||
|
||||
return prisma.$transaction(async (tx) => {
|
||||
// Clé arbitraire, propre à la création de compte. pg_advisory_xact_lock renvoie void : $executeRaw, pas $queryRaw.
|
||||
await tx.$executeRaw`SELECT pg_advisory_xact_lock(113001)`
|
||||
if ((await tx.user.count()) > 0) return null
|
||||
return create(tx)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,207 @@
|
||||
import { env } from '../config/env.js'
|
||||
|
||||
// Sources publiques interrogées par le panneau « Chercher quelqu'un » (SEARCH_SOURCES). Chaque source
|
||||
// reçoit la même question et rend des résultats au même format, que le front affiche sans savoir d'où
|
||||
// ils viennent. Ajouter une source : un objet de plus dans SOURCES, avec ce qu'elle envoie au service.
|
||||
|
||||
export type SearchQuery = {
|
||||
firstName: string
|
||||
lastName: string
|
||||
birthYear?: number
|
||||
place?: string
|
||||
}
|
||||
|
||||
export type SearchEvent = { date: string | null; place: string | null }
|
||||
|
||||
export type SearchResult = {
|
||||
id: string
|
||||
firstName: string
|
||||
lastName: string
|
||||
sex: 'M' | 'F' | null
|
||||
birth: SearchEvent
|
||||
death: SearchEvent
|
||||
url: string
|
||||
// good : prénom, nom, année et lieu de naissance concordent
|
||||
match: 'good' | 'partial'
|
||||
}
|
||||
|
||||
type Source = {
|
||||
id: string
|
||||
search: (query: SearchQuery) => Promise<SearchResult[]>
|
||||
}
|
||||
|
||||
export class SearchSourceUnavailableError extends Error {}
|
||||
|
||||
const TIMEOUT_MS = 10_000
|
||||
const MAX_RESULTS = 10
|
||||
const USER_AGENT = 'Parenthese (+https://parenthese.io)'
|
||||
|
||||
export function normalizeName(value: string): string {
|
||||
return value.normalize('NFD').replace(/\p{Diacritic}/gu, '').toLowerCase().replace(/[^a-z]+/g, ' ').trim()
|
||||
}
|
||||
|
||||
// « 18980824 » ou « 1898-08-24 » → « 1898-08-24 » ; « 0000-00-00 » ou mois inconnu → année seule
|
||||
function toIsoDate(raw: unknown): string | null {
|
||||
const digits = String(raw ?? '').replace(/-/g, '')
|
||||
if (!/^\d{8}$/.test(digits) || digits.startsWith('0000')) return null
|
||||
const [year, month, day] = [digits.slice(0, 4), digits.slice(4, 6), digits.slice(6, 8)]
|
||||
if (month === '00') return year
|
||||
if (day === '00') return `${year}-${month}`
|
||||
return `${year}-${month}-${day}`
|
||||
}
|
||||
|
||||
function yearOf(date: string | null): number | null {
|
||||
return date ? Number(date.slice(0, 4)) : null
|
||||
}
|
||||
|
||||
function grade(query: SearchQuery, result: Omit<SearchResult, 'match'>): SearchResult['match'] {
|
||||
const sameLast = normalizeName(result.lastName) === normalizeName(query.lastName)
|
||||
const firstNames = normalizeName(result.firstName).split(' ')
|
||||
const sameFirst = firstNames.includes(normalizeName(query.firstName).split(' ')[0] ?? '')
|
||||
const birthYear = yearOf(result.birth.date)
|
||||
const sameYear = !query.birthYear || (birthYear !== null && Math.abs(birthYear - query.birthYear) <= 1)
|
||||
// Sans lieu, un nom et une année courants ramènent des homonymes : seul le lieu de naissance départage
|
||||
const samePlace = Boolean(query.place && result.birth.place
|
||||
&& normalizeName(result.birth.place).startsWith(normalizeName(query.place)))
|
||||
return sameLast && sameFirst && sameYear && samePlace ? 'good' : 'partial'
|
||||
}
|
||||
|
||||
async function fetchJson(url: URL, headers: Record<string, string> = {}): Promise<unknown> {
|
||||
let response: Response
|
||||
try {
|
||||
response = await fetch(url, { headers: { 'User-Agent': USER_AGENT, Accept: 'application/json', ...headers }, signal: AbortSignal.timeout(TIMEOUT_MS) })
|
||||
} catch {
|
||||
throw new SearchSourceUnavailableError('unreachable')
|
||||
}
|
||||
// matchID répond 401 ou 422 quand la recherche sans jeton est épuisée ou que le jeton a expiré
|
||||
if (response.status === 401 || response.status === 422) throw new SearchSourceUnavailableError('quota')
|
||||
if (!response.ok) throw new SearchSourceUnavailableError(`http_${response.status}`)
|
||||
try {
|
||||
return await response.json()
|
||||
} catch {
|
||||
throw new SearchSourceUnavailableError('invalid_json')
|
||||
}
|
||||
}
|
||||
|
||||
// matchID demande une recherche par seconde au plus : les appels de toute l'instance passent l'un après l'autre
|
||||
let matchIdQueue: Promise<unknown> = Promise.resolve()
|
||||
const MATCHID_INTERVAL_MS = 1100
|
||||
|
||||
function throttled<T>(run: () => Promise<T>): Promise<T> {
|
||||
const next = matchIdQueue.then(run, run)
|
||||
matchIdQueue = next.then(
|
||||
() => new Promise((resolve) => setTimeout(resolve, MATCHID_INTERVAL_MS)),
|
||||
() => new Promise((resolve) => setTimeout(resolve, MATCHID_INTERVAL_MS)),
|
||||
)
|
||||
return next
|
||||
}
|
||||
|
||||
type MatchIdLocation = { city?: string | string[]; departmentCode?: string; country?: string }
|
||||
type MatchIdPerson = {
|
||||
id: string
|
||||
name?: { first?: string[] | string; last?: string }
|
||||
sex?: string
|
||||
birth?: { date?: string; location?: MatchIdLocation }
|
||||
death?: { date?: string; location?: MatchIdLocation }
|
||||
}
|
||||
|
||||
function matchIdPlace(location: MatchIdLocation | undefined): string | null {
|
||||
if (!location) return null
|
||||
const city = Array.isArray(location.city) ? location.city[0] : location.city
|
||||
if (!city) return location.country || null
|
||||
if (location.country && location.country !== 'France') return `${city}, ${location.country}`
|
||||
return location.departmentCode ? `${city} (${location.departmentCode})` : city
|
||||
}
|
||||
|
||||
// Décès en France depuis 1970 : fichier de l'INSEE, cherché par matchID (deces.matchid.io)
|
||||
const deces: Source = {
|
||||
id: 'deces',
|
||||
search: (query) => throttled(async () => {
|
||||
const url = new URL('https://deces.matchid.io/deces/api/v1/search')
|
||||
url.searchParams.set('firstName', query.firstName)
|
||||
url.searchParams.set('lastName', query.lastName)
|
||||
if (query.birthYear) url.searchParams.set('birthDate', String(query.birthYear))
|
||||
url.searchParams.set('size', String(MAX_RESULTS))
|
||||
const headers: Record<string, string> = env.MATCHID_TOKEN ? { Authorization: `Bearer ${env.MATCHID_TOKEN}` } : {}
|
||||
const payload = await fetchJson(url, headers) as { response?: { persons?: MatchIdPerson[] } }
|
||||
const persons = payload?.response?.persons ?? []
|
||||
return persons.map((person) => {
|
||||
const first = person.name?.first
|
||||
const base: Omit<SearchResult, 'match'> = {
|
||||
id: person.id,
|
||||
firstName: Array.isArray(first) ? first.join(' ') : first ?? '',
|
||||
lastName: person.name?.last ?? '',
|
||||
sex: person.sex === 'M' || person.sex === 'F' ? person.sex : null,
|
||||
birth: { date: toIsoDate(person.birth?.date), place: matchIdPlace(person.birth?.location) },
|
||||
death: { date: toIsoDate(person.death?.date), place: matchIdPlace(person.death?.location) },
|
||||
url: `https://deces.matchid.io/id/${encodeURIComponent(person.id)}`,
|
||||
}
|
||||
return { ...base, match: grade(query, base) }
|
||||
})
|
||||
}),
|
||||
}
|
||||
|
||||
type WikiTreeMatch = {
|
||||
Id: number
|
||||
Name: string
|
||||
FirstName?: string
|
||||
MiddleName?: string
|
||||
LastNameAtBirth?: string
|
||||
Gender?: string
|
||||
BirthDate?: string
|
||||
DeathDate?: string
|
||||
BirthLocation?: string
|
||||
DeathLocation?: string
|
||||
}
|
||||
|
||||
// WikiTree : arbre mondial tenu par ses membres, profils publics seulement (api.wikitree.com)
|
||||
const wikitree: Source = {
|
||||
id: 'wikitree',
|
||||
search: async (query) => {
|
||||
const url = new URL('https://api.wikitree.com/api.php')
|
||||
url.searchParams.set('action', 'searchPerson')
|
||||
url.searchParams.set('appId', 'parenthese')
|
||||
url.searchParams.set('FirstName', query.firstName)
|
||||
url.searchParams.set('LastName', query.lastName)
|
||||
if (query.birthYear) {
|
||||
url.searchParams.set('BirthDate', `${query.birthYear}-01-01`)
|
||||
url.searchParams.set('dateSpread', '2')
|
||||
}
|
||||
url.searchParams.set('limit', String(MAX_RESULTS))
|
||||
const payload = await fetchJson(url) as [{ matches?: WikiTreeMatch[] }] | undefined
|
||||
const matches = Array.isArray(payload) ? payload[0]?.matches ?? [] : []
|
||||
// La recherche de WikiTree est floue (« du Pont » pour Dupont, autres prénoms) : même nom de famille seulement
|
||||
const wantedLast = normalizeName(query.lastName).replace(/ /g, '')
|
||||
return matches.filter((match) => normalizeName(match.LastNameAtBirth ?? '').replace(/ /g, '') === wantedLast).map((match) => {
|
||||
const base: Omit<SearchResult, 'match'> = {
|
||||
id: String(match.Id),
|
||||
firstName: [match.FirstName, match.MiddleName].filter(Boolean).join(' '),
|
||||
lastName: match.LastNameAtBirth ?? '',
|
||||
sex: match.Gender === 'Male' ? 'M' : match.Gender === 'Female' ? 'F' : null,
|
||||
birth: { date: toIsoDate(match.BirthDate), place: match.BirthLocation || null },
|
||||
death: { date: toIsoDate(match.DeathDate), place: match.DeathLocation || null },
|
||||
url: `https://www.wikitree.com/wiki/${encodeURIComponent(match.Name)}`,
|
||||
}
|
||||
return { ...base, match: grade(query, base) }
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
const SOURCES: Source[] = [deces, wikitree]
|
||||
|
||||
// Sources allumées par l'opérateur, dans l'ordre de SOURCES ; un nom inconnu est signalé puis ignoré
|
||||
export function enabledSearchSources(): string[] {
|
||||
const wanted = env.SEARCH_SOURCES.split(',').map((entry) => entry.trim().toLowerCase()).filter(Boolean)
|
||||
for (const name of wanted) {
|
||||
if (!SOURCES.some((source) => source.id === name)) console.warn(`SEARCH_SOURCES : source inconnue ignorée : ${name}`)
|
||||
}
|
||||
return SOURCES.filter((source) => wanted.includes(source.id)).map((source) => source.id)
|
||||
}
|
||||
|
||||
export async function searchSource(id: string, query: SearchQuery): Promise<SearchResult[]> {
|
||||
const source = SOURCES.find((candidate) => candidate.id === id)
|
||||
if (!source) throw new SearchSourceUnavailableError('unknown_source')
|
||||
const results = await source.search(query)
|
||||
// Les meilleures concordances d'abord, l'ordre du service ensuite
|
||||
return results.slice(0, MAX_RESULTS).sort((a, b) => Number(b.match === 'good') - Number(a.match === 'good'))
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { Prisma, PrismaClient } from '../generated/prisma/client.js'
|
||||
|
||||
type LinkReader = Pick<PrismaClient, 'parentChildLink'> | Pick<Prisma.TransactionClient, 'parentChildLink'>
|
||||
|
||||
// Ordre d'un nouvel enfant : après ses frères et sœurs, pour qu'une fratrie déjà réordonnée
|
||||
// ne voie pas le dernier arrivé passer devant (le placement trie les enfants sur displayOrder).
|
||||
export async function nextSiblingOrder(db: LinkReader, treeId: string, parentPersonId: string): Promise<number> {
|
||||
const last = await db.parentChildLink.findFirst({
|
||||
where: { treeId, parentPersonId, deletedAt: null },
|
||||
orderBy: { displayOrder: 'desc' },
|
||||
select: { displayOrder: true },
|
||||
})
|
||||
return Number.isInteger(last?.displayOrder) ? (last!.displayOrder as number) + 1 : 1
|
||||
}
|
||||
@@ -1,11 +1,21 @@
|
||||
import type { PrismaClient } from '../generated/prisma/client.js'
|
||||
|
||||
// Sessions fermées par « Se déconnecter » ou par la suppression du compte, jusqu'à la fin de leur jeton.
|
||||
// Gardées en mémoire pour ne coûter aucune requête par appel, et en base pour survivre au redémarrage de l'API :
|
||||
// avant, chaque déploiement les oubliait et un jeton déconnecté redevenait valable jusqu'à 7 jours.
|
||||
// L'API tourne en un seul processus (pm2 fork, un conteneur) : la mémoire suffit entre deux redémarrages.
|
||||
const revokedUserTokens = new Map<string, number>()
|
||||
|
||||
function nowSeconds(): number {
|
||||
return Math.floor(Date.now() / 1000)
|
||||
}
|
||||
|
||||
export function revokeUserToken(jti: string, exp: number): void {
|
||||
type RevocationStore = Pick<PrismaClient, 'revokedSession'>
|
||||
|
||||
export async function revokeUserToken(store: RevocationStore, jti: string, exp: number): Promise<void> {
|
||||
revokedUserTokens.set(jti, exp)
|
||||
const expiresAt = new Date(exp * 1000)
|
||||
await store.revokedSession.upsert({ where: { jti }, create: { jti, expiresAt }, update: {} })
|
||||
}
|
||||
|
||||
export function isUserTokenRevoked(jti: string): boolean {
|
||||
@@ -22,3 +32,21 @@ export function isUserTokenRevoked(jti: string): boolean {
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// Au démarrage : les déconnexions encore valables reviennent en mémoire, les expirées sont effacées. L'effacement
|
||||
// n'a lieu qu'ici : la table grossit entre deux redémarrages, d'une ligne par déconnexion, ce qui reste minuscule
|
||||
// avec un déploiement par jour ou presque.
|
||||
export async function loadRevokedTokens(store: RevocationStore): Promise<number> {
|
||||
const now = new Date()
|
||||
await store.revokedSession.deleteMany({ where: { expiresAt: { lte: now } } })
|
||||
const rows = await store.revokedSession.findMany({ where: { expiresAt: { gt: now } }, select: { jti: true, expiresAt: true } })
|
||||
for (const row of rows) {
|
||||
revokedUserTokens.set(row.jti, Math.floor(row.expiresAt.getTime() / 1000))
|
||||
}
|
||||
return rows.length
|
||||
}
|
||||
|
||||
// Tests : repartir d'un processus neuf, comme après un redémarrage
|
||||
export function forgetRevokedTokensInMemory(): void {
|
||||
revokedUserTokens.clear()
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { createHash, randomBytes } from 'node:crypto'
|
||||
|
||||
import type { Prisma, PrismaClient } from '../generated/prisma/client.js'
|
||||
|
||||
// Co-gestion d'un arbre (issue #145). Le propriétaire invite une adresse ; Parenthèse n'envoie pas de mail, il
|
||||
// donne un lien à transmettre. Seule l'empreinte du jeton est gardée en base.
|
||||
//
|
||||
// Qui est rattaché, et comment :
|
||||
// - par le lien, avec un compte à la même adresse (mot de passe ou OIDC). L'inscription par mot de passe ne
|
||||
// vérifie pas l'adresse : le lien est la preuve, l'adresse seule ne suffit jamais ;
|
||||
// - sans le lien, seulement par OIDC, quand le fournisseur dit l'email vérifié (claimInvitationsForVerifiedEmail).
|
||||
|
||||
export const INVITATION_TTL_MS = 14 * 24 * 60 * 60 * 1000
|
||||
export const MAX_PENDING_INVITATIONS = 20
|
||||
|
||||
type Db = PrismaClient | Prisma.TransactionClient
|
||||
|
||||
export function newInvitationToken(): { token: string; tokenHash: string } {
|
||||
const token = randomBytes(32).toString('base64url')
|
||||
return { token, tokenHash: hashInvitationToken(token) }
|
||||
}
|
||||
|
||||
export function hashInvitationToken(token: string): string {
|
||||
return createHash('sha256').update(token).digest('hex')
|
||||
}
|
||||
|
||||
export function normalizeEmail(email: string): string {
|
||||
return email.trim().toLowerCase()
|
||||
}
|
||||
|
||||
// Invitation encore valable : ni acceptée, ni annulée, ni expirée
|
||||
export function pendingInvitationWhere(now = new Date()): Prisma.TreeInvitationWhereInput {
|
||||
return { acceptedAt: null, revokedAt: null, expiresAt: { gt: now }, tree: { deletedAt: null } }
|
||||
}
|
||||
|
||||
export async function findPendingInvitationByToken(db: Db, token: string) {
|
||||
if (!token || token.length > 200) return null
|
||||
return db.treeInvitation.findFirst({
|
||||
where: { tokenHash: hashInvitationToken(token), ...pendingInvitationWhere() },
|
||||
include: { tree: { select: { id: true, name: true, icon: true, ownerUserId: true, owner: { select: { firstName: true } } } } },
|
||||
})
|
||||
}
|
||||
|
||||
export async function hasPendingInvitationForEmail(db: Db, email: string): Promise<boolean> {
|
||||
const found = await db.treeInvitation.findFirst({ where: { email: normalizeEmail(email), ...pendingInvitationWhere() }, select: { id: true } })
|
||||
return Boolean(found)
|
||||
}
|
||||
|
||||
export type AcceptResult = { ok: true; treeId: string } | { ok: false; error: 'invitation_invalid' | 'invitation_email_mismatch' | 'already_owner' }
|
||||
|
||||
// Accepte une invitation pour ce compte : co-gestionnaire (admin) de l'arbre. L'invitation ne sert qu'une fois,
|
||||
// même pour deux acceptations simultanées (updateMany conditionnel dans la transaction).
|
||||
export async function acceptInvitation(prisma: PrismaClient, invitationId: string, userId: string, userEmail: string): Promise<AcceptResult> {
|
||||
return prisma.$transaction(async (tx) => {
|
||||
const invitation = await tx.treeInvitation.findFirst({
|
||||
where: { id: invitationId, ...pendingInvitationWhere() },
|
||||
select: { id: true, treeId: true, email: true, tree: { select: { ownerUserId: true } } },
|
||||
})
|
||||
if (!invitation) return { ok: false, error: 'invitation_invalid' } as const
|
||||
if (normalizeEmail(userEmail) !== invitation.email) return { ok: false, error: 'invitation_email_mismatch' } as const
|
||||
if (invitation.tree.ownerUserId === userId) return { ok: false, error: 'already_owner' } as const
|
||||
|
||||
const claimed = await tx.treeInvitation.updateMany({
|
||||
where: { id: invitation.id, ...pendingInvitationWhere() },
|
||||
data: { acceptedAt: new Date(), acceptedUserId: userId },
|
||||
})
|
||||
if (claimed.count !== 1) return { ok: false, error: 'invitation_invalid' } as const
|
||||
|
||||
const existing = await tx.treeMembership.findUnique({
|
||||
where: { treeId_userId: { treeId: invitation.treeId, userId } },
|
||||
select: { role: true },
|
||||
})
|
||||
if (!existing) {
|
||||
await tx.treeMembership.create({ data: { treeId: invitation.treeId, userId, role: 'admin' } })
|
||||
} else if (existing.role === 'member') {
|
||||
await tx.treeMembership.update({ where: { treeId_userId: { treeId: invitation.treeId, userId } }, data: { role: 'admin' } })
|
||||
}
|
||||
// L'arbre s'ouvre à la prochaine visite
|
||||
await tx.user.update({
|
||||
where: { id: userId },
|
||||
data: { lastOpenedTreeId: invitation.treeId, lastOpenedAccessMode: 'member', lastOpenedRole: 'admin', lastOpenedAt: new Date() },
|
||||
})
|
||||
await tx.auditLog.create({
|
||||
data: {
|
||||
treeId: invitation.treeId,
|
||||
actorType: 'user',
|
||||
actorId: userId,
|
||||
action: 'manager_joined',
|
||||
entityType: 'tree',
|
||||
entityId: invitation.treeId,
|
||||
payloadJson: { invitationId: invitation.id },
|
||||
},
|
||||
})
|
||||
return { ok: true, treeId: invitation.treeId } as const
|
||||
})
|
||||
}
|
||||
|
||||
// Connexion OIDC avec un email vérifié par le fournisseur : les invitations en attente à cette adresse sont
|
||||
// acceptées sans le lien. Jamais pour un email non vérifié, jamais pour une connexion par mot de passe, et
|
||||
// seulement si c'est l'adresse du compte : une identité déjà reliée dont l'email a changé chez le fournisseur
|
||||
// ne prend pas les invitations faites à sa nouvelle adresse (elle passe par le lien).
|
||||
export async function claimInvitationsForVerifiedEmail(prisma: PrismaClient, userId: string, verifiedEmail: string): Promise<string[]> {
|
||||
const email = normalizeEmail(verifiedEmail)
|
||||
const invitations = await prisma.treeInvitation.findMany({ where: { email, ...pendingInvitationWhere() }, select: { id: true } })
|
||||
if (!invitations.length) return []
|
||||
const account = await prisma.user.findUnique({ where: { id: userId }, select: { email: true } })
|
||||
if (!account || normalizeEmail(account.email) !== email) return []
|
||||
const joined: string[] = []
|
||||
for (const invitation of invitations) {
|
||||
const result = await acceptInvitation(prisma, invitation.id, userId, email)
|
||||
if (result.ok) joined.push(result.treeId)
|
||||
}
|
||||
return joined
|
||||
}
|
||||
|
||||
// « jacques@exemple.fr » devient « ja•••@exemple.fr » sur la page publique du lien
|
||||
export function maskEmail(email: string): string {
|
||||
const [local, domain] = email.split('@')
|
||||
if (!domain) return '•••'
|
||||
return `${local.slice(0, Math.min(2, local.length))}•••@${domain}`
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { rm } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
|
||||
import type { Prisma, PrismaClient } from '@prisma/client'
|
||||
import type { Prisma, PrismaClient } from '../generated/prisma/client.js'
|
||||
|
||||
import { env } from '../config/env.js'
|
||||
|
||||
|
||||
@@ -6,8 +6,11 @@ import { env } from '../config/env.js'
|
||||
// Une ouverture d'arbre = une visite. Les rechargements du même visiteur dans cette fenêtre
|
||||
// (graphe rechargé après une modification, onglet rouvert) ne comptent qu'une fois.
|
||||
export const VISIT_DEDUP_WINDOW_MS = 30 * 60 * 1000
|
||||
// Au-delà, les visites sont effacées (lecture de l'onglet Visites)
|
||||
// Au-delà, les visites sont effacées : à l'enregistrement d'une visite (au plus une fois par heure,
|
||||
// pour tous les arbres) et à la lecture de l'onglet Visites
|
||||
export const VISIT_RETENTION_DAYS = 365
|
||||
const PURGE_INTERVAL_MS = 60 * 60 * 1000
|
||||
let lastPurgeAt = 0
|
||||
|
||||
export type VisitAccessKind = 'share' | 'member' | 'shared_account'
|
||||
|
||||
@@ -34,6 +37,18 @@ export function visitorKeyOf(treeId: string, ip: string, userAgent: string): str
|
||||
return createHash('sha256').update(`${env.JWT_SECRET}|${treeId}|${ip}|${userAgent}`).digest('hex').slice(0, 32)
|
||||
}
|
||||
|
||||
// Compte supprimé : ses visites restent comptées, sans son identifiant
|
||||
export function deletedAccountVisitorKey(userId: string): string {
|
||||
return createHash('sha256').update(`${env.JWT_SECRET}|deleted|${userId}`).digest('hex').slice(0, 32)
|
||||
}
|
||||
|
||||
async function purgeExpiredVisits(app: FastifyInstance): Promise<void> {
|
||||
const now = Date.now()
|
||||
if (now - lastPurgeAt < PURGE_INTERVAL_MS) return
|
||||
lastPurgeAt = now
|
||||
await app.prisma.treeVisit.deleteMany({ where: { createdAt: { lt: new Date(now - VISIT_RETENTION_DAYS * 24 * 60 * 60 * 1000) } } })
|
||||
}
|
||||
|
||||
// N'échoue jamais : un journal qui casse ne doit pas empêcher d'ouvrir l'arbre
|
||||
export async function recordTreeVisit(
|
||||
app: FastifyInstance,
|
||||
@@ -69,6 +84,7 @@ export async function recordTreeVisit(
|
||||
device: deviceFromUserAgent(userAgent),
|
||||
},
|
||||
})
|
||||
await purgeExpiredVisits(app)
|
||||
} catch (error) {
|
||||
request.log.warn({ err: error, treeId }, 'tree_visit_record_failed')
|
||||
}
|
||||
|
||||
@@ -50,9 +50,9 @@ export function resetTreeUnlockGuard(): void {
|
||||
attemptsByTree.clear()
|
||||
}
|
||||
|
||||
// bcryptjs calcule en JavaScript sur le processus de l'API (≈ 250 ms par comparaison au coût 12) : des essais
|
||||
// lancés en parallèle depuis quelques adresses suffisaient à le saturer pour toutes les familles. Les
|
||||
// comparaisons de mot de passe de partage passent une par une, le reste de l'API garde la main entre deux.
|
||||
// Une comparaison bcrypt coûte ≈ 250 ms au coût 12. Même calculée hors de la boucle (bcrypt natif), des essais
|
||||
// lancés en parallèle depuis quelques adresses occuperaient tous les fils de calcul, connexions comprises. Les
|
||||
// comparaisons de mot de passe de partage passent une par une.
|
||||
// Au-delà de MAX_WAITING comparaisons en attente, on refuse tout de suite (null) plutôt que d'allonger la file.
|
||||
const MAX_WAITING = 20
|
||||
let queue: Promise<unknown> = Promise.resolve()
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
|
||||
import { env } from '../config/env.js'
|
||||
|
||||
// Session d'un compte, la même quelle que soit la façon de se connecter (mot de passe ou fournisseur OIDC)
|
||||
export function signUserSession(app: FastifyInstance, user: { id: string; email: string }): string {
|
||||
return app.jwt.sign(
|
||||
{
|
||||
kind: 'user',
|
||||
sub: user.id,
|
||||
jti: randomUUID(),
|
||||
userId: user.id,
|
||||
email: user.email,
|
||||
},
|
||||
{ expiresIn: env.JWT_EXPIRES_IN },
|
||||
)
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import type { FastifyInstance, FastifyPluginAsync, FastifyReply, FastifyRequest } from 'fastify'
|
||||
import { Prisma } from '@prisma/client'
|
||||
import { Prisma } from '../generated/prisma/client.js'
|
||||
import { z } from 'zod'
|
||||
|
||||
import {
|
||||
@@ -306,64 +306,67 @@ export const annotationRoutes: FastifyPluginAsync = async (app) => {
|
||||
return reply.code(400).send({ error: 'invalid_annotation_photo_path' })
|
||||
}
|
||||
|
||||
// Creates
|
||||
for (const [index, item] of payload.data.create.entries()) {
|
||||
await app.prisma.annotation.create({
|
||||
// Créations, modifications, suppressions et trace : tout ou rien, un nouvel essai ne double rien
|
||||
await app.prisma.$transaction(async (tx) => {
|
||||
// Creates
|
||||
for (const [index, item] of payload.data.create.entries()) {
|
||||
await tx.annotation.create({
|
||||
data: {
|
||||
treeId,
|
||||
type: item.type,
|
||||
x: item.x,
|
||||
y: item.y,
|
||||
content: createContents[index] as string,
|
||||
style: (item.style ?? {}) as Prisma.InputJsonValue,
|
||||
zIndex: item.zIndex ?? 0,
|
||||
createdBy: user.userId,
|
||||
},
|
||||
})
|
||||
results.created++
|
||||
}
|
||||
|
||||
// Updates
|
||||
for (const [index, item] of payload.data.update.entries()) {
|
||||
const data: Record<string, unknown> = {}
|
||||
if (item.x !== undefined) data.x = item.x
|
||||
if (item.y !== undefined) data.y = item.y
|
||||
if (item.content !== undefined) data.content = updateContents[index]
|
||||
if (item.style !== undefined) data.style = item.style
|
||||
if (item.zIndex !== undefined) data.zIndex = item.zIndex
|
||||
|
||||
if (Object.keys(data).length > 0) {
|
||||
const updated = await tx.annotation.updateMany({
|
||||
where: { id: item.id, treeId, deletedAt: null },
|
||||
data,
|
||||
})
|
||||
if (updated.count > 0) results.updated++
|
||||
}
|
||||
}
|
||||
|
||||
// Deletes
|
||||
if (payload.data.delete.length > 0) {
|
||||
const deleted = await tx.annotation.updateMany({
|
||||
where: {
|
||||
id: { in: payload.data.delete },
|
||||
treeId,
|
||||
deletedAt: null,
|
||||
},
|
||||
data: { deletedAt: new Date() },
|
||||
})
|
||||
results.deleted = deleted.count
|
||||
}
|
||||
|
||||
await tx.auditLog.create({
|
||||
data: {
|
||||
treeId,
|
||||
type: item.type,
|
||||
x: item.x,
|
||||
y: item.y,
|
||||
content: createContents[index] as string,
|
||||
style: (item.style ?? {}) as Prisma.InputJsonValue,
|
||||
zIndex: item.zIndex ?? 0,
|
||||
createdBy: user.userId,
|
||||
actorType: 'user',
|
||||
actorId: user.userId,
|
||||
action: 'annotations_batch',
|
||||
entityType: 'annotation',
|
||||
entityId: treeId,
|
||||
payloadJson: results,
|
||||
},
|
||||
})
|
||||
results.created++
|
||||
}
|
||||
|
||||
// Updates
|
||||
for (const [index, item] of payload.data.update.entries()) {
|
||||
const data: Record<string, unknown> = {}
|
||||
if (item.x !== undefined) data.x = item.x
|
||||
if (item.y !== undefined) data.y = item.y
|
||||
if (item.content !== undefined) data.content = updateContents[index]
|
||||
if (item.style !== undefined) data.style = item.style
|
||||
if (item.zIndex !== undefined) data.zIndex = item.zIndex
|
||||
|
||||
if (Object.keys(data).length > 0) {
|
||||
const updated = await app.prisma.annotation.updateMany({
|
||||
where: { id: item.id, treeId, deletedAt: null },
|
||||
data,
|
||||
})
|
||||
if (updated.count > 0) results.updated++
|
||||
}
|
||||
}
|
||||
|
||||
// Deletes
|
||||
if (payload.data.delete.length > 0) {
|
||||
const deleted = await app.prisma.annotation.updateMany({
|
||||
where: {
|
||||
id: { in: payload.data.delete },
|
||||
treeId,
|
||||
deletedAt: null,
|
||||
},
|
||||
data: { deletedAt: new Date() },
|
||||
})
|
||||
results.deleted = deleted.count
|
||||
}
|
||||
|
||||
await app.prisma.auditLog.create({
|
||||
data: {
|
||||
treeId,
|
||||
actorType: 'user',
|
||||
actorId: user.userId,
|
||||
action: 'annotations_batch',
|
||||
entityType: 'annotation',
|
||||
entityId: treeId,
|
||||
payloadJson: results,
|
||||
},
|
||||
})
|
||||
|
||||
return reply.send({ ok: true, ...results })
|
||||
|
||||
+136
-35
@@ -3,8 +3,13 @@ import { randomUUID } from 'node:crypto'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { env } from '../config/env.js'
|
||||
import { hashPassword, verifyPassword } from '../lib/auth.js'
|
||||
import { confirmsWithPassword, hashPassword, verifyPassword } from '../lib/auth.js'
|
||||
import { isOidcEnabled } from '../lib/oidc.js'
|
||||
import { createAccountIfAllowed, isRegistrationOpen } from '../lib/registration.js'
|
||||
import { acceptInvitation, findPendingInvitationByToken } from '../lib/tree-invitations.js'
|
||||
import { signUserSession } from '../lib/user-session.js'
|
||||
import { revokeUserToken } from '../lib/token-revocation.js'
|
||||
import { deletedAccountVisitorKey } from '../lib/tree-visits.js'
|
||||
import { deleteTreeRecords, removeTreeMediaDirectories } from '../lib/tree-purge.js'
|
||||
import type { AnyJwtPayload } from '../types/auth.js'
|
||||
|
||||
@@ -20,10 +25,27 @@ const credentialsSchema = z.object({
|
||||
password: z.string().min(8).max(128),
|
||||
})
|
||||
|
||||
const deleteAccountSchema = z.object({
|
||||
password: z.string().min(1).max(128),
|
||||
// Prénom du compte, facultatif : seulement à l'inscription (la connexion ne le demande pas)
|
||||
const registerSchema = credentialsSchema.extend({
|
||||
firstName: z.string().max(60).optional().nullable(),
|
||||
// Lien d'invitation à co-gérer un arbre : ouvre un compte même inscription fermée, à l'adresse invitée seulement
|
||||
invitationToken: z.string().min(1).max(200).optional(),
|
||||
})
|
||||
|
||||
function trimmedFirstName(value: string | null | undefined): string | null {
|
||||
const trimmed = (value ?? '').trim()
|
||||
return trimmed ? trimmed : null
|
||||
}
|
||||
|
||||
// Suppression d'un compte sans mot de passe : connexion chez le fournisseur de moins de 15 minutes
|
||||
const RECENT_SIGN_IN_MS = 15 * 60 * 1000
|
||||
|
||||
// Un compte avec mot de passe le redonne ; un compte né d'une connexion OIDC, sans mot de passe, retape son email
|
||||
const deleteAccountSchema = z.object({
|
||||
password: z.string().min(1).max(128).optional(),
|
||||
confirmEmail: z.string().min(1).max(320).optional(),
|
||||
}).refine((value) => value.password || value.confirmEmail, { message: 'password or confirmEmail required' })
|
||||
|
||||
const updateLastTreeSchema = z.object({
|
||||
treeId: z.string().min(1),
|
||||
accessMode: z.enum(['member', 'share']),
|
||||
@@ -83,6 +105,22 @@ async function resolveAccessibleLastTree(
|
||||
}
|
||||
|
||||
export const authRoutes: FastifyPluginAsync = async (app) => {
|
||||
// Ce que l'écran d'accueil propose : l'app cache « Créer un compte » quand l'instance n'en accepte plus
|
||||
app.get(
|
||||
'/options',
|
||||
{ config: { rateLimit: { max: 60, timeWindow: '1 minute' } } },
|
||||
async (_request, reply) => {
|
||||
const registration = await isRegistrationOpen(app.prisma)
|
||||
return reply.send({
|
||||
registration,
|
||||
passwordLogin: env.PASSWORD_LOGIN,
|
||||
oidc: isOidcEnabled() ? { name: env.OIDC_PROVIDER_NAME } : null,
|
||||
// Rien à proposer quand l'instance ne crée plus de compte
|
||||
signupPrompts: env.SIGNUP_PROMPTS && registration && env.PASSWORD_LOGIN,
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
app.post(
|
||||
'/register',
|
||||
{
|
||||
@@ -94,41 +132,67 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
|
||||
},
|
||||
},
|
||||
async (request, reply) => {
|
||||
const parsed = credentialsSchema.safeParse(request.body)
|
||||
const parsed = registerSchema.safeParse(request.body)
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'invalid_payload', details: parsed.error.flatten() })
|
||||
}
|
||||
|
||||
// Connexion par le fournisseur seulement (PASSWORD_LOGIN=false) : pas de compte à mot de passe
|
||||
if (!env.PASSWORD_LOGIN) {
|
||||
return reply.code(403).send({ error: 'password_login_disabled' })
|
||||
}
|
||||
|
||||
const email = parsed.data.email.trim().toLowerCase()
|
||||
const invitation = parsed.data.invitationToken ? await findPendingInvitationByToken(app.prisma, parsed.data.invitationToken) : null
|
||||
if (parsed.data.invitationToken && !invitation) {
|
||||
return reply.code(410).send({ error: 'invitation_invalid' })
|
||||
}
|
||||
if (invitation && invitation.email !== email) {
|
||||
return reply.code(403).send({ error: 'invitation_email_mismatch' })
|
||||
}
|
||||
|
||||
// Inscription fermée : refusée avant toute lecture, la réponse ne dit pas si l'adresse a un compte
|
||||
if (!invitation && !(await isRegistrationOpen(app.prisma))) {
|
||||
return reply.code(403).send({ error: 'registration_closed' })
|
||||
}
|
||||
|
||||
const existing = await app.prisma.user.findUnique({ where: { email } })
|
||||
if (existing) {
|
||||
return reply.code(409).send({ error: 'email_already_exists' })
|
||||
}
|
||||
|
||||
const passwordHash = await hashPassword(parsed.data.password)
|
||||
const user = await app.prisma.user.create({
|
||||
const user = await createAccountIfAllowed(app.prisma, (tx) => tx.user.create({
|
||||
data: {
|
||||
email,
|
||||
passwordHash,
|
||||
firstName: trimmedFirstName(parsed.data.firstName),
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
firstName: true,
|
||||
},
|
||||
})
|
||||
}), { invited: Boolean(invitation) })
|
||||
// Un autre compte est né pendant le calcul du hash, sur une instance fermée
|
||||
if (!user) {
|
||||
return reply.code(403).send({ error: 'registration_closed' })
|
||||
}
|
||||
|
||||
const token = app.jwt.sign(
|
||||
{
|
||||
kind: 'user',
|
||||
sub: user.id,
|
||||
jti: randomUUID(),
|
||||
userId: user.id,
|
||||
email: user.email,
|
||||
},
|
||||
{ expiresIn: env.JWT_EXPIRES_IN },
|
||||
)
|
||||
// Compte ouvert par une invitation : co-gestionnaire de l'arbre tout de suite
|
||||
let joinedTreeId: string | null = null
|
||||
if (invitation) {
|
||||
const accepted = await acceptInvitation(app.prisma, invitation.id, user.id, user.email)
|
||||
if (accepted.ok) {
|
||||
joinedTreeId = accepted.treeId
|
||||
} else if (!(await isRegistrationOpen(app.prisma))) {
|
||||
// Invitation annulée ou servie entre-temps, sur une instance fermée : pas de compte sans arbre
|
||||
await app.prisma.user.delete({ where: { id: user.id } })
|
||||
return reply.code(410).send({ error: 'invitation_invalid' })
|
||||
}
|
||||
}
|
||||
|
||||
return reply.code(201).send({ token, user })
|
||||
return reply.code(201).send({ token: signUserSession(app, user), user: { ...user, hasPassword: true }, joinedTreeId })
|
||||
},
|
||||
)
|
||||
|
||||
@@ -143,6 +207,10 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
|
||||
},
|
||||
},
|
||||
async (request, reply) => {
|
||||
if (!env.PASSWORD_LOGIN) {
|
||||
return reply.code(403).send({ error: 'password_login_disabled' })
|
||||
}
|
||||
|
||||
const parsed = credentialsSchema.safeParse(request.body)
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'invalid_payload', details: parsed.error.flatten() })
|
||||
@@ -154,12 +222,14 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
firstName: true,
|
||||
passwordHash: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (!user) {
|
||||
// Même durée qu'un mauvais mot de passe : la réponse ne dit pas si l'adresse a un compte
|
||||
// Adresse inconnue, ou compte né d'une connexion OIDC (sans mot de passe) : même durée qu'un mauvais mot de
|
||||
// passe, la réponse ne dit pas si l'adresse a un compte
|
||||
if (!user?.passwordHash) {
|
||||
await verifyPassword(parsed.data.password, await getDummyHash())
|
||||
return reply.code(401).send({ error: 'invalid_credentials' })
|
||||
}
|
||||
@@ -169,27 +239,37 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
|
||||
return reply.code(401).send({ error: 'invalid_credentials' })
|
||||
}
|
||||
|
||||
const token = app.jwt.sign(
|
||||
{
|
||||
kind: 'user',
|
||||
sub: user.id,
|
||||
jti: randomUUID(),
|
||||
userId: user.id,
|
||||
email: user.email,
|
||||
},
|
||||
{ expiresIn: env.JWT_EXPIRES_IN },
|
||||
)
|
||||
|
||||
return reply.send({
|
||||
token,
|
||||
token: signUserSession(app, user),
|
||||
user: {
|
||||
id: user.id,
|
||||
email: user.email,
|
||||
firstName: user.firstName,
|
||||
hasPassword: true,
|
||||
},
|
||||
})
|
||||
},
|
||||
)
|
||||
|
||||
// Profil du compte connecté (prénom compris) : la session restaurée sur un autre appareil le retrouve
|
||||
app.get('/me', async (request, reply) => {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
}
|
||||
|
||||
const user = await app.prisma.user.findUnique({
|
||||
where: { id: request.actor.userId },
|
||||
select: { id: true, email: true, firstName: true, passwordHash: true, identities: { select: { id: true }, take: 1 } },
|
||||
})
|
||||
if (!user) {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
}
|
||||
|
||||
// hasPassword : l'écran de suppression demande le mot de passe, ou l'email pour un compte sans mot de passe.
|
||||
// oidcLinked : le compte se connecte déjà par le fournisseur ; sinon le compte propose « Relier à … »
|
||||
return reply.send({ user: { id: user.id, email: user.email, firstName: user.firstName, hasPassword: confirmsWithPassword(user.passwordHash), oidcLinked: (user.identities?.length ?? 0) > 0 } })
|
||||
})
|
||||
|
||||
app.get('/me/last-tree', async (request, reply) => {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
@@ -318,6 +398,7 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
|
||||
where: { id: userId },
|
||||
select: {
|
||||
id: true,
|
||||
email: true,
|
||||
passwordHash: true,
|
||||
},
|
||||
})
|
||||
@@ -326,12 +407,26 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
}
|
||||
|
||||
const isValid = await verifyPassword(parsed.data.password, user.passwordHash)
|
||||
const payload = await request.jwtVerify<AnyJwtPayload & { exp?: number; iat?: number }>()
|
||||
|
||||
const withPassword = confirmsWithPassword(user.passwordHash)
|
||||
if (!withPassword) {
|
||||
// Compte né d'une connexion OIDC, ou dont la connexion par mot de passe est fermée : pas de mot de passe à
|
||||
// redonner. Il retape son email, et la session doit venir d'une connexion récente chez le fournisseur
|
||||
// (une session volée ou oubliée ouverte ne suffit pas).
|
||||
const sessionAgeMs = typeof payload.iat === 'number' ? Date.now() - payload.iat * 1000 : Infinity
|
||||
if (sessionAgeMs > RECENT_SIGN_IN_MS) {
|
||||
return reply.code(403).send({ error: 'recent_sign_in_required' })
|
||||
}
|
||||
}
|
||||
|
||||
const isValid = withPassword
|
||||
? Boolean(parsed.data.password) && await verifyPassword(parsed.data.password as string, user.passwordHash as string)
|
||||
: (parsed.data.confirmEmail ?? '').trim().toLowerCase() === user.email
|
||||
if (!isValid) {
|
||||
return reply.code(403).send({ error: 'invalid_password' })
|
||||
}
|
||||
|
||||
const payload = await request.jwtVerify<AnyJwtPayload & { exp?: number }>()
|
||||
|
||||
// Arbres possédés (y compris ceux marqués supprimés) puis compte, dans une seule transaction :
|
||||
// la relation propriétaire est en Restrict, les arbres doivent partir avant l'utilisateur.
|
||||
@@ -350,12 +445,18 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
|
||||
data: { submittedByLabel: 'Contributeur' },
|
||||
})
|
||||
|
||||
// Ses visites des autres arbres restent comptées, sans son identifiant
|
||||
await tx.treeVisit.updateMany({
|
||||
where: { visitorKey: `user:${userId}` },
|
||||
data: { visitorKey: deletedAccountVisitorKey(userId) },
|
||||
})
|
||||
|
||||
await tx.user.delete({ where: { id: userId } })
|
||||
return treeIds
|
||||
})
|
||||
|
||||
if (payload.kind === 'user' && typeof payload.exp === 'number') {
|
||||
revokeUserToken(payload.jti, payload.exp)
|
||||
await revokeUserToken(app.prisma, payload.jti, payload.exp)
|
||||
}
|
||||
|
||||
await removeTreeMediaDirectories(ownedTreeIds, request.log)
|
||||
@@ -375,7 +476,7 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
|
||||
}
|
||||
|
||||
if (typeof payload.exp === 'number') {
|
||||
revokeUserToken(payload.jti, payload.exp)
|
||||
await revokeUserToken(app.prisma, payload.jti, payload.exp)
|
||||
}
|
||||
|
||||
return reply.send({ ok: true })
|
||||
|
||||
@@ -1,16 +1,23 @@
|
||||
import path from 'node:path'
|
||||
|
||||
import type { FastifyInstance, FastifyPluginAsync } from 'fastify'
|
||||
import { Prisma } from '@prisma/client'
|
||||
import { Prisma } from '../generated/prisma/client.js'
|
||||
import { z } from 'zod'
|
||||
import { env, UPLOAD_BODY_LIMIT } from '../config/env.js'
|
||||
import { sanitizeAnnotationContentForRead } from '../lib/annotation-content.js'
|
||||
import { AnnotationChangeError, applyAnnotationChange, normalizedAnnotationAfter, releaseRejectedPhotos, validateAnnotationChange } from '../lib/annotation-changes.js'
|
||||
import { softDeletePersonCascade, softDeleteUnionCascade } from '../lib/entity-deletion.js'
|
||||
import { removeStoredFile } from '../lib/media-files.js'
|
||||
import { canReadTree } from '../lib/tree-access.js'
|
||||
import { syncPersonMediaOrder } from '../lib/media-order.js'
|
||||
import { mediaPeopleSchema, normalizeMediaPeople, replaceMediaPeople } from '../lib/media-people.js'
|
||||
|
||||
import type { Actor, MembershipRole } from '../types/auth.js'
|
||||
import { findParentChildValidationError, findUnionValidationError } from '../utils/relationship-guards.js'
|
||||
import { nextSiblingOrder } from '../lib/sibling-order.js'
|
||||
import { personPrecisionResets, unionPrecisionResets } from '../lib/date-precision.js'
|
||||
import { hasAnyName } from '../lib/person-names.js'
|
||||
import { sexOrNull, sexSchema } from '../lib/person-sex.js'
|
||||
|
||||
const isoDateRegex = /^\d{4}-\d{2}-\d{2}$/
|
||||
|
||||
@@ -27,6 +34,8 @@ const sessionParamsSchema = z.object({
|
||||
// remplissait la base à 12 Mo par envoi
|
||||
const MAX_CHANGE_JSON_CHARS = 64_000
|
||||
const MAX_PENDING_SESSIONS_PER_TREE = 200
|
||||
// Annotations proposées avant la 1.5.1 : écartées à la relecture si elles ne se posent pas
|
||||
const SKIPPABLE_ANNOTATION_ERRORS = new Set(['invalid_annotation_change', 'invalid_annotation_photo_path', 'unsupported_change_action_for_annotation'])
|
||||
const boundedJson = z.unknown().optional().refine(
|
||||
(value) => value === undefined || JSON.stringify(value).length <= MAX_CHANGE_JSON_CHARS,
|
||||
{ message: 'change_too_large' },
|
||||
@@ -66,31 +75,39 @@ const reviewSessionSchema = z.object({
|
||||
})
|
||||
|
||||
const personCreateSchema = z.object({
|
||||
firstName: z.string().min(1).max(120),
|
||||
lastName: z.string().min(1).max(120),
|
||||
firstName: z.string().trim().max(120),
|
||||
lastName: z.string().trim().max(120),
|
||||
birthName: z.string().max(120).optional().nullable(),
|
||||
nickname: z.string().max(120).optional().nullable(),
|
||||
birthDate: z.string().regex(isoDateRegex).optional().nullable(),
|
||||
deathDate: z.string().regex(isoDateRegex).optional().nullable(),
|
||||
isDeceased: z.boolean().optional(),
|
||||
toVerify: z.boolean().optional(),
|
||||
birthPlace: z.string().max(200).optional().nullable(),
|
||||
deathPlace: z.string().max(200).optional().nullable(),
|
||||
profession: z.string().max(200).optional().nullable(),
|
||||
region: z.string().max(120).optional().nullable(),
|
||||
nationality: z.string().max(120).optional().nullable(),
|
||||
sex: z.string().max(20).optional().nullable(),
|
||||
sex: sexSchema,
|
||||
notes: z.string().max(2000).optional().nullable(),
|
||||
})
|
||||
}).refine((value) => hasAnyName(value.firstName, value.lastName), { message: 'name_required', path: ['lastName'] })
|
||||
|
||||
const personUpdateSchema = z
|
||||
.object({
|
||||
firstName: z.string().min(1).max(120).optional(),
|
||||
lastName: z.string().min(1).max(120).optional(),
|
||||
firstName: z.string().trim().max(120).optional(),
|
||||
lastName: z.string().trim().max(120).optional(),
|
||||
birthName: z.string().max(120).optional().nullable(),
|
||||
nickname: z.string().max(120).optional().nullable(),
|
||||
birthDate: z.string().regex(isoDateRegex).optional().nullable(),
|
||||
deathDate: z.string().regex(isoDateRegex).optional().nullable(),
|
||||
isDeceased: z.boolean().optional(),
|
||||
toVerify: z.boolean().optional(),
|
||||
birthPlace: z.string().max(200).optional().nullable(),
|
||||
deathPlace: z.string().max(200).optional().nullable(),
|
||||
profession: z.string().max(200).optional().nullable(),
|
||||
region: z.string().max(120).optional().nullable(),
|
||||
nationality: z.string().max(120).optional().nullable(),
|
||||
sex: z.string().max(20).optional().nullable(),
|
||||
sex: sexSchema,
|
||||
notes: z.string().max(2000).optional().nullable(),
|
||||
})
|
||||
.refine((value) => Object.keys(value).length > 0, {
|
||||
@@ -145,7 +162,11 @@ const reorderSchema = z.object({
|
||||
|
||||
type ContributionStatus = 'pending' | 'approved' | 'rejected'
|
||||
|
||||
type ParsedChange = z.infer<typeof contributionChangeSchema>
|
||||
// Les souvenirs, les moments et les personnes d'un souvenir arrivent par leurs propres routes, jamais par une
|
||||
// session envoyée en bloc
|
||||
type ParsedChange = Omit<z.infer<typeof contributionChangeSchema>, 'entityType'> & {
|
||||
entityType: z.infer<typeof contributionChangeSchema>['entityType'] | 'life_event' | 'media_people'
|
||||
}
|
||||
|
||||
type TxClient = Prisma.TransactionClient
|
||||
|
||||
@@ -177,7 +198,7 @@ function recordTempRef(after: unknown, createdId: string, refs: RefMap) {
|
||||
}
|
||||
|
||||
// Personnes d'abord, puis unions, puis liens : un lien vers une personne ajoutée s'applique après elle
|
||||
const ENTITY_ORDER: Record<string, number> = { person: 0, union: 1, parent_child_link: 2, media: 3, annotation: 4 }
|
||||
const ENTITY_ORDER: Record<string, number> = { person: 0, union: 1, parent_child_link: 2, media: 3, annotation: 4, media_people: 5 }
|
||||
function byApplicationOrder<T extends { entityType: string; action: string }>(changes: T[]): T[] {
|
||||
const rank = (change: T) => (ENTITY_ORDER[change.entityType] ?? 9) * 10 + (change.action === 'create' ? 0 : 1)
|
||||
return changes.map((change, index) => ({ change, index }))
|
||||
@@ -229,7 +250,7 @@ function stripAnnotationUrl<T>(value: T): T {
|
||||
|
||||
function toPrismaJson(
|
||||
value: unknown,
|
||||
): Prisma.InputJsonValue | Prisma.NullTypes.DbNull | Prisma.NullTypes.JsonNull | undefined {
|
||||
): Prisma.InputJsonValue | typeof Prisma.DbNull | typeof Prisma.JsonNull | undefined {
|
||||
if (value === undefined) {
|
||||
return undefined
|
||||
}
|
||||
@@ -308,10 +329,50 @@ async function applyContributionChange(
|
||||
// Fichiers à effacer une fois la transaction validée (suppression d'une personne)
|
||||
filesToRemove: string[] = [],
|
||||
): Promise<{ entityId: string | null }> {
|
||||
// Les annotations sont appliquées par le client après la relecture (batchAnnotations) :
|
||||
// rien à faire ici. Avant, elles tombaient dans la branche des liens et faisaient échouer la relecture.
|
||||
// Annotation (dessin, texte, sticker, photo posée sur l'arbre) : posée ici, dans la transaction qui accepte
|
||||
// la proposition. Avant la 1.5.1, le navigateur du relecteur la posait après coup, et pouvait la perdre.
|
||||
if (change.entityType === 'annotation') {
|
||||
return { entityId: change.entityId ?? null }
|
||||
try {
|
||||
return await applyAnnotationChange(tx, treeId, { action: change.action, entityId: change.entityId, after: change.after }, actorUserId)
|
||||
} catch (error) {
|
||||
if (error instanceof AnnotationChangeError) throw new ContributionRouteError(400, error.code)
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// Moment proposé par la famille : il existe déjà, on le rend visible
|
||||
if (change.entityType === 'life_event') {
|
||||
if (change.action !== 'create' || !change.entityId) {
|
||||
throw new ContributionRouteError(400, 'unsupported_change_action_for_life_event')
|
||||
}
|
||||
const updated = await tx.lifeEvent.updateMany({
|
||||
where: { id: change.entityId, treeId, deletedAt: null },
|
||||
data: { status: 'approved' },
|
||||
})
|
||||
if (updated.count === 0) {
|
||||
throw new ContributionRouteError(400, 'invalid_entity_reference')
|
||||
}
|
||||
return { entityId: change.entityId }
|
||||
}
|
||||
|
||||
// Personnes identifiées sur un souvenir : la liste proposée remplace l'actuelle. Souvenir supprimé entre
|
||||
// l'envoi et la relecture : rien à faire, la relecture continue.
|
||||
if (change.entityType === 'media_people') {
|
||||
if (change.action !== 'update' || !change.entityId) {
|
||||
throw new ContributionRouteError(400, 'unsupported_change_action_for_media_people')
|
||||
}
|
||||
const people = mediaPeopleSchema.safeParse(isRecord(change.after) ? change.after.people : undefined)
|
||||
if (!people.success) {
|
||||
throw new ContributionRouteError(400, 'invalid_media_people')
|
||||
}
|
||||
const media = await tx.mediaItem.findFirst({
|
||||
where: { id: change.entityId, treeId, status: 'approved', deletedAt: null },
|
||||
select: { id: true },
|
||||
})
|
||||
if (media) {
|
||||
await replaceMediaPeople(tx, treeId, change.entityId, normalizeMediaPeople(people.data), actorUserId)
|
||||
}
|
||||
return { entityId: change.entityId }
|
||||
}
|
||||
|
||||
// Souvenir envoyé par la famille : le fichier existe déjà, on le rend visible
|
||||
@@ -356,9 +417,13 @@ async function applyContributionChange(
|
||||
firstName: parsed.data.firstName.trim(),
|
||||
lastName: parsed.data.lastName.trim(),
|
||||
birthName: toTrimmedStringOrNull(parsed.data.birthName),
|
||||
nickname: toTrimmedStringOrNull(parsed.data.nickname),
|
||||
birthDate: toDateOrNull(parsed.data.birthDate),
|
||||
deathDate: toDateOrNull(parsed.data.deathDate),
|
||||
isDeceased: !parsed.data.deathDate && Boolean(parsed.data.isDeceased),
|
||||
toVerify: Boolean(parsed.data.toVerify),
|
||||
birthPlace: toTrimmedStringOrNull(parsed.data.birthPlace),
|
||||
deathPlace: toTrimmedStringOrNull(parsed.data.deathPlace),
|
||||
profession: toTrimmedStringOrNull(parsed.data.profession),
|
||||
region: toTrimmedStringOrNull(parsed.data.region),
|
||||
nationality: toTrimmedStringOrNull(parsed.data.nationality),
|
||||
@@ -390,6 +455,27 @@ async function applyContributionChange(
|
||||
throw new ContributionRouteError(400, 'invalid_change_after')
|
||||
}
|
||||
|
||||
const nextDates = {
|
||||
birthDate: parsed.data.birthDate !== undefined ? toDateOrNull(parsed.data.birthDate) : undefined,
|
||||
deathDate: parsed.data.deathDate !== undefined ? toDateOrNull(parsed.data.deathDate) : undefined,
|
||||
}
|
||||
const currentDates = nextDates.birthDate !== undefined || nextDates.deathDate !== undefined
|
||||
? await tx.person.findFirst({
|
||||
where: { id: change.entityId, treeId, deletedAt: null },
|
||||
select: { birthDate: true, deathDate: true },
|
||||
})
|
||||
: null
|
||||
|
||||
if (parsed.data.firstName !== undefined || parsed.data.lastName !== undefined) {
|
||||
const before = await tx.person.findFirst({
|
||||
where: { id: change.entityId, treeId, deletedAt: null },
|
||||
select: { firstName: true, lastName: true },
|
||||
})
|
||||
if (before && !hasAnyName(parsed.data.firstName ?? before.firstName, parsed.data.lastName ?? before.lastName)) {
|
||||
throw new ContributionRouteError(400, 'invalid_change_after')
|
||||
}
|
||||
}
|
||||
|
||||
const result = await tx.person.updateMany({
|
||||
where: {
|
||||
id: change.entityId,
|
||||
@@ -397,12 +483,17 @@ async function applyContributionChange(
|
||||
deletedAt: null,
|
||||
},
|
||||
data: {
|
||||
...personPrecisionResets(currentDates, nextDates),
|
||||
firstName: parsed.data.firstName !== undefined ? parsed.data.firstName.trim() : undefined,
|
||||
lastName: parsed.data.lastName !== undefined ? parsed.data.lastName.trim() : undefined,
|
||||
birthName: parsed.data.birthName !== undefined ? toTrimmedStringOrNull(parsed.data.birthName) : undefined,
|
||||
birthDate: parsed.data.birthDate !== undefined ? toDateOrNull(parsed.data.birthDate) : undefined,
|
||||
deathDate: parsed.data.deathDate !== undefined ? toDateOrNull(parsed.data.deathDate) : undefined,
|
||||
nickname: parsed.data.nickname !== undefined ? toTrimmedStringOrNull(parsed.data.nickname) : undefined,
|
||||
birthDate: nextDates.birthDate,
|
||||
deathDate: nextDates.deathDate,
|
||||
isDeceased: nextDates.deathDate ? false : parsed.data.isDeceased,
|
||||
toVerify: parsed.data.toVerify,
|
||||
birthPlace: parsed.data.birthPlace !== undefined ? toTrimmedStringOrNull(parsed.data.birthPlace) : undefined,
|
||||
deathPlace: parsed.data.deathPlace !== undefined ? toTrimmedStringOrNull(parsed.data.deathPlace) : undefined,
|
||||
profession: parsed.data.profession !== undefined ? toTrimmedStringOrNull(parsed.data.profession) : undefined,
|
||||
region: parsed.data.region !== undefined ? toTrimmedStringOrNull(parsed.data.region) : undefined,
|
||||
nationality: parsed.data.nationality !== undefined ? toTrimmedStringOrNull(parsed.data.nationality) : undefined,
|
||||
@@ -510,6 +601,7 @@ async function applyContributionChange(
|
||||
select: {
|
||||
partner1PersonId: true,
|
||||
partner2PersonId: true,
|
||||
startDate: true,
|
||||
},
|
||||
})
|
||||
if (!existingUnion) {
|
||||
@@ -536,6 +628,9 @@ async function applyContributionChange(
|
||||
deletedAt: null,
|
||||
},
|
||||
data: {
|
||||
...unionPrecisionResets(existingUnion, {
|
||||
startDate: parsed.data.startDate !== undefined ? toDateOrNull(parsed.data.startDate) : undefined,
|
||||
}),
|
||||
partner1PersonId: parsed.data.partner1PersonId,
|
||||
partner2PersonId: parsed.data.partner2PersonId,
|
||||
unionType: parsed.data.unionType,
|
||||
@@ -632,7 +727,7 @@ async function applyContributionChange(
|
||||
childPersonId: parsed.data.childPersonId,
|
||||
viaUnionId: parsed.data.viaUnionId ?? null,
|
||||
parentageType: parsed.data.parentageType ?? 'biologique',
|
||||
displayOrder: parsed.data.displayOrder ?? 1,
|
||||
displayOrder: parsed.data.displayOrder ?? await nextSiblingOrder(tx, treeId, parsed.data.parentPersonId),
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
@@ -792,9 +887,13 @@ async function snapshotEntity(
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
birthName: true,
|
||||
nickname: true,
|
||||
birthDate: true,
|
||||
deathDate: true,
|
||||
isDeceased: true,
|
||||
toVerify: true,
|
||||
birthPlace: true,
|
||||
deathPlace: true,
|
||||
profession: true,
|
||||
region: true,
|
||||
nationality: true,
|
||||
@@ -807,6 +906,7 @@ async function snapshotEntity(
|
||||
...current,
|
||||
birthDate: current.birthDate?.toISOString().slice(0, 10) ?? null,
|
||||
deathDate: current.deathDate?.toISOString().slice(0, 10) ?? null,
|
||||
sex: sexOrNull(current.sex),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -999,6 +1099,115 @@ export async function resolveSubmissionContext(app: FastifyInstance, actor: Acto
|
||||
}
|
||||
|
||||
export const contributionRoutes: FastifyPluginAsync = async (app) => {
|
||||
// Personnes identifiées sur un souvenir. Administrateur : enregistré tout de suite. Famille (membre, lien
|
||||
// de partage) : une proposition, appliquée à la relecture, ou tout de suite si l'arbre l'autorise.
|
||||
app.put('/trees/:id/media/:mediaId/people', { config: { rateLimit: { max: 60, timeWindow: '1 minute' } } }, async (request, reply) => {
|
||||
const params = z.object({ id: z.string().min(1), mediaId: z.string().min(1) }).safeParse(request.params)
|
||||
if (!params.success) {
|
||||
return reply.code(400).send({ error: 'invalid_params' })
|
||||
}
|
||||
const payload = z.object({
|
||||
people: mediaPeopleSchema,
|
||||
submittedByLabel: z.string().trim().min(1).max(120).optional(),
|
||||
}).safeParse(request.body)
|
||||
if (!payload.success) {
|
||||
return reply.code(400).send({ error: 'invalid_payload' })
|
||||
}
|
||||
const treeId = params.data.id
|
||||
const mediaId = params.data.mediaId
|
||||
|
||||
try {
|
||||
const context = await resolveSubmissionContext(app, request.actor, treeId)
|
||||
const actor = request.actor
|
||||
const membership = actor?.kind === 'user'
|
||||
? await app.prisma.treeMembership.findUnique({ where: { treeId_userId: { treeId, userId: actor.userId } }, select: { role: true } })
|
||||
: null
|
||||
const isAdmin = Boolean(membership && hasAdminRight(membership.role))
|
||||
|
||||
const media = await app.prisma.mediaItem.findFirst({
|
||||
where: { id: mediaId, treeId, status: 'approved', deletedAt: null },
|
||||
select: { id: true, personId: true },
|
||||
})
|
||||
if (!media) {
|
||||
return reply.code(404).send({ error: 'media_not_found' })
|
||||
}
|
||||
|
||||
const people = normalizeMediaPeople(payload.data.people)
|
||||
const known = people.length
|
||||
? await app.prisma.person.count({ where: { treeId, id: { in: people.map((person) => person.personId) }, deletedAt: null } })
|
||||
: 0
|
||||
if (known !== people.length) {
|
||||
return reply.code(400).send({ error: 'invalid_person_reference' })
|
||||
}
|
||||
|
||||
if (context.autoStatus === 'pending') {
|
||||
const pendingCount = await app.prisma.contributionSession.count({ where: { treeId, status: 'pending' } })
|
||||
if (pendingCount >= MAX_PENDING_SESSIONS_PER_TREE) {
|
||||
return reply.code(429).send({ error: 'too_many_pending_contributions' })
|
||||
}
|
||||
}
|
||||
|
||||
const now = new Date()
|
||||
const saved = await app.prisma.$transaction(async (tx) => {
|
||||
const before = await tx.mediaPersonTag.findMany({
|
||||
where: { treeId, mediaId },
|
||||
select: { personId: true, x: true, y: true },
|
||||
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
|
||||
})
|
||||
const applied = context.autoStatus === 'approved'
|
||||
? await replaceMediaPeople(tx, treeId, mediaId, people, context.submittedByUserId)
|
||||
: null
|
||||
|
||||
// L'administrateur n'a rien à relire : pas de session, comme pour ses propres souvenirs
|
||||
if (!isAdmin) {
|
||||
const session = await tx.contributionSession.create({
|
||||
data: {
|
||||
treeId,
|
||||
submittedByUserId: context.submittedByUserId,
|
||||
submittedByLabel: payload.data.submittedByLabel?.trim() || context.submittedByLabel,
|
||||
mode: context.mode,
|
||||
status: context.autoStatus,
|
||||
title: 'Personnes sur un souvenir',
|
||||
reviewedAt: context.autoStatus === 'approved' ? now : undefined,
|
||||
reviewedBy: context.autoStatus === 'approved' ? context.submittedByUserId : undefined,
|
||||
},
|
||||
})
|
||||
await tx.contributionChange.create({
|
||||
data: {
|
||||
sessionId: session.id,
|
||||
entityType: 'media_people',
|
||||
entityId: mediaId,
|
||||
action: 'update',
|
||||
beforeJson: toPrismaJson({ mediaId, ownerPersonId: media.personId, people: before }),
|
||||
afterJson: toPrismaJson({ mediaId, ownerPersonId: media.personId, people }),
|
||||
decision: context.autoStatus === 'approved' ? 'approved' : undefined,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
await tx.auditLog.create({
|
||||
data: {
|
||||
treeId,
|
||||
actorType: context.actorType,
|
||||
actorId: context.actorId,
|
||||
action: 'media_people_updated',
|
||||
entityType: 'media_item',
|
||||
entityId: mediaId,
|
||||
payloadJson: { status: context.autoStatus, count: people.length },
|
||||
},
|
||||
})
|
||||
return applied
|
||||
})
|
||||
|
||||
return reply.send({ status: context.autoStatus, people: saved ?? people })
|
||||
} catch (error) {
|
||||
if (error instanceof ContributionRouteError) {
|
||||
return reply.code(error.statusCode).send({ error: error.code })
|
||||
}
|
||||
throw error
|
||||
}
|
||||
})
|
||||
|
||||
app.post('/trees/:id/contributions/sessions', { bodyLimit: UPLOAD_BODY_LIMIT, config: { rateLimit: { max: 30, timeWindow: '1 minute' } } }, async (request, reply) => {
|
||||
const params = treeIdParamSchema.safeParse(request.params)
|
||||
if (!params.success) {
|
||||
@@ -1014,6 +1223,17 @@ export const contributionRoutes: FastifyPluginAsync = async (app) => {
|
||||
return reply.code(400).send({ error: 'media_changes_not_allowed' })
|
||||
}
|
||||
|
||||
// Une annotation refusée à l'écriture le serait aussi à la relecture : on le dit tout de suite
|
||||
for (const change of payload.data.changes) {
|
||||
if (change.entityType !== 'annotation') continue
|
||||
try {
|
||||
validateAnnotationChange(change, params.data.id)
|
||||
} catch (error) {
|
||||
if (error instanceof AnnotationChangeError) return reply.code(400).send({ error: error.code })
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
const context = await resolveSubmissionContext(app, request.actor, params.data.id)
|
||||
const now = new Date()
|
||||
@@ -1075,7 +1295,8 @@ export const contributionRoutes: FastifyPluginAsync = async (app) => {
|
||||
entityId: effectiveEntityId,
|
||||
action: change.action,
|
||||
beforeJson: toPrismaJson(change.entityType === 'annotation' ? stripAnnotationUrl(before) : before),
|
||||
afterJson: toPrismaJson(change.entityType === 'annotation' ? stripAnnotationUrl(change.after) : change.after),
|
||||
// Annotation : gardée nettoyée (photoPath canonique), pour être relue sans ambiguïté à la relecture
|
||||
afterJson: toPrismaJson(change.entityType === 'annotation' ? stripAnnotationUrl(normalizedAnnotationAfter(change, params.data.id)) : change.after),
|
||||
conflictState: change.conflictState ?? 'none',
|
||||
decision: context.autoStatus === 'approved' ? 'approved' : undefined,
|
||||
},
|
||||
@@ -1174,6 +1395,21 @@ export const contributionRoutes: FastifyPluginAsync = async (app) => {
|
||||
}
|
||||
})
|
||||
|
||||
// État d'une proposition, pour la personne qui l'a envoyée : ses fantômes « en attente » s'effacent quand elle
|
||||
// est relue. Seulement le statut, à qui lit l'arbre et connaît l'identifiant (rendu à l'envoi).
|
||||
app.get('/trees/:id/contributions/sessions/:sessionId/status', { config: { rateLimit: { max: 120, timeWindow: '1 minute' } } }, async (request, reply) => {
|
||||
const params = sessionParamsSchema.safeParse(request.params)
|
||||
if (!params.success) return reply.code(400).send({ error: 'invalid_params' })
|
||||
if (!request.actor) return reply.code(401).send({ error: 'authentication_required' })
|
||||
if (!(await canReadTree(app, params.data.id, request.actor))) return reply.code(403).send({ error: 'forbidden' })
|
||||
const session = await app.prisma.contributionSession.findFirst({
|
||||
where: { id: params.data.sessionId, treeId: params.data.id },
|
||||
select: { status: true },
|
||||
})
|
||||
if (!session) return reply.code(404).send({ error: 'contribution_session_not_found' })
|
||||
return reply.send({ status: session.status })
|
||||
})
|
||||
|
||||
app.post('/trees/:id/contributions/sessions/:sessionId/review', async (request, reply) => {
|
||||
const params = sessionParamsSchema.safeParse(request.params)
|
||||
if (!params.success) {
|
||||
@@ -1229,6 +1465,10 @@ export const contributionRoutes: FastifyPluginAsync = async (app) => {
|
||||
let rejectedCount = 0
|
||||
let conflictCount = 0
|
||||
const refs: RefMap = new Map()
|
||||
// Photos posées sur l'arbre par la famille : celles des annotations refusées sont libérées après toutes les
|
||||
// décisions. Une annotation acceptée dans cette même relecture a déjà retiré la ligne d'attente de sa photo,
|
||||
// qui n'est donc plus effacée (avant, la libération dans la boucle effaçait une photo acceptée plus loin).
|
||||
const rejectedAnnotationAfters: unknown[] = []
|
||||
|
||||
for (const change of byApplicationOrder(session.changes)) {
|
||||
let decision = explicitDecisions.get(change.id) ?? payload.data.decision
|
||||
@@ -1267,15 +1507,24 @@ export const contributionRoutes: FastifyPluginAsync = async (app) => {
|
||||
)
|
||||
approvedCount += 1
|
||||
} catch (error) {
|
||||
// Lien vers une personne ajoutée mais refusée : le lien est écarté, pas la relecture
|
||||
if (error instanceof ContributionRouteError && error.code === 'unresolved_reference') {
|
||||
// Lien vers une personne ajoutée mais refusée, ou annotation d'avant la 1.5.1 que le serveur ne
|
||||
// peut pas poser (contenu incomplet) : la proposition est écartée, pas la relecture
|
||||
if (error instanceof ContributionRouteError && (error.code === 'unresolved_reference' || SKIPPABLE_ANNOTATION_ERRORS.has(error.code))) {
|
||||
decision = 'rejected'
|
||||
rejectedCount += 1
|
||||
if (change.entityType === 'annotation') rejectedAnnotationAfters.push(change.afterJson)
|
||||
} else {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (change.entityType === 'life_event' && change.entityId) {
|
||||
await tx.lifeEvent.updateMany({
|
||||
where: { id: change.entityId, treeId: params.data.id },
|
||||
data: { status: 'rejected', deletedAt: new Date() },
|
||||
})
|
||||
}
|
||||
if (change.entityType === 'annotation') rejectedAnnotationAfters.push(change.afterJson)
|
||||
if (change.entityType === 'media' && change.entityId) {
|
||||
await tx.mediaItem.updateMany({
|
||||
where: { id: change.entityId, treeId: params.data.id },
|
||||
@@ -1296,6 +1545,8 @@ export const contributionRoutes: FastifyPluginAsync = async (app) => {
|
||||
})
|
||||
}
|
||||
|
||||
filesToRemove.push(...await releaseRejectedPhotos(tx, params.data.id, rejectedAnnotationAfters, session.id))
|
||||
|
||||
const status: ContributionStatus = approvedCount > 0 ? 'approved' : 'rejected'
|
||||
|
||||
const updatedSession = await tx.contributionSession.update({
|
||||
|
||||
+333
-75
@@ -2,7 +2,13 @@ import type { FastifyPluginAsync } from 'fastify'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { UPLOAD_BODY_LIMIT } from '../config/env.js'
|
||||
import { parseGedcomDate } from '../lib/gedcom-dates.js'
|
||||
import { adoptedFamilies, FAMILY_EVENT_TYPES, familyExtras, PERSON_EVENT_TYPES, personExtras } from '../lib/gedcom-events.js'
|
||||
import { indexGedcomRecords, mediaRefsForPerson, noteText, photoPathForPerson } from '../lib/gedcom-photos.js'
|
||||
import type { GedcomRecords } from '../lib/gedcom-photos.js'
|
||||
import type { MembershipRole } from '../types/auth.js'
|
||||
import { nextSiblingOrder } from '../lib/sibling-order.js'
|
||||
import { sexOrNull, type PersonSex } from '../lib/person-sex.js'
|
||||
|
||||
const treeIdParamSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
@@ -15,12 +21,17 @@ const importBodySchema = z.object({
|
||||
// Un fichier GEDCOM vient de l'extérieur : longueur des lignes, nombre de fiches et taille des champs
|
||||
// plafonnés comme partout ailleurs (sinon un seul fichier bloque l'API ou remplit la base)
|
||||
const MAX_LINE_LENGTH = 4096
|
||||
const MAX_GEDCOM_LEVEL = 99
|
||||
// Remontées d'ascendance permises sur tout l'import : au-delà, les liens ne sont plus contrôlés (fichier hors norme)
|
||||
const MAX_ANCESTRY_STEPS = 5_000_000
|
||||
const MAX_IMPORTED_PERSONS = 20000
|
||||
const MAX_IMPORTED_FAMILIES = 20000
|
||||
// Le parseur construit un objet par ligne : 10 Mo de lignes courtes montaient à 370 Mo de mémoire, et le
|
||||
// redémarrage pm2 qui suivait effaçait les limites d'essais gardées en mémoire. Au-delà, le fichier est refusé.
|
||||
const MAX_GEDCOM_NODES = 300_000
|
||||
const MAX_IMPORTED_LINKS = 60_000
|
||||
// Fichiers cités renvoyés à l'app pour en faire des souvenirs : au-delà, la réponse deviendrait trop lourde
|
||||
const MAX_IMPORTED_MEDIA_REFS = 20_000
|
||||
|
||||
class GedcomTooLargeError extends Error {}
|
||||
|
||||
@@ -33,6 +44,22 @@ function clip(value: string | null, max: number): string | null {
|
||||
return trimmed ? trimmed.slice(0, max) : null
|
||||
}
|
||||
|
||||
// Lieu d'un GEDCOM : les logiciels remplissent toutes les colonnes de leur format de lieu, même vides, et y
|
||||
// glissent des codes. Heredis écrit « La Roche-sur-Yon,85191,Vendée,Pays de la Loire,France, » (ville, code
|
||||
// INSEE, département, région, pays, subdivision). On garde les noms, sans case vide, sans code INSEE ni
|
||||
// postal, sans répétition : « La Roche-sur-Yon, Vendée, Pays de la Loire, France ».
|
||||
export function cleanGedcomPlace(value: string | null | undefined): string | null {
|
||||
if (!value) return null
|
||||
const parts: string[] = []
|
||||
for (const raw of value.split(',')) {
|
||||
const part = raw.trim()
|
||||
if (!part || /^(\d{4,5}|2[AB]\d{3})$/i.test(part)) continue
|
||||
if (parts.length && parts[parts.length - 1].toLowerCase() === part.toLowerCase()) continue
|
||||
parts.push(part)
|
||||
}
|
||||
return parts.length ? parts.join(', ') : null
|
||||
}
|
||||
|
||||
// Export : un champ sur une ligne ne doit jamais en créer une autre (enregistrement injecté)
|
||||
function oneLine(value: string | null | undefined): string {
|
||||
return String(value ?? '').replace(/[\r\n]+/g, ' ')
|
||||
@@ -49,30 +76,36 @@ type GedcomNode = {
|
||||
xref?: string
|
||||
tag: string
|
||||
value: string
|
||||
// Valeur telle qu'écrite, espaces compris : une ligne coupée en CONC se recolle sans rien perdre
|
||||
// (« pendant » + « 2 CONC trente-cinq ans » ou « pendant » + « 2 CONC trente-cinq ans »)
|
||||
rawValue?: string
|
||||
children: GedcomNode[]
|
||||
}
|
||||
|
||||
function parseGedcom(text: string): GedcomNode[] {
|
||||
export function parseGedcom(text: string): GedcomNode[] {
|
||||
const lines = text.split(/\r\n|\r|\n/)
|
||||
const roots: GedcomNode[] = []
|
||||
const stack: GedcomNode[] = []
|
||||
let nodeCount = 0
|
||||
|
||||
for (const raw of lines) {
|
||||
const line = raw.trim()
|
||||
if (!line || line.length > MAX_LINE_LENGTH) continue
|
||||
const line = raw.replace(/^[\s]+/, '')
|
||||
if (!line.trim() || line.length > MAX_LINE_LENGTH) continue
|
||||
nodeCount += 1
|
||||
if (nodeCount > MAX_GEDCOM_NODES) throw new GedcomTooLargeError()
|
||||
|
||||
const match = line.match(/^(\d+)\s+(?:(@[^@]+@)\s+)?(\w+)(?:\s+(.*))?$/)
|
||||
const match = line.match(/^(\d+)\s+(?:(@[^@]+@)\s+)?(\w+)(?:[ \t](.*))?$/)
|
||||
if (!match) continue
|
||||
|
||||
const level = parseInt(match[1], 10)
|
||||
// La norme s'arrête à 99 niveaux : au-delà, la lecture récursive de l'import déborderait la pile
|
||||
if (level > MAX_GEDCOM_LEVEL) continue
|
||||
const xref = match[2] ? match[2].slice(1, -1) : undefined
|
||||
const tag = match[3]
|
||||
const value = match[4]?.trim() ?? ''
|
||||
const rawValue = match[4] ?? ''
|
||||
const value = rawValue.trim()
|
||||
|
||||
const node: GedcomNode = { level, xref, tag, value, children: [] }
|
||||
const node: GedcomNode = { level, xref, tag, value, rawValue, children: [] }
|
||||
|
||||
while (stack.length > 0 && stack[stack.length - 1].level >= level) {
|
||||
stack.pop()
|
||||
@@ -100,36 +133,18 @@ function findAllChildren(node: GedcomNode | undefined, tag: string): GedcomNode[
|
||||
|
||||
// ─── Date Conversion ────────────────────────────────────────────────────────
|
||||
|
||||
const MONTH_MAP: Record<string, string> = {
|
||||
JAN: '01', FEB: '02', MAR: '03', APR: '04', MAY: '05', JUN: '06',
|
||||
JUL: '07', AUG: '08', SEP: '09', OCT: '10', NOV: '11', DEC: '12',
|
||||
}
|
||||
|
||||
const MONTHS_ARR = ['JAN', 'FEB', 'MAR', 'APR', 'MAY', 'JUN', 'JUL', 'AUG', 'SEP', 'OCT', 'NOV', 'DEC']
|
||||
|
||||
// Lecture complète dans lib/gedcom-dates.ts : vers, avant, après, entre, julien, républicain, double année
|
||||
function gedcomDateToIso(value: string): string | null {
|
||||
if (!value) return null
|
||||
// Remove qualifiers (ABT, BEF, AFT, EST, CAL, etc.)
|
||||
const cleaned = value.trim().toUpperCase().replace(/^(ABT|BEF|AFT|EST|CAL|INT|FROM|TO|BET|AND)\s+/, '')
|
||||
return parseGedcomDate(value)?.iso ?? null
|
||||
}
|
||||
|
||||
// "15 JAN 1900" → "1900-01-15"
|
||||
const ddMmmYyyy = cleaned.match(/^(\d{1,2})\s+([A-Z]{3})\s+(\d{4})$/)
|
||||
if (ddMmmYyyy) {
|
||||
const month = MONTH_MAP[ddMmmYyyy[2]]
|
||||
if (month) return `${ddMmmYyyy[3]}-${month}-${ddMmmYyyy[1].padStart(2, '0')}`
|
||||
}
|
||||
|
||||
// "JAN 1900" → "1900-01"
|
||||
const mmmYyyy = cleaned.match(/^([A-Z]{3})\s+(\d{4})$/)
|
||||
if (mmmYyyy) {
|
||||
const month = MONTH_MAP[mmmYyyy[1]]
|
||||
if (month) return `${mmmYyyy[2]}-${month}`
|
||||
}
|
||||
|
||||
// "1900" → "1900"
|
||||
if (/^\d{4}$/.test(cleaned)) return cleaned
|
||||
|
||||
return null
|
||||
// Notes d'une personne : écrites sous elle ou partagées (« 1 NOTE @N1@ »), lignes recollées (CONT, CONC),
|
||||
// RTF de Heredis Mac nettoyé. Plusieurs notes sont séparées par une ligne vide.
|
||||
export function personNotes(indi: GedcomNode, records: GedcomRecords): string | null {
|
||||
const texts = findAllChildren(indi, 'NOTE').map((note) => noteText(note, records)).filter(Boolean)
|
||||
return texts.length ? texts.join('\n\n') : null
|
||||
}
|
||||
|
||||
function isoDateToDbDate(iso: string | null): Date | null {
|
||||
@@ -159,10 +174,92 @@ function isoToGedcomDate(value: string | Date | null): string | null {
|
||||
return null
|
||||
}
|
||||
|
||||
// Date avec sa précision (ABT 1879, BET 1914 AND 1918…). Une date exacte reste telle quelle.
|
||||
const PRECISION_PREFIX: Record<string, string> = {
|
||||
about: 'ABT', estimated: 'EST', calculated: 'CAL', before: 'BEF', after: 'AFT', interpreted: 'INT',
|
||||
}
|
||||
|
||||
// Une date tronquée au 1er janvier vient d'une année seule : on la réécrit comme une année
|
||||
function exportedDate(value: Date | null): string | null {
|
||||
if (!value) return null
|
||||
const iso = value.toISOString().slice(0, 10)
|
||||
return isoToGedcomDate(iso.endsWith('-01-01') ? iso.slice(0, 4) : iso)
|
||||
}
|
||||
|
||||
function qualifiedGedcomDate(start: Date | null, end: Date | null, precision: string | null, text?: string | null): string | null {
|
||||
// Le texte d'origine (calendrier républicain, julien, période) prime : on le rend tel qu'il a été lu
|
||||
if (text && precision) return oneLine(text)
|
||||
const from = exportedDate(start)
|
||||
const to = exportedDate(end)
|
||||
if (!from) return text ? oneLine(text) : null
|
||||
if (!precision || precision === 'exact') return from
|
||||
if (precision === 'between') return to ? `BET ${from} AND ${to}` : `AFT ${from}`
|
||||
if (precision === 'from') return to ? `FROM ${from} TO ${to}` : `FROM ${from}`
|
||||
if (precision === 'to') return `TO ${from}`
|
||||
const prefix = PRECISION_PREFIX[precision]
|
||||
return prefix ? `${prefix} ${from}` : from
|
||||
}
|
||||
|
||||
type ExportedEvent = {
|
||||
type: string
|
||||
label: string | null
|
||||
date: Date | null
|
||||
dateEnd: Date | null
|
||||
datePrecision: string | null
|
||||
dateText: string | null
|
||||
place: string | null
|
||||
description: string | null
|
||||
notes: string | null
|
||||
sources: string | null
|
||||
}
|
||||
|
||||
// Balise GEDCOM de chaque type : la première rencontrée dans la table de lecture (BAPM avant CHR)
|
||||
const reverseTags = (table: Record<string, string>) => {
|
||||
const out: Record<string, string> = {}
|
||||
for (const [tag, type] of Object.entries(table)) if (!out[type]) out[type] = tag
|
||||
return out
|
||||
}
|
||||
const PERSON_EVENT_TAGS = reverseTags(PERSON_EVENT_TYPES)
|
||||
const FAMILY_EVENT_TAGS = reverseTags(FAMILY_EVENT_TYPES)
|
||||
|
||||
function pushMultiline(lines: string[], level: number, tag: string, text: string) {
|
||||
const [first, ...rest] = text.split(/\r\n|\r|\n/)
|
||||
lines.push(`${level} ${tag} ${first}`.trimEnd())
|
||||
for (const line of rest) lines.push(`${level + 1} CONT ${line}`.trimEnd())
|
||||
}
|
||||
|
||||
function pushNotesAndSources(lines: string[], level: number, event: Pick<ExportedEvent, 'notes' | 'sources'> | undefined) {
|
||||
if (!event) return
|
||||
if (event.notes) pushMultiline(lines, level, 'NOTE', event.notes)
|
||||
for (const source of (event.sources ?? '').split('\n').map((s) => s.trim()).filter(Boolean)) {
|
||||
lines.push(`${level} SOUR ${source}`)
|
||||
}
|
||||
}
|
||||
|
||||
function pushLifeEvent(lines: string[], event: ExportedEvent, tags: Record<string, string>) {
|
||||
const tag = tags[event.type] ?? 'EVEN'
|
||||
const value = event.description ? ` ${oneLine(event.description)}` : ''
|
||||
lines.push(`1 ${tag}${value}`)
|
||||
if (tag === 'EVEN' || tag === 'FACT') {
|
||||
const label = event.label ?? (tags[event.type] ? null : event.type)
|
||||
if (label) lines.push(`2 TYPE ${oneLine(label)}`)
|
||||
}
|
||||
const date = qualifiedGedcomDate(event.date, event.dateEnd, event.datePrecision, event.dateText)
|
||||
if (date) lines.push(`2 DATE ${date}`)
|
||||
if (event.place) lines.push(`2 PLAC ${oneLine(event.place)}`)
|
||||
pushNotesAndSources(lines, 2, event)
|
||||
}
|
||||
|
||||
// ─── Name Parsing ────────────────────────────────────────────────────────────
|
||||
|
||||
// Valeur de « 1 NAME ». Prénom inconnu (chaîne vide) : « /Dupont/ », sans espace de tête
|
||||
export function gedcomNameValue(firstName: string, lastName: string): string {
|
||||
const given = firstName ? `${oneLine(firstName)} ` : ''
|
||||
return `${given}/${oneLine(lastName).replace(/\//g, '')}/`
|
||||
}
|
||||
|
||||
// « Jean /Dupont/ » : lu par indexOf, l'ancienne expression régulière était quadratique sur les espaces
|
||||
function parseGedcomName(value: string): { firstName: string; lastName: string } {
|
||||
export function parseGedcomName(value: string): { firstName: string; lastName: string } {
|
||||
const open = value.indexOf('/')
|
||||
const close = open >= 0 ? value.indexOf('/', open + 1) : -1
|
||||
if (open >= 0 && close > open) {
|
||||
@@ -176,6 +273,27 @@ function parseGedcomName(value: string): { firstName: string; lastName: string }
|
||||
return { firstName: value.trim(), lastName: '' }
|
||||
}
|
||||
|
||||
// Réimport : une personne du fichier déjà présente dans l'arbre (même prénom, nom, naissance et décès)
|
||||
// est reprise au lieu d'être créée une seconde fois
|
||||
function personKey(firstName: string, lastName: string, birthDate: Date | null, deathDate: Date | null): string {
|
||||
const norm = (value: string) => value.normalize('NFC').trim().toLowerCase()
|
||||
const day = (value: Date | null) => (value ? value.toISOString().slice(0, 10) : '')
|
||||
return [norm(firstName), norm(lastName), day(birthDate), day(deathDate)].join('|')
|
||||
}
|
||||
|
||||
function pairKey(a: string, b: string | null): string {
|
||||
return b ? [a, b].sort().join('|') : `${a}|`
|
||||
}
|
||||
|
||||
// GEDCOM 5.5.1 n'admet que M, F et U (inconnu, autre). « X » n'existe qu'en 7.0 : un sexe « autre » s'écrit U,
|
||||
// et l'import relit X comme avant.
|
||||
export function gedcomSexValue(sex: PersonSex | null): 'M' | 'F' | 'U' | null {
|
||||
if (sex === 'male') return 'M'
|
||||
if (sex === 'female') return 'F'
|
||||
if (sex === 'other') return 'U'
|
||||
return null
|
||||
}
|
||||
|
||||
function sanitizeXref(id: string): string {
|
||||
return id.replace(/[^A-Za-z0-9_]/g, '_')
|
||||
}
|
||||
@@ -229,10 +347,11 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => {
|
||||
}
|
||||
}
|
||||
|
||||
const [persons, unions, links] = await Promise.all([
|
||||
const [persons, unions, links, lifeEvents] = await Promise.all([
|
||||
app.prisma.person.findMany({ where: { treeId, deletedAt: null } }),
|
||||
app.prisma.union.findMany({ where: { treeId, deletedAt: null } }),
|
||||
app.prisma.parentChildLink.findMany({ where: { treeId, deletedAt: null } }),
|
||||
app.prisma.lifeEvent.findMany({ where: { treeId, deletedAt: null, status: 'approved' }, orderBy: [{ date: 'asc' }, { displayOrder: 'asc' }] }),
|
||||
])
|
||||
|
||||
const personById = new Map(persons.map((p) => [p.id, p]))
|
||||
@@ -269,6 +388,7 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => {
|
||||
|
||||
// Assign each child to a union FAM
|
||||
const childrenByUnion = new Map<string, Set<string>>()
|
||||
const adoptedInUnion = new Set<string>()
|
||||
for (const link of links) {
|
||||
const childId = link.childPersonId
|
||||
let unionId: string | undefined
|
||||
@@ -289,6 +409,7 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => {
|
||||
}
|
||||
|
||||
if (!unionId) continue
|
||||
if (link.parentageType === 'adoption') adoptedInUnion.add(`${unionId}|${childId}`)
|
||||
const set = childrenByUnion.get(unionId) ?? new Set()
|
||||
set.add(childId)
|
||||
childrenByUnion.set(unionId, set)
|
||||
@@ -315,6 +436,16 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => {
|
||||
}
|
||||
}
|
||||
|
||||
// Événements de vie : rangés par personne et par union, pour les réécrire sous leur propriétaire
|
||||
const eventsByPerson = new Map<string, typeof lifeEvents>()
|
||||
const eventsByUnion = new Map<string, typeof lifeEvents>()
|
||||
for (const event of lifeEvents) {
|
||||
const target = event.personId ? eventsByPerson : event.unionId ? eventsByUnion : null
|
||||
const key = event.personId ?? event.unionId
|
||||
if (!target || !key) continue
|
||||
target.set(key, [...(target.get(key) ?? []), event])
|
||||
}
|
||||
|
||||
// ── Write GEDCOM ──
|
||||
const lines: string[] = []
|
||||
const now = new Date()
|
||||
@@ -331,25 +462,43 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => {
|
||||
for (const person of persons) {
|
||||
const xref = sanitizeXref(person.id)
|
||||
lines.push(`0 @I${xref}@ INDI`)
|
||||
lines.push(`1 NAME ${oneLine(person.firstName)} /${oneLine(person.lastName).replace(/\//g, '')}/`)
|
||||
lines.push(`1 NAME ${gedcomNameValue(person.firstName, person.lastName)}`)
|
||||
if (person.nickname) lines.push(`2 NICK ${oneLine(person.nickname)}`)
|
||||
|
||||
if (person.sex === 'male' || person.sex === 'M') lines.push('1 SEX M')
|
||||
else if (person.sex === 'female' || person.sex === 'F') lines.push('1 SEX F')
|
||||
const sexValue = gedcomSexValue(sexOrNull(person.sex))
|
||||
if (sexValue) lines.push(`1 SEX ${sexValue}`)
|
||||
|
||||
const birthDate = isoToGedcomDate(person.birthDate)
|
||||
if (birthDate || person.birthPlace) {
|
||||
const personEvents = eventsByPerson.get(person.id) ?? []
|
||||
const birthDetails = personEvents.find((event) => event.type === 'birth')
|
||||
const deathDetails = personEvents.find((event) => event.type === 'death')
|
||||
|
||||
const birthDate = qualifiedGedcomDate(person.birthDate, person.birthDateEnd, person.birthDatePrecision)
|
||||
if (birthDate || person.birthPlace || birthDetails) {
|
||||
lines.push('1 BIRT')
|
||||
if (birthDate) lines.push(`2 DATE ${birthDate}`)
|
||||
if (person.birthPlace) lines.push(`2 PLAC ${oneLine(person.birthPlace)}`)
|
||||
pushNotesAndSources(lines, 2, birthDetails)
|
||||
}
|
||||
|
||||
const deathDate = isoToGedcomDate(person.deathDate)
|
||||
if (deathDate) {
|
||||
const deathDate = qualifiedGedcomDate(person.deathDate, person.deathDateEnd, person.deathDatePrecision)
|
||||
if (deathDate || person.deathPlace || deathDetails) {
|
||||
lines.push('1 DEAT')
|
||||
lines.push(`2 DATE ${deathDate}`)
|
||||
if (deathDate) lines.push(`2 DATE ${deathDate}`)
|
||||
if (person.deathPlace) lines.push(`2 PLAC ${oneLine(person.deathPlace)}`)
|
||||
pushNotesAndSources(lines, 2, deathDetails)
|
||||
} else if (person.isDeceased) {
|
||||
// Décédé(e) sans rien d'autre : la forme courte de la norme
|
||||
lines.push('1 DEAT Y')
|
||||
}
|
||||
|
||||
if (person.profession) lines.push(`1 OCCU ${oneLine(person.profession)}`)
|
||||
// Le champ « profession » s'écrit seulement s'il n'est pas déjà un des métiers datés
|
||||
const professionKnown = personEvents.some(
|
||||
(event) => event.type === 'occupation' && event.description?.trim().toLowerCase() === person.profession?.trim().toLowerCase(),
|
||||
)
|
||||
if (person.profession && !professionKnown) lines.push(`1 OCCU ${oneLine(person.profession)}`)
|
||||
for (const event of personEvents) {
|
||||
if (event.type !== 'birth' && event.type !== 'death') pushLifeEvent(lines, event, PERSON_EVENT_TAGS)
|
||||
}
|
||||
|
||||
if (person.notes) {
|
||||
const noteLines = person.notes.split(/\r\n|\r|\n/)
|
||||
@@ -367,6 +516,7 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => {
|
||||
// FAMC: links this person to their parent family (as child)
|
||||
for (const uid of famcByPerson.get(person.id) ?? []) {
|
||||
lines.push(`1 FAMC @F${sanitizeXref(uid)}@`)
|
||||
if (adoptedInUnion.has(`${uid}|${person.id}`)) lines.push('2 PEDI adopted')
|
||||
}
|
||||
}
|
||||
|
||||
@@ -378,9 +528,9 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => {
|
||||
const p1 = union.partner1PersonId ? personById.get(union.partner1PersonId) : null
|
||||
const p2 = union.partner2PersonId ? personById.get(union.partner2PersonId) : null
|
||||
|
||||
const p1IsFemale = p1?.sex === 'female' || p1?.sex === 'F'
|
||||
const p1IsMale = p1?.sex === 'male' || p1?.sex === 'M'
|
||||
const p2IsMale = p2?.sex === 'male' || p2?.sex === 'M'
|
||||
const p1IsFemale = sexOrNull(p1?.sex) === 'female'
|
||||
const p1IsMale = sexOrNull(p1?.sex) === 'male'
|
||||
const p2IsMale = sexOrNull(p2?.sex) === 'male'
|
||||
|
||||
// Swap to HUSB=male if we know p1 is female and p2 is male (or unknown)
|
||||
const shouldSwap = p1IsFemale && !p2IsMale === false ? false : p1IsFemale && (p2IsMale || !p1IsMale)
|
||||
@@ -394,10 +544,17 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => {
|
||||
lines.push(`1 CHIL @I${sanitizeXref(childId)}@`)
|
||||
}
|
||||
|
||||
const marriageDate = isoToGedcomDate(union.startDate)
|
||||
if (marriageDate) {
|
||||
const unionEvents = eventsByUnion.get(union.id) ?? []
|
||||
const marriageDetails = unionEvents.find((event) => event.type === 'marriage')
|
||||
const marriageDate = qualifiedGedcomDate(union.startDate, null, union.startDatePrecision)
|
||||
if (marriageDate || union.startPlace || marriageDetails) {
|
||||
lines.push('1 MARR')
|
||||
lines.push(`2 DATE ${marriageDate}`)
|
||||
if (marriageDate) lines.push(`2 DATE ${marriageDate}`)
|
||||
if (union.startPlace) lines.push(`2 PLAC ${oneLine(union.startPlace)}`)
|
||||
pushNotesAndSources(lines, 2, marriageDetails)
|
||||
}
|
||||
for (const event of unionEvents) {
|
||||
if (event.type !== 'marriage') pushLifeEvent(lines, event, FAMILY_EVENT_TAGS)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -466,9 +623,57 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => {
|
||||
}
|
||||
|
||||
const xrefToPersonId = new Map<string, string>()
|
||||
const records = indexGedcomRecords(roots)
|
||||
const objeByXref = records.obje
|
||||
const photoRefs: Array<{ personId: string; file: string }> = []
|
||||
// Les autres fichiers cités (actes, registres, photos de famille) : des souvenirs pour les personnes
|
||||
// créées par cet import. Une personne déjà dans l'arbre n'en reçoit pas, un second import ne double rien.
|
||||
const mediaRefs: Array<{ personId: string; file: string; caption: string | null; source: string | null }> = []
|
||||
|
||||
// Ce que l'arbre contient déjà : un second import du même fichier complète l'arbre sans rien doubler.
|
||||
// Chaque personne existante ne sert qu'une fois, deux fiches identiques du fichier restent deux personnes.
|
||||
const [existingPersons, existingUnions, existingLinks] = await Promise.all([
|
||||
app.prisma.person.findMany({
|
||||
where: { treeId, deletedAt: null },
|
||||
select: { id: true, firstName: true, lastName: true, birthDate: true, deathDate: true, avatarPath: true },
|
||||
}),
|
||||
app.prisma.union.findMany({ where: { treeId, deletedAt: null }, select: { id: true, partner1PersonId: true, partner2PersonId: true } }),
|
||||
app.prisma.parentChildLink.findMany({ where: { treeId, deletedAt: null }, select: { parentPersonId: true, childPersonId: true } }),
|
||||
])
|
||||
const reusablePersons = new Map<string, Array<{ id: string; hasAvatar: boolean }>>()
|
||||
for (const person of existingPersons) {
|
||||
const key = personKey(person.firstName, person.lastName, person.birthDate, person.deathDate)
|
||||
if (!reusablePersons.has(key)) reusablePersons.set(key, [])
|
||||
reusablePersons.get(key)!.push({ id: person.id, hasAvatar: Boolean(person.avatarPath) })
|
||||
}
|
||||
const unionByPair = new Map(existingUnions.map((u) => [pairKey(u.partner1PersonId, u.partner2PersonId), u.id]))
|
||||
const linkKeys = new Set(existingLinks.map((l) => `${l.parentPersonId}:${l.childPersonId}`))
|
||||
// Parents de chaque personne, pour refuser un lien qui ferait de quelqu'un son propre ancêtre
|
||||
// (les validateurs de l'API relisent tout l'arbre à chaque lien : trop lent pour un import)
|
||||
const parentsOf = new Map<string, string[]>()
|
||||
for (const link of existingLinks) parentsOf.set(link.childPersonId, [...(parentsOf.get(link.childPersonId) ?? []), link.parentPersonId])
|
||||
let ancestryBudget = MAX_ANCESTRY_STEPS
|
||||
const isAncestorOf = (candidate: string, personId: string): boolean => {
|
||||
const seen = new Set<string>()
|
||||
const stack = [personId]
|
||||
while (stack.length) {
|
||||
const current = stack.pop()!
|
||||
if (current === candidate) return true
|
||||
if (seen.has(current) || --ancestryBudget < 0) continue
|
||||
seen.add(current)
|
||||
stack.push(...(parentsOf.get(current) ?? []))
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
let personsCreated = 0
|
||||
let personsReused = 0
|
||||
let unionsCreated = 0
|
||||
let linksCreated = 0
|
||||
let eventsCreated = 0
|
||||
let relationsSkipped = 0
|
||||
// Adoptions déclarées sous l'enfant (« 2 PEDI adopted ») : enfant → familles où il est adopté
|
||||
const adoptedByChild = new Map(indiNodes.map((indi) => [indi.xref!, adoptedFamilies(indi)]))
|
||||
|
||||
importInProgress = true
|
||||
try {
|
||||
@@ -477,45 +682,69 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => {
|
||||
const nameNode = findChild(indi, 'NAME')
|
||||
const { firstName, lastName } = nameNode
|
||||
? parseGedcomName(nameNode.value)
|
||||
: { firstName: '?', lastName: '' }
|
||||
: { firstName: '', lastName: '' }
|
||||
|
||||
const sexNode = findChild(indi, 'SEX')
|
||||
const sex = sexNode?.value === 'M' ? 'male' : sexNode?.value === 'F' ? 'female' : null
|
||||
const sex = sexOrNull(sexNode?.value)
|
||||
|
||||
const birtNode = findChild(indi, 'BIRT')
|
||||
const birthDateIso = gedcomDateToIso(findChild(birtNode, 'DATE')?.value ?? '')
|
||||
const birthPlace = clip(findChild(birtNode, 'PLAC')?.value ?? null, 200)
|
||||
const birthPlace = clip(cleanGedcomPlace(findChild(birtNode, 'PLAC')?.value), 200)
|
||||
|
||||
const deatNode = findChild(indi, 'DEAT')
|
||||
const deathDateIso = gedcomDateToIso(findChild(deatNode, 'DATE')?.value ?? '')
|
||||
|
||||
const profession = clip(findChild(indi, 'OCCU')?.value ?? null, 200)
|
||||
|
||||
const noteNode = findChild(indi, 'NOTE')
|
||||
let notes: string | null = null
|
||||
if (noteNode?.value) {
|
||||
const contLines = findAllChildren(noteNode, 'CONT').map((n) => n.value)
|
||||
notes = clip([noteNode.value, ...contLines].join('\n'), 2000)
|
||||
// Prénom absent du fichier : chaîne vide, comme un prénom inconnu dans l'arbre
|
||||
const personFirstName = (firstName || '').slice(0, 120)
|
||||
const personLastName = (lastName || '').slice(0, 120)
|
||||
const birthDate = isoDateToDbDate(birthDateIso)
|
||||
const deathDate = isoDateToDbDate(deathDateIso)
|
||||
const photoPath = photoPathForPerson(indi, objeByXref)
|
||||
|
||||
const existing = reusablePersons.get(personKey(personFirstName, personLastName, birthDate, deathDate))?.shift()
|
||||
if (existing) {
|
||||
xrefToPersonId.set(indi.xref!, existing.id)
|
||||
personsReused++
|
||||
// Une personne qui a déjà son portrait le garde
|
||||
if (photoPath && !existing.hasAvatar) photoRefs.push({ personId: existing.id, file: photoPath })
|
||||
continue
|
||||
}
|
||||
|
||||
const notes = clip(personNotes(indi, records), 2000)
|
||||
const { events, ...extras } = personExtras(indi, records)
|
||||
const person = await tx.person.create({
|
||||
data: {
|
||||
treeId,
|
||||
firstName: (firstName || '?').slice(0, 120),
|
||||
lastName: (lastName || '').slice(0, 120),
|
||||
firstName: personFirstName,
|
||||
lastName: personLastName,
|
||||
sex,
|
||||
birthDate: isoDateToDbDate(birthDateIso),
|
||||
deathDate: isoDateToDbDate(deathDateIso),
|
||||
birthDate,
|
||||
deathDate,
|
||||
// « 1 DEAT Y » ou un décès sans date : décédé(e), date inconnue
|
||||
isDeceased: Boolean(deatNode) && !deathDate,
|
||||
birthPlace,
|
||||
profession,
|
||||
notes,
|
||||
...extras,
|
||||
createdBy: actor.userId,
|
||||
updatedBy: actor.userId,
|
||||
},
|
||||
})
|
||||
if (events.length) {
|
||||
await tx.lifeEvent.createMany({ data: events.map((event, index) => ({ ...event, treeId, personId: person.id, displayOrder: index + 1 })) })
|
||||
eventsCreated += events.length
|
||||
}
|
||||
|
||||
xrefToPersonId.set(indi.xref!, person.id)
|
||||
personsCreated++
|
||||
if (photoPath) photoRefs.push({ personId: person.id, file: photoPath })
|
||||
const personMedia = mediaRefs.length < MAX_IMPORTED_MEDIA_REFS ? mediaRefsForPerson(indi, records, photoPath) : []
|
||||
for (const ref of personMedia) {
|
||||
if (mediaRefs.length >= MAX_IMPORTED_MEDIA_REFS) break
|
||||
mediaRefs.push({ personId: person.id, ...ref })
|
||||
}
|
||||
}
|
||||
|
||||
for (const fam of famNodes) {
|
||||
@@ -523,23 +752,40 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => {
|
||||
const wifeXref = findChild(fam, 'WIFE')?.value?.replace(/@/g, '').trim()
|
||||
|
||||
const partner1Id = husbXref ? xrefToPersonId.get(husbXref) : undefined
|
||||
const partner2Id = wifeXref ? xrefToPersonId.get(wifeXref) : undefined
|
||||
let partner2Id = wifeXref ? xrefToPersonId.get(wifeXref) : undefined
|
||||
// Une même personne des deux côtés d'une union : un seul partenaire
|
||||
if (partner2Id && partner2Id === partner1Id) {
|
||||
partner2Id = undefined
|
||||
relationsSkipped++
|
||||
}
|
||||
|
||||
if (!partner1Id && !partner2Id) continue
|
||||
|
||||
const marrNode = findChild(fam, 'MARR')
|
||||
const marriageDateIso = gedcomDateToIso(findChild(marrNode, 'DATE')?.value ?? '')
|
||||
|
||||
const union = await tx.union.create({
|
||||
data: {
|
||||
treeId,
|
||||
partner1PersonId: partner1Id ?? partner2Id!,
|
||||
partner2PersonId: partner1Id ? (partner2Id ?? null) : null,
|
||||
startDate: isoDateToDbDate(marriageDateIso),
|
||||
},
|
||||
})
|
||||
|
||||
unionsCreated++
|
||||
const firstPartner = partner1Id ?? partner2Id!
|
||||
const secondPartner = partner1Id ? (partner2Id ?? null) : null
|
||||
let unionId = unionByPair.get(pairKey(firstPartner, secondPartner))
|
||||
if (!unionId) {
|
||||
const { events: familyEvents, ...unionExtras } = familyExtras(fam, records)
|
||||
const union = await tx.union.create({
|
||||
data: {
|
||||
treeId,
|
||||
partner1PersonId: firstPartner,
|
||||
partner2PersonId: secondPartner,
|
||||
startDate: isoDateToDbDate(marriageDateIso),
|
||||
...unionExtras,
|
||||
},
|
||||
})
|
||||
unionId = union.id
|
||||
unionByPair.set(pairKey(firstPartner, secondPartner), unionId)
|
||||
unionsCreated++
|
||||
if (familyEvents.length) {
|
||||
await tx.lifeEvent.createMany({ data: familyEvents.map((event, index) => ({ ...event, treeId, unionId: union.id, displayOrder: index + 1 })) })
|
||||
eventsCreated += familyEvents.length
|
||||
}
|
||||
}
|
||||
|
||||
const chilNodes = findAllChildren(fam, 'CHIL')
|
||||
const seenChildren = new Set<string>()
|
||||
@@ -555,14 +801,24 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => {
|
||||
const parentIds = [partner1Id, partner2Id].filter((id): id is string => Boolean(id))
|
||||
|
||||
for (const parentId of parentIds) {
|
||||
const linkKey = `${parentId}:${childId}`
|
||||
if (linkKeys.has(linkKey)) continue
|
||||
if (parentId === childId || isAncestorOf(childId, parentId)) {
|
||||
relationsSkipped++
|
||||
continue
|
||||
}
|
||||
await tx.parentChildLink.create({
|
||||
data: {
|
||||
treeId,
|
||||
parentPersonId: parentId,
|
||||
childPersonId: childId,
|
||||
viaUnionId: union.id,
|
||||
viaUnionId: unionId,
|
||||
...(adoptedByChild.get(chilXref)?.has(fam.xref!) ? { parentageType: 'adoption' } : {}),
|
||||
displayOrder: await nextSiblingOrder(tx, treeId, parentId),
|
||||
},
|
||||
})
|
||||
linkKeys.add(linkKey)
|
||||
parentsOf.set(childId, [...(parentsOf.get(childId) ?? []), parentId])
|
||||
linksCreated++
|
||||
}
|
||||
}
|
||||
@@ -576,7 +832,7 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => {
|
||||
action: 'gedcom_imported',
|
||||
entityType: 'tree',
|
||||
entityId: treeId,
|
||||
payloadJson: { personsCreated, unionsCreated, linksCreated },
|
||||
payloadJson: { personsCreated, personsReused, unionsCreated, linksCreated, eventsCreated, relationsSkipped, photoRefs: photoRefs.length, mediaRefs: mediaRefs.length },
|
||||
},
|
||||
})
|
||||
}, { timeout: 60000 })
|
||||
@@ -584,6 +840,8 @@ export const gedcomRoutes: FastifyPluginAsync = async (app) => {
|
||||
importInProgress = false
|
||||
}
|
||||
|
||||
return reply.send({ personsCreated, unionsCreated, linksCreated })
|
||||
// photoRefs : chemin de la photo que le logiciel d'origine associait à chaque personne ; mediaRefs : les
|
||||
// autres fichiers cités, avec leur titre et leur source (rien n'est gardé en base)
|
||||
return reply.send({ personsCreated, personsReused, unionsCreated, linksCreated, eventsCreated, relationsSkipped, photoRefs, mediaRefs })
|
||||
})
|
||||
}
|
||||
+168
-62
@@ -1,4 +1,4 @@
|
||||
import type { FastifyPluginAsync } from 'fastify'
|
||||
import type { FastifyInstance, FastifyPluginAsync, FastifyRequest } from 'fastify'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { signMediaToken } from '../lib/tree-access.js'
|
||||
@@ -9,47 +9,65 @@ const treeIdParamSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
})
|
||||
|
||||
export const graphRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get('/trees/:id/graph', async (request, reply) => {
|
||||
const params = treeIdParamSchema.safeParse(request.params)
|
||||
if (!params.success) {
|
||||
return reply.code(400).send({ error: 'invalid_tree_id' })
|
||||
type ReadAccess =
|
||||
| { ok: true; rootPersonId: string | null; visitKind: VisitAccessKind }
|
||||
| { ok: false; status: number; error: string }
|
||||
|
||||
// Qui peut lire un arbre : un accès par mot de passe de cet arbre, un membre, ou un compte avec qui il est
|
||||
// partagé. Utilisé par le graphe et par la frise de vie d'une personne.
|
||||
async function resolveReadAccess(app: FastifyInstance, actor: FastifyRequest['actor'], treeId: string): Promise<ReadAccess> {
|
||||
let rootPersonId: string | null = null
|
||||
let visitKind: VisitAccessKind = 'share'
|
||||
if (!actor) {
|
||||
return { ok: false, status: 401, error: 'authentication_required' }
|
||||
}
|
||||
|
||||
if (actor.kind === 'tree_access') {
|
||||
if (actor.treeId !== treeId) {
|
||||
return { ok: false, status: 403, error: 'forbidden' }
|
||||
}
|
||||
|
||||
const treeId = params.data.id
|
||||
const actor = request.actor
|
||||
let rootPersonId: string | null = null
|
||||
let visitKind: VisitAccessKind = 'share'
|
||||
const tree = await app.prisma.tree.findFirst({
|
||||
where: {
|
||||
id: treeId,
|
||||
deletedAt: null,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
rootPersonId: true,
|
||||
},
|
||||
})
|
||||
|
||||
if (!actor) {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
if (!tree) {
|
||||
return { ok: false, status: 404, error: 'tree_not_found' }
|
||||
}
|
||||
|
||||
if (actor.kind === 'tree_access') {
|
||||
if (actor.treeId !== treeId) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
rootPersonId = tree.rootPersonId
|
||||
}
|
||||
|
||||
const tree = await app.prisma.tree.findFirst({
|
||||
where: {
|
||||
id: treeId,
|
||||
deletedAt: null,
|
||||
if (actor.kind === 'user') {
|
||||
const membership = await app.prisma.treeMembership.findUnique({
|
||||
where: {
|
||||
treeId_userId: {
|
||||
treeId,
|
||||
userId: actor.userId,
|
||||
},
|
||||
select: {
|
||||
id: true,
|
||||
rootPersonId: true,
|
||||
},
|
||||
include: {
|
||||
tree: {
|
||||
select: {
|
||||
deletedAt: true,
|
||||
rootPersonId: true,
|
||||
},
|
||||
},
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
if (!tree) {
|
||||
return reply.code(404).send({ error: 'tree_not_found' })
|
||||
}
|
||||
|
||||
rootPersonId = tree.rootPersonId
|
||||
}
|
||||
|
||||
if (actor.kind === 'user') {
|
||||
const membership = await app.prisma.treeMembership.findUnique({
|
||||
if (membership && !membership.tree.deletedAt) {
|
||||
rootPersonId = membership.tree.rootPersonId
|
||||
visitKind = 'member'
|
||||
} else {
|
||||
const shared = await app.prisma.userTreeAccess.findUnique({
|
||||
where: {
|
||||
treeId_userId: {
|
||||
treeId,
|
||||
@@ -66,40 +84,42 @@ export const graphRoutes: FastifyPluginAsync = async (app) => {
|
||||
},
|
||||
})
|
||||
|
||||
if (membership && !membership.tree.deletedAt) {
|
||||
rootPersonId = membership.tree.rootPersonId
|
||||
visitKind = 'member'
|
||||
} else {
|
||||
const shared = await app.prisma.userTreeAccess.findUnique({
|
||||
where: {
|
||||
treeId_userId: {
|
||||
treeId,
|
||||
userId: actor.userId,
|
||||
},
|
||||
},
|
||||
include: {
|
||||
tree: {
|
||||
select: {
|
||||
deletedAt: true,
|
||||
rootPersonId: true,
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (!shared || shared.tree.deletedAt) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
|
||||
rootPersonId = shared.tree.rootPersonId
|
||||
visitKind = 'shared_account'
|
||||
if (!shared || shared.tree.deletedAt) {
|
||||
return { ok: false, status: 403, error: 'forbidden' }
|
||||
}
|
||||
|
||||
rootPersonId = shared.tree.rootPersonId
|
||||
visitKind = 'shared_account'
|
||||
}
|
||||
}
|
||||
|
||||
return { ok: true, rootPersonId, visitKind }
|
||||
}
|
||||
|
||||
export const graphRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get('/trees/:id/graph', async (request, reply) => {
|
||||
const params = treeIdParamSchema.safeParse(request.params)
|
||||
if (!params.success) {
|
||||
return reply.code(400).send({ error: 'invalid_tree_id' })
|
||||
}
|
||||
|
||||
const treeId = params.data.id
|
||||
const actor = request.actor
|
||||
let rootPersonId: string | null = null
|
||||
let visitKind: VisitAccessKind = 'share'
|
||||
|
||||
const access = await resolveReadAccess(app, actor, treeId)
|
||||
if (!access.ok || !actor) {
|
||||
if (access.ok) return reply.code(401).send({ error: 'authentication_required' })
|
||||
return reply.code(access.status).send({ error: access.error })
|
||||
}
|
||||
rootPersonId = access.rootPersonId
|
||||
visitKind = access.visitKind
|
||||
|
||||
// Journal des visites (onglet Visites des administrateurs), sans attendre
|
||||
void recordTreeVisit(app, request, treeId, visitKind, actor.kind === 'user' ? actor.userId : null)
|
||||
|
||||
const [persons, unions, links, medias, annotations] = await Promise.all([
|
||||
const [persons, unions, links, medias, annotations, mediaPeople] = await Promise.all([
|
||||
app.prisma.person.findMany({
|
||||
where: {
|
||||
treeId,
|
||||
@@ -136,9 +156,14 @@ export const graphRoutes: FastifyPluginAsync = async (app) => {
|
||||
},
|
||||
orderBy: [{ zIndex: 'asc' }, { createdAt: 'asc' }, { id: 'asc' }],
|
||||
}),
|
||||
app.prisma.mediaPersonTag.findMany({
|
||||
where: { treeId },
|
||||
select: { mediaId: true, personId: true, x: true, y: true },
|
||||
orderBy: [{ createdAt: 'asc' }, { id: 'asc' }],
|
||||
}),
|
||||
])
|
||||
|
||||
const graph = buildGraphPayload(treeId, persons, unions, links, medias, annotations)
|
||||
const graph = buildGraphPayload(treeId, persons, unions, links, medias, annotations, mediaPeople)
|
||||
|
||||
return reply.send({
|
||||
treeId,
|
||||
@@ -148,4 +173,85 @@ export const graphRoutes: FastifyPluginAsync = async (app) => {
|
||||
mediaToken: signMediaToken(app, treeId, actor),
|
||||
})
|
||||
})
|
||||
|
||||
// Frise de vie d'une personne : chargée à l'ouverture de la fiche plutôt que dans le graphe, qui resterait
|
||||
// lourd sur un grand arbre. Mêmes droits de lecture que le graphe.
|
||||
app.get('/trees/:id/persons/:personId/life', async (request, reply) => {
|
||||
const params = z.object({ id: z.string().min(1), personId: z.string().min(1) }).safeParse(request.params)
|
||||
if (!params.success) {
|
||||
return reply.code(400).send({ error: 'invalid_params' })
|
||||
}
|
||||
const { id: treeId, personId } = params.data
|
||||
const access = await resolveReadAccess(app, request.actor, treeId)
|
||||
if (!access.ok) {
|
||||
return reply.code(access.status).send({ error: access.error })
|
||||
}
|
||||
|
||||
const person = await app.prisma.person.findFirst({
|
||||
where: { id: personId, treeId, deletedAt: null },
|
||||
select: {
|
||||
id: true, birthDatePrecision: true, birthDateEnd: true, deathDatePrecision: true, deathDateEnd: true,
|
||||
deathPlace: true, nickname: true,
|
||||
},
|
||||
})
|
||||
if (!person) {
|
||||
return reply.code(404).send({ error: 'person_not_found' })
|
||||
}
|
||||
|
||||
const unions = await app.prisma.union.findMany({
|
||||
where: { treeId, deletedAt: null, OR: [{ partner1PersonId: personId }, { partner2PersonId: personId }] },
|
||||
select: { id: true, partner1PersonId: true, partner2PersonId: true, startDate: true, startPlace: true, startDatePrecision: true, endDate: true },
|
||||
orderBy: [{ displayOrder: 'asc' }, { createdAt: 'asc' }],
|
||||
})
|
||||
const unionIds = unions.map((union) => union.id)
|
||||
const events = await app.prisma.lifeEvent.findMany({
|
||||
where: { treeId, deletedAt: null, status: 'approved', OR: [{ personId }, ...(unionIds.length ? [{ unionId: { in: unionIds } }] : [])] },
|
||||
select: {
|
||||
id: true, personId: true, unionId: true, type: true, label: true, date: true, dateEnd: true, datePrecision: true,
|
||||
dateText: true, place: true, description: true, notes: true, sources: true, mediaId: true, displayOrder: true,
|
||||
},
|
||||
orderBy: [{ date: 'asc' }, { displayOrder: 'asc' }, { createdAt: 'asc' }],
|
||||
})
|
||||
|
||||
// Souvenirs rattachés à chaque moment (photo, vidéo, acte…), visibles seulement une fois acceptés
|
||||
const attached = events.length
|
||||
? await app.prisma.mediaItem.findMany({
|
||||
where: { treeId, lifeEventId: { in: events.map((event) => event.id) }, status: 'approved', deletedAt: null },
|
||||
select: { id: true, lifeEventId: true },
|
||||
orderBy: [{ displayOrder: 'asc' }, { createdAt: 'asc' }],
|
||||
})
|
||||
: []
|
||||
const mediaIdsByEvent = new Map<string, string[]>()
|
||||
for (const media of attached) {
|
||||
if (!media.lifeEventId) continue
|
||||
mediaIdsByEvent.set(media.lifeEventId, [...(mediaIdsByEvent.get(media.lifeEventId) ?? []), media.id])
|
||||
}
|
||||
|
||||
const day = (value: Date | null) => (value ? value.toISOString().slice(0, 10) : null)
|
||||
return reply.send({
|
||||
person: {
|
||||
birthDatePrecision: person.birthDatePrecision,
|
||||
birthDateEnd: day(person.birthDateEnd),
|
||||
deathDatePrecision: person.deathDatePrecision,
|
||||
deathDateEnd: day(person.deathDateEnd),
|
||||
deathPlace: person.deathPlace,
|
||||
nickname: person.nickname,
|
||||
},
|
||||
unions: unions.map((union) => ({
|
||||
id: union.id,
|
||||
partnerId: union.partner1PersonId === personId ? union.partner2PersonId : union.partner1PersonId,
|
||||
startDate: day(union.startDate),
|
||||
startPlace: union.startPlace,
|
||||
startDatePrecision: union.startDatePrecision,
|
||||
endDate: day(union.endDate),
|
||||
})),
|
||||
// L'ancienne colonne mediaId est reprise par media_items.lifeEventId (migration du 17/10)
|
||||
events: events.map(({ mediaId: _legacy, ...event }) => ({
|
||||
...event,
|
||||
date: day(event.date),
|
||||
dateEnd: day(event.dateEnd),
|
||||
mediaIds: mediaIdsByEvent.get(event.id) ?? [],
|
||||
})),
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,660 @@
|
||||
import { Prisma } from '../generated/prisma/client.js'
|
||||
import type { FastifyInstance, FastifyPluginAsync, FastifyReply, FastifyRequest } from 'fastify'
|
||||
import path from 'node:path'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { mkdir, writeFile } from 'node:fs/promises'
|
||||
import { z } from 'zod'
|
||||
|
||||
import {
|
||||
getImmichInstanceByApiUrl,
|
||||
getImmichInstances,
|
||||
getTreeImmichClient,
|
||||
isImmichPersonId,
|
||||
normalizeImmichApiUrl,
|
||||
ImmichAuthError,
|
||||
ImmichNotFoundError,
|
||||
ImmichUnavailableError,
|
||||
type ImmichPersonSummary,
|
||||
} from '../lib/immich.js'
|
||||
import { computeBlurhash } from '../lib/blurhash.js'
|
||||
import { decryptImmichApiKey, encryptImmichApiKey } from '../lib/immich-secret.js'
|
||||
import { IMAGE_MIME_TYPES, InvalidMediaError, isImmichAvatarPath, removeStoredFile, sniffMimeType } from '../lib/media-files.js'
|
||||
import { exceedsStorageQuota, getStorageRoot, prepareUploadedFile } from './media.js'
|
||||
|
||||
// Reconnaissance des visages : associer une personne de l'arbre à une personne Immich, dont la
|
||||
// vignette devient son portrait. Chaque arbre porte sa propre connexion Immich : une adresse
|
||||
// choisie parmi celles autorisées par l'opérateur du serveur (IMMICH_ALLOWED_API_URLS), et une
|
||||
// clé chiffrée en base. Toutes les routes sont rattachées à un arbre, réservées à ses
|
||||
// administrateurs, et ne parlent jamais à l'instance d'un autre arbre.
|
||||
|
||||
const treeParamSchema = z.object({ id: z.string().min(1) })
|
||||
const treePersonParamsSchema = z.object({ id: z.string().min(1), personId: z.string().min(1) })
|
||||
|
||||
const assignSchema = z.object({
|
||||
personId: z.string().min(1),
|
||||
immichPersonId: z.string().refine(isImmichPersonId, 'invalid_immich_person_id'),
|
||||
// Remplacer un portrait déjà en place demande un accord explicite, quelle que soit son
|
||||
// origine (posé à la main ou venu d'une association Immich précédente).
|
||||
replaceAvatar: z.boolean().optional(),
|
||||
})
|
||||
|
||||
const unassignSchema = z.object({
|
||||
personId: z.string().min(1),
|
||||
})
|
||||
|
||||
const thumbnailParamSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
immichPersonId: z.string().refine(isImmichPersonId, 'invalid_immich_person_id'),
|
||||
})
|
||||
|
||||
// Connexion Immich d'un arbre : instance choisie parmi celles autorisées par l'opérateur du
|
||||
// serveur (IMMICH_ALLOWED_API_URLS), désignée par son identifiant opaque. L'adresse ne circule
|
||||
// jamais vers le front. La clé se joint à la mise à jour ou, si le champ reste vide, celle en
|
||||
// place est conservée — jamais relue par le front.
|
||||
const configPayloadSchema = z.object({
|
||||
instanceId: z.string().regex(/^[0-9a-f]{16}$/, 'invalid_instance_id'),
|
||||
apiKey: z.string().min(1).max(512).optional(),
|
||||
})
|
||||
|
||||
const MAX_THUMBNAIL_BYTES = 5 * 1024 * 1024
|
||||
|
||||
function replyImmichError(request: FastifyRequest, reply: FastifyReply, error: unknown): FastifyReply {
|
||||
if (error instanceof ImmichNotFoundError) {
|
||||
return reply.code(404).send({ error: 'immich_person_not_found' })
|
||||
}
|
||||
if (error instanceof ImmichAuthError) {
|
||||
return reply.code(502).send({ error: 'immich_auth_failed' })
|
||||
}
|
||||
if (error instanceof ImmichUnavailableError) {
|
||||
return reply.code(503).send({ error: 'immich_unreachable' })
|
||||
}
|
||||
request.log.error({ err: error }, 'Erreur inattendue pendant un appel à Immich')
|
||||
return reply.code(500).send({ error: 'immich_api_error' })
|
||||
}
|
||||
|
||||
// Métadonnées sûres d'une connexion Immich d'arbre : jamais la clé, jamais son chiffré, jamais
|
||||
// l'adresse (l'instance se nomme par son libellé). Une adresse sortie de la liste de l'opérateur
|
||||
// vaut « non configuré » : la connexion est inerte. Une clé qui ne se déchiffre plus (JWT_SECRET
|
||||
// changé) vaut aussi « non configuré », avec keyNeedsReentry : l'administrateur doit la ressaisir.
|
||||
function immichConfigSummary(config: { apiUrl: string; apiKeyEnc: string; updatedAt: Date } | null) {
|
||||
const instance = config ? getImmichInstanceByApiUrl(config.apiUrl) : undefined
|
||||
if (!config || !instance) {
|
||||
return { configured: false, keyNeedsReentry: false, instanceId: null, label: null, updatedAt: null }
|
||||
}
|
||||
const keyReadable = decryptImmichApiKey(config.apiKeyEnc) !== null
|
||||
return {
|
||||
configured: keyReadable,
|
||||
keyNeedsReentry: !keyReadable,
|
||||
instanceId: instance.id,
|
||||
label: instance.label,
|
||||
updatedAt: config.updatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
// Portraits venus d'Immich : même nommage que les envois manuels (« avatar-<uuid> »), 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}`)
|
||||
}
|
||||
|
||||
|
||||
async function membershipRole(app: FastifyInstance, userId: string, treeId: string) {
|
||||
const membership = await app.prisma.treeMembership.findUnique({
|
||||
where: { treeId_userId: { treeId, userId } },
|
||||
select: { role: true, tree: { select: { deletedAt: true } } },
|
||||
})
|
||||
return membership && !membership.tree.deletedAt ? membership.role : null
|
||||
}
|
||||
|
||||
// Immich passe par la clé du propriétaire, qui ouvre toute sa photothèque, pas seulement les photos de l'arbre :
|
||||
// réservé au propriétaire, jamais aux co-gestionnaires (issue #145)
|
||||
async function requireImmichOwner(app: FastifyInstance, userId: string, treeId: string): Promise<boolean> {
|
||||
return (await membershipRole(app, userId, treeId)) === 'owner'
|
||||
}
|
||||
|
||||
export const immichRoutes: FastifyPluginAsync = async (app) => {
|
||||
// Lecture réservée aux administrateurs : la clé donne accès à la photothèque de l'arbre.
|
||||
// Les fichiers sélectionnés passent ensuite par l'envoi de souvenirs habituel (quota,
|
||||
// validation et rattachement au moment), sans exposer d'URL ni de clé Immich au navigateur.
|
||||
app.get('/trees/:id/immich/assets', async (request, reply) => {
|
||||
if (request.actor?.kind !== 'user') return reply.code(401).send({ error: 'authentication_required' })
|
||||
const params = treeParamSchema.safeParse(request.params)
|
||||
const query = z.object({
|
||||
page: z.coerce.number().int().min(1).max(100000).default(1),
|
||||
type: z.enum(['IMAGE', 'VIDEO']).default('IMAGE'),
|
||||
q: z.string().trim().max(500).optional(),
|
||||
personId: z.string().refine(isImmichPersonId).optional(),
|
||||
}).safeParse(request.query)
|
||||
if (!params.success || !query.success) return reply.code(400).send({ error: 'invalid_params' })
|
||||
if (!(await requireImmichOwner(app, request.actor.userId, params.data.id))) return reply.code(403).send({ error: 'forbidden' })
|
||||
const client = await getTreeImmichClient(app.prisma, params.data.id)
|
||||
if (!client) return reply.code(503).send({ error: 'immich_not_configured' })
|
||||
try {
|
||||
reply.header('Cache-Control', 'no-store')
|
||||
return reply.send(await client.listAssets(query.data.page, query.data.type, { query: query.data.q, personId: query.data.personId }))
|
||||
} catch (error) { return replyImmichError(request, reply, error) }
|
||||
})
|
||||
|
||||
app.get('/trees/:id/immich/assets/:assetId/:variant', async (request, reply) => {
|
||||
if (request.actor?.kind !== 'user') return reply.code(401).send({ error: 'authentication_required' })
|
||||
const params = z.object({ id: z.string().min(1), assetId: z.string().refine(isImmichPersonId), variant: z.enum(['thumbnail', 'preview', 'original']) }).safeParse(request.params)
|
||||
if (!params.success) return reply.code(400).send({ error: 'invalid_params' })
|
||||
if (!(await requireImmichOwner(app, request.actor.userId, params.data.id))) return reply.code(403).send({ error: 'forbidden' })
|
||||
const client = await getTreeImmichClient(app.prisma, params.data.id)
|
||||
if (!client) return reply.code(503).send({ error: 'immich_not_configured' })
|
||||
try {
|
||||
const thumbnail = params.data.variant !== 'original'
|
||||
const bytes = await client.getAssetBytes(params.data.assetId, thumbnail, (thumbnail ? 5 : 20) * 1024 * 1024, params.data.variant === 'preview')
|
||||
if (!bytes) return reply.code(413).send({ error: 'immich_asset_too_large' })
|
||||
const mime = sniffMimeType(bytes, 'video')
|
||||
if (!mime || !(mime.startsWith('image/') || (!thumbnail && mime.startsWith('video/')))) return reply.code(400).send({ error: 'invalid_immich_media' })
|
||||
if (mime.startsWith('image/') && bytes.length > MAX_THUMBNAIL_BYTES) return reply.code(413).send({ error: 'immich_asset_too_large' })
|
||||
return reply.header('Content-Type', mime).header('X-Content-Type-Options', 'nosniff').header('Cache-Control', 'no-store').send(bytes)
|
||||
} catch (error) {
|
||||
if (error instanceof ImmichNotFoundError) return reply.code(404).send({ error: 'immich_asset_not_found' })
|
||||
return replyImmichError(request, reply, error)
|
||||
}
|
||||
})
|
||||
|
||||
// ── 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' })
|
||||
}
|
||||
|
||||
const role = await membershipRole(app, request.actor.userId, params.data.id)
|
||||
if (role !== 'owner' && role !== 'admin') {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
// Co-gestionnaire : la clé Immich est celle du propriétaire et ouvre toute sa photothèque. Il ne voit ni ne
|
||||
// règle rien ; pour l'interface, Immich n'est pas configuré
|
||||
if (role !== 'owner') {
|
||||
return reply.send({ config: null, instances: [], ownerOnly: true })
|
||||
}
|
||||
|
||||
const config = await app.prisma.treeImmichConfig.findUnique({
|
||||
where: { treeId: params.data.id },
|
||||
select: { apiUrl: true, apiKeyEnc: true, updatedAt: true },
|
||||
})
|
||||
|
||||
return reply.send({
|
||||
config: immichConfigSummary(config),
|
||||
// Les administrateurs choisissent parmi ces instances : le front en fait un menu, pas un champ libre.
|
||||
instances: getImmichInstances().map(({ id, label }) => ({ id, label })),
|
||||
})
|
||||
})
|
||||
|
||||
app.put('/trees/:id/immich/config', async (request, reply) => {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
}
|
||||
|
||||
const params = treeParamSchema.safeParse(request.params)
|
||||
const payload = configPayloadSchema.safeParse(request.body)
|
||||
if (!params.success) {
|
||||
return reply.code(400).send({ error: 'invalid_params' })
|
||||
}
|
||||
if (!payload.success) {
|
||||
return reply.code(400).send({ error: 'invalid_payload', details: payload.error.flatten() })
|
||||
}
|
||||
|
||||
if (!(await requireImmichOwner(app, request.actor.userId, params.data.id))) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
|
||||
// L'instance doit faire partie de la liste de l'opérateur : le serveur ne devient jamais
|
||||
// un proxy vers un service interne choisi librement (SSRF). L'adresse vient de la liste,
|
||||
// jamais de la requête.
|
||||
const instance = getImmichInstances().find((candidate) => candidate.id === payload.data.instanceId)
|
||||
if (!instance) {
|
||||
return reply.code(400).send({ error: 'instance_not_allowed' })
|
||||
}
|
||||
|
||||
const treeId = params.data.id
|
||||
const existing = await app.prisma.treeImmichConfig.findUnique({
|
||||
where: { treeId },
|
||||
select: { apiUrl: true, apiKeyEnc: true },
|
||||
})
|
||||
|
||||
// Sans nouvelle clé, la clé en place est conservée — mais il en faut une pour une
|
||||
// première configuration, et quand celle en place ne se déchiffre plus : on ne devine
|
||||
// jamais d'identifiants ailleurs.
|
||||
if (!payload.data.apiKey && (!existing || !decryptImmichApiKey(existing.apiKeyEnc))) {
|
||||
return reply.code(400).send({ error: 'api_key_required' })
|
||||
}
|
||||
|
||||
// Changer d'instance n'emmène jamais la clé de l'ancienne : elle ne vaut rien pour la
|
||||
// nouvelle, et on ne l'envoie pas à un serveur qui n'est pas le sien.
|
||||
if (existing && !payload.data.apiKey
|
||||
&& normalizeImmichApiUrl(existing.apiUrl) !== instance.apiUrl) {
|
||||
return reply.code(400).send({ error: 'api_key_required' })
|
||||
}
|
||||
|
||||
const apiKeyEnc = payload.data.apiKey
|
||||
? encryptImmichApiKey(payload.data.apiKey)
|
||||
: existing!.apiKeyEnc
|
||||
|
||||
const config = await app.prisma.treeImmichConfig.upsert({
|
||||
where: { treeId },
|
||||
create: { treeId, apiUrl: instance.apiUrl, apiKeyEnc },
|
||||
update: { apiUrl: instance.apiUrl, apiKeyEnc },
|
||||
select: { apiUrl: true, apiKeyEnc: true, updatedAt: true },
|
||||
})
|
||||
|
||||
// Journal d'audit : jamais la clé, seulement le fait qu'elle a changé.
|
||||
await app.prisma.auditLog.create({
|
||||
data: {
|
||||
treeId,
|
||||
actorType: 'user',
|
||||
actorId: request.actor.userId,
|
||||
action: 'immich_config_updated',
|
||||
entityType: 'tree_immich_config',
|
||||
entityId: treeId,
|
||||
payloadJson: { instanceId: instance.id, apiKeyChanged: Boolean(payload.data.apiKey) },
|
||||
},
|
||||
})
|
||||
|
||||
return reply.send({ config: immichConfigSummary(config) })
|
||||
})
|
||||
|
||||
app.delete('/trees/:id/immich/config', async (request, reply) => {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
}
|
||||
|
||||
const params = treeParamSchema.safeParse(request.params)
|
||||
if (!params.success) {
|
||||
return reply.code(400).send({ error: 'invalid_params' })
|
||||
}
|
||||
|
||||
if (!(await requireImmichOwner(app, request.actor.userId, params.data.id))) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
|
||||
const treeId = params.data.id
|
||||
const removed = await app.prisma.treeImmichConfig.deleteMany({ where: { treeId } })
|
||||
|
||||
if (removed.count > 0) {
|
||||
await app.prisma.auditLog.create({
|
||||
data: {
|
||||
treeId,
|
||||
actorType: 'user',
|
||||
actorId: request.actor.userId,
|
||||
action: 'immich_config_removed',
|
||||
entityType: 'tree_immich_config',
|
||||
entityId: treeId,
|
||||
payloadJson: {},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return reply.send({ config: { configured: false, keyNeedsReentry: false, instanceId: null, label: null, updatedAt: null } })
|
||||
})
|
||||
|
||||
app.get('/trees/:id/immich/status', async (request, reply) => {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
}
|
||||
|
||||
const params = treeParamSchema.safeParse(request.params)
|
||||
if (!params.success) {
|
||||
return reply.code(400).send({ error: 'invalid_params' })
|
||||
}
|
||||
|
||||
if (!(await requireImmichOwner(app, request.actor.userId, params.data.id))) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
|
||||
const client = await getTreeImmichClient(app.prisma, params.data.id)
|
||||
if (!client) {
|
||||
return reply.send({ available: false, reason: 'not_configured' })
|
||||
}
|
||||
|
||||
const available = await client.ping()
|
||||
return reply.send({ available, reason: available ? null : 'unreachable' })
|
||||
})
|
||||
|
||||
app.get('/trees/:id/immich/people', async (request, reply) => {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
}
|
||||
|
||||
const params = treeParamSchema.safeParse(request.params)
|
||||
if (!params.success) {
|
||||
return reply.code(400).send({ error: 'invalid_params' })
|
||||
}
|
||||
|
||||
if (!(await requireImmichOwner(app, request.actor.userId, params.data.id))) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
|
||||
const client = await getTreeImmichClient(app.prisma, params.data.id)
|
||||
if (!client) {
|
||||
return reply.code(503).send({ error: 'immich_not_configured' })
|
||||
}
|
||||
|
||||
try {
|
||||
const people = await client.listPeople()
|
||||
return reply.send({ people })
|
||||
} catch (error) {
|
||||
return replyImmichError(request, reply, error)
|
||||
}
|
||||
})
|
||||
|
||||
// Vignette d'une personne Immich, montrée dans le sélecteur. Passée par l'API : l'adresse
|
||||
// d'Immich et sa clé ne quittent jamais le serveur.
|
||||
app.get('/trees/:id/immich/thumbnail/:immichPersonId', async (request, reply) => {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
}
|
||||
|
||||
const params = thumbnailParamSchema.safeParse(request.params)
|
||||
if (!params.success) {
|
||||
return reply.code(400).send({ error: 'invalid_immich_person_id' })
|
||||
}
|
||||
|
||||
if (!(await requireImmichOwner(app, request.actor.userId, params.data.id))) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
|
||||
const client = await getTreeImmichClient(app.prisma, params.data.id)
|
||||
if (!client) {
|
||||
return reply.code(503).send({ error: 'immich_not_configured' })
|
||||
}
|
||||
|
||||
let thumbnail: Buffer | null
|
||||
try {
|
||||
thumbnail = await client.getPersonThumbnail(params.data.immichPersonId, MAX_THUMBNAIL_BYTES)
|
||||
} catch (error) {
|
||||
return replyImmichError(request, reply, error)
|
||||
}
|
||||
|
||||
// Le type se lit dans les octets, pas dans ce qu'Immich déclare : la vignette finit dans une
|
||||
// balise <img>. Vide, trop grande ou pas une image : rien à montrer.
|
||||
const mimeType = thumbnail?.length ? sniffMimeType(thumbnail, 'photo') : null
|
||||
if (!thumbnail || !mimeType || !(IMAGE_MIME_TYPES as readonly string[]).includes(mimeType)) {
|
||||
request.log.warn('Vignette Immich vide, trop grande ou qui n’est pas une image')
|
||||
return reply.code(404).send({ error: 'thumbnail_not_found' })
|
||||
}
|
||||
|
||||
reply.header('Content-Type', mimeType)
|
||||
reply.header('X-Content-Type-Options', 'nosniff')
|
||||
reply.header('Cache-Control', 'private, max-age=3600')
|
||||
return reply.send(thumbnail)
|
||||
})
|
||||
|
||||
// Personne Immich déjà associée à une fiche, pour la marquer dans le sélecteur. Réservé aux
|
||||
// administrateurs : l'identifiant n'entre jamais dans le graphe public.
|
||||
app.get('/trees/:id/immich/links/:personId', async (request, reply) => {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
}
|
||||
|
||||
const params = treePersonParamsSchema.safeParse(request.params)
|
||||
if (!params.success) {
|
||||
return reply.code(400).send({ error: 'invalid_params' })
|
||||
}
|
||||
|
||||
if (!(await requireImmichOwner(app, request.actor.userId, params.data.id))) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
|
||||
const person = await app.prisma.person.findFirst({
|
||||
where: { id: params.data.personId, treeId: params.data.id, deletedAt: null },
|
||||
select: { immichPersonId: true },
|
||||
})
|
||||
if (!person) {
|
||||
return reply.code(404).send({ error: 'person_not_found' })
|
||||
}
|
||||
|
||||
return reply.send({ immichPersonId: person.immichPersonId })
|
||||
})
|
||||
|
||||
app.post('/trees/:id/immich/assign', async (request, reply) => {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
}
|
||||
|
||||
const params = treeParamSchema.safeParse(request.params)
|
||||
const payload = assignSchema.safeParse(request.body)
|
||||
if (!params.success || !payload.success) {
|
||||
return reply.code(400).send({ error: payload.success ? 'invalid_params' : 'invalid_immich_person_id' })
|
||||
}
|
||||
|
||||
if (!(await requireImmichOwner(app, request.actor.userId, params.data.id))) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
|
||||
const client = await getTreeImmichClient(app.prisma, params.data.id)
|
||||
if (!client) {
|
||||
return reply.code(503).send({ error: 'immich_not_configured' })
|
||||
}
|
||||
|
||||
const { personId, immichPersonId } = payload.data
|
||||
const treeId = params.data.id
|
||||
|
||||
const person = await app.prisma.person.findFirst({
|
||||
where: { id: personId, treeId, deletedAt: null },
|
||||
select: { id: true, avatarPath: true },
|
||||
})
|
||||
if (!person) {
|
||||
return reply.code(404).send({ error: 'person_not_found' })
|
||||
}
|
||||
|
||||
// La personne Immich doit exister : le 404 de la vignette ne le prouve pas (personne
|
||||
// absente ou simple vignette manquante), on la vérifie donc explicitement. Un refus
|
||||
// d'authentification ou une erreur serveur ne sont jamais pris pour une absence.
|
||||
let immichPerson: ImmichPersonSummary
|
||||
try {
|
||||
immichPerson = await client.getPerson(immichPersonId)
|
||||
} catch (error) {
|
||||
return replyImmichError(request, reply, error)
|
||||
}
|
||||
|
||||
// Vignette de la personne Immich : absente -> on associe sans toucher au portrait existant.
|
||||
// Demandée seulement si Immich en annonce une : sans vignette, l'appel est inutile.
|
||||
let thumbnail: Buffer | null = null
|
||||
if (immichPerson.hasThumbnail) {
|
||||
try {
|
||||
thumbnail = await client.getPersonThumbnail(immichPersonId, MAX_THUMBNAIL_BYTES)
|
||||
} catch (error) {
|
||||
if (!(error instanceof ImmichNotFoundError)) {
|
||||
return replyImmichError(request, reply, error)
|
||||
}
|
||||
// Vignette absente : l'association se fait sans portrait.
|
||||
}
|
||||
}
|
||||
|
||||
if (!thumbnail) {
|
||||
await app.prisma.$transaction([
|
||||
app.prisma.person.update({
|
||||
where: { id: personId },
|
||||
data: { immichPersonId, updatedBy: request.actor.userId },
|
||||
}),
|
||||
app.prisma.auditLog.create({
|
||||
data: {
|
||||
treeId,
|
||||
actorType: 'user',
|
||||
actorId: request.actor.userId,
|
||||
action: 'immich_assign',
|
||||
entityType: 'person',
|
||||
entityId: personId,
|
||||
payloadJson: { immichPersonId, avatarUpdated: false },
|
||||
},
|
||||
}),
|
||||
])
|
||||
|
||||
return reply.send({ ok: true, avatarUpdated: false, immichPersonId })
|
||||
}
|
||||
|
||||
// Un portrait déjà en place ne se remplace jamais en silence : sans accord explicite,
|
||||
// l'association s'arrête avant d'écrire quoi que ce soit. Le front transforme ce refus
|
||||
// en demande de confirmation puis rejoue la requête avec replaceAvatar.
|
||||
if (person.avatarPath && !payload.data.replaceAvatar) {
|
||||
return reply.code(409).send({ error: 'avatar_exists' })
|
||||
}
|
||||
|
||||
// La vignette passe par le même traitement qu'un portrait envoyé : type lu dans les octets,
|
||||
// métadonnées retirées, quota de l'arbre respecté.
|
||||
let prepared: Awaited<ReturnType<typeof prepareUploadedFile>>
|
||||
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,
|
||||
// Nouveau portrait, nouveau cadrage à faire
|
||||
avatarCrop: Prisma.DbNull,
|
||||
avatarBlurhash: await computeBlurhash(prepared.buffer) ?? '',
|
||||
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 requireImmichOwner(app, request.actor.userId, params.data.id))) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
|
||||
// Pas de garde « non configuré » ici : le retrait d'association ne parle jamais à Immich,
|
||||
// et c'est le seul moyen de nettoyer des associations passées après une déconnexion.
|
||||
const { personId } = payload.data
|
||||
const treeId = params.data.id
|
||||
|
||||
const person = await app.prisma.person.findFirst({
|
||||
where: { id: personId, treeId, deletedAt: null },
|
||||
select: { id: true, avatarPath: true, immichPersonId: true },
|
||||
})
|
||||
if (!person) {
|
||||
return reply.code(404).send({ error: 'person_not_found' })
|
||||
}
|
||||
|
||||
// Le graphe ne dit plus qui est associé : le retrait se propose toujours côté front. Sans
|
||||
// association en place, il ne fait rien — pas d'écriture, pas d'entrée d'audit.
|
||||
if (!person.immichPersonId) {
|
||||
return reply.send({ ok: true, avatarRemoved: false })
|
||||
}
|
||||
|
||||
// Le portrait vient d'Immich uniquement si son fichier porte notre préfixe. Un portrait
|
||||
// envoyé à la main reste en place : seule l'association est retirée.
|
||||
const avatarFromImmich = isImmichAvatarPath(person.avatarPath)
|
||||
|
||||
const updateData: {
|
||||
immichPersonId: null
|
||||
updatedBy: string
|
||||
avatarPath?: null
|
||||
avatarMimeType?: null
|
||||
avatarCrop?: typeof Prisma.DbNull
|
||||
avatarBlurhash?: null
|
||||
} = { immichPersonId: null, updatedBy: request.actor.userId }
|
||||
if (avatarFromImmich) {
|
||||
updateData.avatarPath = null
|
||||
updateData.avatarMimeType = null
|
||||
updateData.avatarCrop = Prisma.DbNull
|
||||
updateData.avatarBlurhash = 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 })
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,241 @@
|
||||
import type { FastifyInstance, FastifyPluginAsync, FastifyReply, FastifyRequest } from 'fastify'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { env } from '../config/env.js'
|
||||
import { isOidcEnabled } from '../lib/oidc.js'
|
||||
import {
|
||||
INVITATION_TTL_MS,
|
||||
MAX_PENDING_INVITATIONS,
|
||||
acceptInvitation,
|
||||
findPendingInvitationByToken,
|
||||
hashInvitationToken,
|
||||
maskEmail,
|
||||
newInvitationToken,
|
||||
normalizeEmail,
|
||||
pendingInvitationWhere,
|
||||
} from '../lib/tree-invitations.js'
|
||||
|
||||
// Co-gestion d'un arbre (issue #145). Un co-gestionnaire est un membre « admin » : il fait tout ce que fait le
|
||||
// propriétaire, sauf inviter ou retirer un co-gestionnaire et supprimer l'arbre (DELETE /trees/:id, réservé au
|
||||
// propriétaire), ni Immich, qui passe par la clé du propriétaire (routes/immich.ts). Les droits sont relus en base à
|
||||
// chaque requête : un co-gestionnaire retiré perd la main aussitôt. Il a pu voir le mot de passe de partage :
|
||||
// l'écran de retrait propose de le changer.
|
||||
|
||||
const treeIdParamSchema = z.object({ id: z.string().min(1) })
|
||||
const invitationParamsSchema = z.object({ id: z.string().min(1), invitationId: z.string().min(1) })
|
||||
const managerParamsSchema = z.object({ id: z.string().min(1), userId: z.string().min(1) })
|
||||
const tokenParamSchema = z.object({ token: z.string().min(1).max(200) })
|
||||
const inviteSchema = z.object({ email: z.string().trim().email().max(254) })
|
||||
|
||||
function requireUser(request: FastifyRequest, reply: FastifyReply): { userId: string } | null {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
reply.code(401).send({ error: 'authentication_required' })
|
||||
return null
|
||||
}
|
||||
return { userId: request.actor.userId }
|
||||
}
|
||||
|
||||
async function membershipOf(app: FastifyInstance, treeId: string, userId: string) {
|
||||
const membership = await app.prisma.treeMembership.findUnique({
|
||||
where: { treeId_userId: { treeId, userId } },
|
||||
select: { role: true, tree: { select: { deletedAt: true, ownerUserId: true } } },
|
||||
})
|
||||
return membership && !membership.tree.deletedAt ? membership : null
|
||||
}
|
||||
|
||||
function audit(app: FastifyInstance, treeId: string, actorId: string, action: string, payloadJson: Record<string, string>) {
|
||||
return app.prisma.auditLog.create({
|
||||
data: { treeId, actorType: 'user', actorId, action, entityType: 'tree', entityId: treeId, payloadJson },
|
||||
})
|
||||
}
|
||||
|
||||
export const managerRoutes: FastifyPluginAsync = async (app) => {
|
||||
// Gestionnaires et invitations en attente, pour tout gestionnaire de l'arbre. canManage : le propriétaire.
|
||||
app.get('/trees/:id/managers', async (request, reply) => {
|
||||
const user = requireUser(request, reply)
|
||||
if (!user) return
|
||||
const params = treeIdParamSchema.safeParse(request.params)
|
||||
if (!params.success) return reply.code(400).send({ error: 'invalid_tree_id' })
|
||||
|
||||
const membership = await membershipOf(app, params.data.id, user.userId)
|
||||
if (!membership || (membership.role !== 'owner' && membership.role !== 'admin')) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
|
||||
const [managers, invitations] = await Promise.all([
|
||||
app.prisma.treeMembership.findMany({
|
||||
where: { treeId: params.data.id, role: { in: ['owner', 'admin'] } },
|
||||
select: { role: true, createdAt: true, user: { select: { id: true, email: true, firstName: true } } },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
}),
|
||||
app.prisma.treeInvitation.findMany({
|
||||
where: { treeId: params.data.id, ...pendingInvitationWhere() },
|
||||
select: { id: true, email: true, createdAt: true, expiresAt: true },
|
||||
orderBy: { createdAt: 'asc' },
|
||||
}),
|
||||
])
|
||||
|
||||
return reply.send({
|
||||
canManage: membership.role === 'owner',
|
||||
managers: managers.map((m) => ({ userId: m.user.id, email: m.user.email, firstName: m.user.firstName, role: m.role, since: m.createdAt })),
|
||||
invitations,
|
||||
})
|
||||
})
|
||||
|
||||
// Inviter une adresse. Une invitation déjà en attente pour cette adresse reçoit un nouveau lien (l'ancien ne
|
||||
// sert plus). Le jeton n'est rendu qu'ici et par /link : la base n'en garde que l'empreinte.
|
||||
app.post('/trees/:id/invitations', { config: { rateLimit: { max: 20, timeWindow: '10 minutes' } } }, async (request, reply) => {
|
||||
const user = requireUser(request, reply)
|
||||
if (!user) return
|
||||
const params = treeIdParamSchema.safeParse(request.params)
|
||||
if (!params.success) return reply.code(400).send({ error: 'invalid_tree_id' })
|
||||
const payload = inviteSchema.safeParse(request.body)
|
||||
if (!payload.success) return reply.code(400).send({ error: 'invalid_email' })
|
||||
|
||||
const membership = await membershipOf(app, params.data.id, user.userId)
|
||||
if (!membership || membership.role !== 'owner') return reply.code(403).send({ error: 'forbidden' })
|
||||
|
||||
const email = normalizeEmail(payload.data.email)
|
||||
const alreadyManager = await app.prisma.treeMembership.findFirst({
|
||||
where: { treeId: params.data.id, role: { in: ['owner', 'admin'] }, user: { email } },
|
||||
select: { id: true },
|
||||
})
|
||||
if (alreadyManager) return reply.code(409).send({ error: 'already_manager' })
|
||||
|
||||
const { token, tokenHash } = newInvitationToken()
|
||||
const expiresAt = new Date(Date.now() + INVITATION_TTL_MS)
|
||||
const existing = await app.prisma.treeInvitation.findFirst({
|
||||
where: { treeId: params.data.id, email, ...pendingInvitationWhere() },
|
||||
select: { id: true },
|
||||
})
|
||||
let invitation
|
||||
if (existing) {
|
||||
invitation = await app.prisma.treeInvitation.update({
|
||||
where: { id: existing.id },
|
||||
data: { tokenHash, expiresAt },
|
||||
select: { id: true, email: true, createdAt: true, expiresAt: true },
|
||||
})
|
||||
} else {
|
||||
const pending = await app.prisma.treeInvitation.count({ where: { treeId: params.data.id, ...pendingInvitationWhere() } })
|
||||
if (pending >= MAX_PENDING_INVITATIONS) return reply.code(429).send({ error: 'too_many_invitations' })
|
||||
invitation = await app.prisma.treeInvitation.create({
|
||||
data: { treeId: params.data.id, email, tokenHash, expiresAt, invitedByUserId: user.userId },
|
||||
select: { id: true, email: true, createdAt: true, expiresAt: true },
|
||||
})
|
||||
}
|
||||
await audit(app, params.data.id, user.userId, 'manager_invited', { invitationId: invitation.id })
|
||||
return reply.code(201).send({ invitation, token })
|
||||
})
|
||||
|
||||
// « Copier le lien » : un nouveau jeton (l'ancien lien ne sert plus), la durée repart de zéro
|
||||
app.post('/trees/:id/invitations/:invitationId/link', { config: { rateLimit: { max: 30, timeWindow: '10 minutes' } } }, async (request, reply) => {
|
||||
const user = requireUser(request, reply)
|
||||
if (!user) return
|
||||
const params = invitationParamsSchema.safeParse(request.params)
|
||||
if (!params.success) return reply.code(400).send({ error: 'invalid_params' })
|
||||
|
||||
const membership = await membershipOf(app, params.data.id, user.userId)
|
||||
if (!membership || membership.role !== 'owner') return reply.code(403).send({ error: 'forbidden' })
|
||||
|
||||
const { token, tokenHash } = newInvitationToken()
|
||||
const updated = await app.prisma.treeInvitation.updateMany({
|
||||
where: { id: params.data.invitationId, treeId: params.data.id, ...pendingInvitationWhere() },
|
||||
data: { tokenHash, expiresAt: new Date(Date.now() + INVITATION_TTL_MS) },
|
||||
})
|
||||
if (updated.count !== 1) return reply.code(404).send({ error: 'invitation_not_found' })
|
||||
return reply.send({ token })
|
||||
})
|
||||
|
||||
app.delete('/trees/:id/invitations/:invitationId', async (request, reply) => {
|
||||
const user = requireUser(request, reply)
|
||||
if (!user) return
|
||||
const params = invitationParamsSchema.safeParse(request.params)
|
||||
if (!params.success) return reply.code(400).send({ error: 'invalid_params' })
|
||||
|
||||
const membership = await membershipOf(app, params.data.id, user.userId)
|
||||
if (!membership || membership.role !== 'owner') return reply.code(403).send({ error: 'forbidden' })
|
||||
|
||||
const revoked = await app.prisma.treeInvitation.updateMany({
|
||||
where: { id: params.data.invitationId, treeId: params.data.id, ...pendingInvitationWhere() },
|
||||
data: { revokedAt: new Date() },
|
||||
})
|
||||
if (revoked.count !== 1) return reply.code(404).send({ error: 'invitation_not_found' })
|
||||
await audit(app, params.data.id, user.userId, 'manager_invitation_revoked', { invitationId: params.data.invitationId })
|
||||
return reply.send({ ok: true })
|
||||
})
|
||||
|
||||
// Retirer un co-gestionnaire (le propriétaire), ou quitter la gestion (le co-gestionnaire lui-même).
|
||||
// Le propriétaire ne se retire jamais : son arbre part avec lui (suppression de l'arbre ou du compte).
|
||||
app.delete('/trees/:id/managers/:userId', async (request, reply) => {
|
||||
const user = requireUser(request, reply)
|
||||
if (!user) return
|
||||
const params = managerParamsSchema.safeParse(request.params)
|
||||
if (!params.success) return reply.code(400).send({ error: 'invalid_params' })
|
||||
|
||||
const membership = await membershipOf(app, params.data.id, user.userId)
|
||||
const leaving = params.data.userId === user.userId
|
||||
if (!membership || (leaving ? membership.role !== 'admin' : membership.role !== 'owner')) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
|
||||
// Un accès retenu par le mot de passe de partage (user_tree_accesses) part aussi : sinon le compte retiré
|
||||
// lirait encore l'arbre
|
||||
const removed = await app.prisma.$transaction(async (tx) => {
|
||||
const deleted = await tx.treeMembership.deleteMany({
|
||||
where: { treeId: params.data.id, userId: params.data.userId, role: 'admin' },
|
||||
})
|
||||
if (deleted.count === 1) {
|
||||
await tx.userTreeAccess.deleteMany({ where: { treeId: params.data.id, userId: params.data.userId } })
|
||||
}
|
||||
return deleted
|
||||
})
|
||||
if (removed.count !== 1) return reply.code(404).send({ error: 'manager_not_found' })
|
||||
await audit(app, params.data.id, user.userId, leaving ? 'manager_left' : 'manager_removed', { userId: params.data.userId })
|
||||
return reply.send({ ok: true })
|
||||
})
|
||||
|
||||
// Page du lien, sans compte : l'arbre, qui invite, l'adresse masquée, et les façons d'entrer sur ce serveur
|
||||
app.get('/invitations/:token', { config: { rateLimit: { max: 30, timeWindow: '1 minute' } } }, async (request, reply) => {
|
||||
const params = tokenParamSchema.safeParse(request.params)
|
||||
if (!params.success) return reply.code(404).send({ error: 'invitation_invalid' })
|
||||
const invitation = await findPendingInvitationByToken(app.prisma, params.data.token)
|
||||
if (!invitation) {
|
||||
// Lien déjà servi ou expiré : dit tel quel, pour que la page explique quoi faire. Rien d'autre ne sort.
|
||||
const known = await app.prisma.treeInvitation.findUnique({
|
||||
where: { tokenHash: hashInvitationToken(params.data.token) },
|
||||
select: { acceptedAt: true, revokedAt: true, expiresAt: true },
|
||||
})
|
||||
const error = known?.acceptedAt ? 'invitation_used' : known && !known.revokedAt && known.expiresAt <= new Date() ? 'invitation_expired' : 'invitation_invalid'
|
||||
return reply.code(404).send({ error })
|
||||
}
|
||||
return reply.send({
|
||||
treeName: invitation.tree.name,
|
||||
treeIcon: invitation.tree.icon,
|
||||
invitedBy: invitation.tree.owner.firstName || null,
|
||||
emailHint: maskEmail(invitation.email),
|
||||
expiresAt: invitation.expiresAt,
|
||||
passwordLogin: env.PASSWORD_LOGIN,
|
||||
oidc: isOidcEnabled() ? { name: env.OIDC_PROVIDER_NAME } : null,
|
||||
})
|
||||
})
|
||||
|
||||
// Accepter avec le compte connecté : il doit avoir l'adresse invitée
|
||||
app.post('/invitations/:token/accept', { config: { rateLimit: { max: 10, timeWindow: '1 minute' } } }, async (request, reply) => {
|
||||
const user = requireUser(request, reply)
|
||||
if (!user) return
|
||||
const params = tokenParamSchema.safeParse(request.params)
|
||||
if (!params.success) return reply.code(404).send({ error: 'invitation_invalid' })
|
||||
|
||||
const invitation = await findPendingInvitationByToken(app.prisma, params.data.token)
|
||||
if (!invitation) return reply.code(404).send({ error: 'invitation_invalid' })
|
||||
const account = await app.prisma.user.findUnique({ where: { id: user.userId }, select: { email: true } })
|
||||
if (!account) return reply.code(401).send({ error: 'authentication_required' })
|
||||
|
||||
const result = await acceptInvitation(app.prisma, invitation.id, user.userId, account.email)
|
||||
if (!result.ok) {
|
||||
const code = result.error === 'invitation_invalid' ? 404 : result.error === 'already_owner' ? 409 : 403
|
||||
return reply.code(code).send({ error: result.error })
|
||||
}
|
||||
return reply.send({ treeId: result.treeId, role: 'admin' })
|
||||
})
|
||||
}
|
||||
+319
-34
@@ -2,6 +2,7 @@ import { randomUUID } from 'node:crypto'
|
||||
import { mkdir, readdir, readFile, stat, writeFile } from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
|
||||
import { Prisma } from '../generated/prisma/client.js'
|
||||
import type { FastifyPluginAsync, FastifyRequest } from 'fastify'
|
||||
import { z } from 'zod'
|
||||
|
||||
@@ -10,18 +11,24 @@ import {
|
||||
applyMediaResponseHeaders,
|
||||
extensionForMime,
|
||||
InvalidMediaError,
|
||||
isImmichAvatarPath,
|
||||
isMimeAllowedForType,
|
||||
removeStoredFile,
|
||||
sanitizeImage,
|
||||
scrubMp4Location,
|
||||
sendFileWithRanges,
|
||||
sniffMimeType,
|
||||
storedFileSize,
|
||||
type BinaryMediaType,
|
||||
} from '../lib/media-files.js'
|
||||
import { avatarCropInputSchema, readAvatarCrop, toStoredAvatarCrop } from '../lib/avatar-crop.js'
|
||||
import { computeBlurhash } from '../lib/blurhash.js'
|
||||
import { syncPersonMediaOrder } from '../lib/media-order.js'
|
||||
import { resolveTreeMediaDirectory } from '../lib/tree-purge.js'
|
||||
import { canReadTree, canReadTreeWithMediaToken } from '../lib/tree-access.js'
|
||||
import type { MembershipRole } from '../types/auth.js'
|
||||
import { ContributionRouteError, resolveSubmissionContext } from './contributions.js'
|
||||
import { forgetPendingPhoto, reservePendingPhoto, sweepStalePendingPhotos } from '../lib/annotation-changes.js'
|
||||
|
||||
const MAX_IMAGE_BYTES = 5 * 1024 * 1024
|
||||
const MAX_FILE_BYTES = 20 * 1024 * 1024
|
||||
@@ -48,6 +55,8 @@ const downloadQuerySchema = z.object({
|
||||
|
||||
const uploadBinaryMediaSchema = z.object({
|
||||
submittedByLabel: z.string().trim().min(1).max(120).optional(),
|
||||
// Moment de l'onglet Vie auquel rattacher ce souvenir
|
||||
lifeEventId: z.string().min(1).max(64).optional(),
|
||||
type: z.enum(['photo', 'video', 'audio', 'document', 'geojson', 'gpx']),
|
||||
fileName: z.string().min(1).max(255),
|
||||
mimeType: z.string().min(1).max(120),
|
||||
@@ -59,6 +68,8 @@ const uploadBinaryMediaSchema = z.object({
|
||||
|
||||
const uploadCitationMediaSchema = z.object({
|
||||
submittedByLabel: z.string().trim().min(1).max(120).optional(),
|
||||
// Moment de l'onglet Vie auquel rattacher ce souvenir
|
||||
lifeEventId: z.string().min(1).max(64).optional(),
|
||||
type: z.literal('citation'),
|
||||
caption: z.string().trim().min(1).max(2000),
|
||||
source: mediaSourceSchema,
|
||||
@@ -68,6 +79,8 @@ const YOUTUBE_URL_RE = /^https:\/\/(www\.)?(youtube\.com|youtu\.be)\//
|
||||
|
||||
const uploadYoutubeVideoSchema = z.object({
|
||||
submittedByLabel: z.string().trim().min(1).max(120).optional(),
|
||||
// Moment de l'onglet Vie auquel rattacher ce souvenir
|
||||
lifeEventId: z.string().min(1).max(64).optional(),
|
||||
type: z.literal('video'),
|
||||
mimeType: z.literal('video/youtube'),
|
||||
youtubeUrl: z.string().max(500).regex(YOUTUBE_URL_RE),
|
||||
@@ -88,11 +101,19 @@ const reorderMediaSchema = z.object({
|
||||
orderedMediaIds: z.array(z.string().min(1)).min(1),
|
||||
})
|
||||
|
||||
const MAX_CAPTION_LENGTH = 280
|
||||
const MAX_CITATION_LENGTH = 2000
|
||||
const updateMediaSchema = z.object({
|
||||
caption: z.string().trim().min(1).max(MAX_CITATION_LENGTH),
|
||||
lifeEventId: z.string().min(1).max(64).nullable().optional(),
|
||||
})
|
||||
|
||||
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 +137,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 +188,7 @@ async function treeDiskUsage(treeId: string): Promise<number> {
|
||||
}
|
||||
|
||||
// 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<boolean> {
|
||||
export async function exceedsStorageQuota(app: FastifyRequest['server'], treeId: string, incomingBytes: number, isPending: boolean): Promise<boolean> {
|
||||
const MB = 1024 * 1024
|
||||
if ((await treeDiskUsage(treeId)) + incomingBytes > env.MEDIA_QUOTA_PER_TREE_MB * MB) {
|
||||
return true
|
||||
@@ -186,8 +207,11 @@ 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' } } }
|
||||
// Portraits : réservés au propriétaire, mais l'app peut en placer quelques centaines d'un coup (photos
|
||||
// retrouvées après un import GEDCOM), envoyées une par une. Le quota de stockage de l'arbre s'applique.
|
||||
const AVATAR_RATE_LIMIT = { bodyLimit: UPLOAD_BODY_LIMIT, config: { rateLimit: { max: 120, timeWindow: '1 minute' } } }
|
||||
|
||||
async function requireAdminMembership(app: FastifyRequest['server'], userId: string, treeId: string) {
|
||||
export async function requireAdminMembership(app: FastifyRequest['server'], userId: string, treeId: string) {
|
||||
const membership = await app.prisma.treeMembership.findUnique({
|
||||
where: {
|
||||
treeId_userId: {
|
||||
@@ -220,6 +244,18 @@ async function canReadMedia(app: FastifyRequest['server'], treeId: string, reque
|
||||
return token ? canReadTreeWithMediaToken(app, treeId, token) : false
|
||||
}
|
||||
|
||||
// Compte qui demande un média : celui de la session, sinon celui du jeton médias (lien de partage : aucun)
|
||||
async function mediaRequesterUserId(app: FastifyRequest['server'], request: FastifyRequest, token: string | undefined): Promise<string | null> {
|
||||
if (request.actor?.kind === 'user') return request.actor.userId
|
||||
if (!token) return null
|
||||
try {
|
||||
const payload = await app.jwt.verify<{ kind?: string; userId?: string }>(token)
|
||||
return payload.kind === 'media' && payload.userId ? payload.userId : null
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.post('/trees/:id/persons/:personId/media', UPLOAD_RATE_LIMIT, async (request, reply) => {
|
||||
const actor = request.actor
|
||||
@@ -263,6 +299,7 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
select: {
|
||||
id: true,
|
||||
firstName: true,
|
||||
lastName: true,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -270,6 +307,33 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
return reply.code(404).send({ error: 'person_not_found' })
|
||||
}
|
||||
|
||||
// Rattachement à un moment : un moment de cette personne (ou de son union). La famille ne rattache qu'à
|
||||
// un moment qu'elle vient de proposer, encore en attente ; l'administrateur, à un moment visible.
|
||||
const lifeEventId = payload.data.lifeEventId ?? null
|
||||
let momentSessionId: string | null = null
|
||||
if (lifeEventId) {
|
||||
const event = await app.prisma.lifeEvent.findFirst({
|
||||
where: { id: lifeEventId, treeId: params.data.id, deletedAt: null },
|
||||
select: { personId: true, unionId: true, status: true, contributionSessionId: true },
|
||||
})
|
||||
let ownsEvent = event?.personId === person.id
|
||||
if (event && !ownsEvent && event.unionId) {
|
||||
const union = await app.prisma.union.findFirst({ where: { id: event.unionId, treeId: params.data.id }, select: { partner1PersonId: true, partner2PersonId: true } })
|
||||
ownsEvent = union?.partner1PersonId === person.id || union?.partner2PersonId === person.id
|
||||
}
|
||||
const statusOk = contribution ? event?.status === 'pending' : event?.status === 'approved'
|
||||
if (!event || !ownsEvent || !statusOk) {
|
||||
return reply.code(400).send({ error: 'invalid_life_event_reference' })
|
||||
}
|
||||
if (contribution && event.contributionSessionId) {
|
||||
const session = await app.prisma.contributionSession.findFirst({
|
||||
where: { id: event.contributionSessionId, treeId: params.data.id, status: 'pending' },
|
||||
select: { id: true },
|
||||
})
|
||||
momentSessionId = session?.id ?? null
|
||||
}
|
||||
}
|
||||
|
||||
// Fichier reconnu, nettoyé et compté AVANT toute écriture : un envoi refusé ne laisse ni contribution
|
||||
// vide en attente ni fichier sur le disque
|
||||
let prepared: { buffer: Buffer; mimeType: string; extension: string } | null = null
|
||||
@@ -314,7 +378,10 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
|
||||
// Une contribution d'une ligne, créée avant le média pour qu'il la référence
|
||||
const now = new Date()
|
||||
const contributionSession = contribution
|
||||
// Fichier d'un moment proposé : il rejoint la relecture du moment au lieu d'en ouvrir une autre
|
||||
const contributionSession = contribution && momentSessionId
|
||||
? { id: momentSessionId }
|
||||
: contribution
|
||||
? await app.prisma.contributionSession.create({
|
||||
data: {
|
||||
treeId: params.data.id,
|
||||
@@ -322,7 +389,7 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
submittedByLabel: payload.data.submittedByLabel?.trim() || contribution.submittedByLabel,
|
||||
mode: contribution.mode,
|
||||
status: contribution.autoStatus,
|
||||
title: `Souvenir pour ${person.firstName}`.slice(0, 120),
|
||||
title: `Souvenir pour ${person.firstName || person.lastName}`.slice(0, 120),
|
||||
reviewedAt: contribution.autoStatus === 'approved' ? now : undefined,
|
||||
reviewedBy: contribution.autoStatus === 'approved' ? contribution.submittedByUserId : undefined,
|
||||
},
|
||||
@@ -372,6 +439,7 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
uploadedBy: uploaderUserId,
|
||||
status: isPending ? 'pending' : 'approved',
|
||||
contributionSessionId: contributionSession?.id ?? null,
|
||||
lifeEventId,
|
||||
},
|
||||
})
|
||||
if (!isPending) {
|
||||
@@ -433,6 +501,8 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
uploadedBy: uploaderUserId,
|
||||
status: isPending ? 'pending' : 'approved',
|
||||
contributionSessionId: contributionSession?.id ?? null,
|
||||
lifeEventId,
|
||||
blurhash: payload.data.type === 'photo' ? await computeBlurhash(prepared.buffer) ?? '' : null,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -461,7 +531,7 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
return reply.code(201).send({ media, status: media.status })
|
||||
})
|
||||
|
||||
app.post('/trees/:id/persons/:personId/avatar', UPLOAD_RATE_LIMIT, async (request, reply) => {
|
||||
app.post('/trees/:id/persons/:personId/avatar', AVATAR_RATE_LIMIT, async (request, reply) => {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
}
|
||||
@@ -490,6 +560,7 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
select: {
|
||||
id: true,
|
||||
avatarPath: true,
|
||||
immichPersonId: true,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -549,7 +620,14 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
data: {
|
||||
avatarPath: relativePath,
|
||||
avatarMimeType: prepared.mimeType,
|
||||
// Nouveau portrait : le cadrage de l'ancien ne s'applique pas à celui-ci
|
||||
avatarCrop: Prisma.DbNull,
|
||||
avatarBlurhash: await computeBlurhash(prepared.buffer) ?? '',
|
||||
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 } : {}),
|
||||
},
|
||||
})
|
||||
|
||||
@@ -564,6 +642,7 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
action: 'person_avatar_updated',
|
||||
entityType: 'person',
|
||||
entityId: params.data.personId,
|
||||
...(person.immichPersonId ? { payloadJson: { immichLinkRemoved: true } } : {}),
|
||||
},
|
||||
})
|
||||
|
||||
@@ -599,6 +678,10 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
data: {
|
||||
avatarPath: null,
|
||||
avatarMimeType: null,
|
||||
avatarCrop: Prisma.DbNull,
|
||||
avatarBlurhash: null,
|
||||
// Retirer le portrait retire aussi le lien Immich : l'association ne survit pas au portrait.
|
||||
immichPersonId: null,
|
||||
updatedBy: request.actor.userId,
|
||||
},
|
||||
})
|
||||
@@ -623,6 +706,69 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
return reply.send({ ok: true })
|
||||
})
|
||||
|
||||
// Cadrage du portrait : l'original reste en place, seul le cadrage est enregistré. Même droit que changer la photo.
|
||||
app.put('/trees/:id/persons/:personId/avatar/crop', async (request, reply) => {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
}
|
||||
|
||||
const params = treePersonParamsSchema.safeParse(request.params)
|
||||
if (!params.success) {
|
||||
return reply.code(400).send({ error: 'invalid_params' })
|
||||
}
|
||||
|
||||
const payload = avatarCropInputSchema.safeParse(request.body)
|
||||
if (!payload.success) {
|
||||
return reply.code(400).send({ error: 'invalid_payload', details: payload.error.flatten() })
|
||||
}
|
||||
|
||||
const membership = await requireAdminMembership(app, request.actor.userId, params.data.id)
|
||||
if (!membership) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
|
||||
const person = await app.prisma.person.findFirst({
|
||||
where: { id: params.data.personId, treeId: params.data.id, deletedAt: null },
|
||||
select: { avatarPath: true },
|
||||
})
|
||||
|
||||
if (!person) {
|
||||
return reply.code(404).send({ error: 'person_not_found' })
|
||||
}
|
||||
|
||||
if (!person.avatarPath) {
|
||||
return reply.code(404).send({ error: 'avatar_not_found' })
|
||||
}
|
||||
|
||||
// Hors périmètre pour l'instant : les portraits venus d'Immich ne se recadrent pas
|
||||
if (isImmichAvatarPath(person.avatarPath)) {
|
||||
return reply.code(409).send({ error: 'avatar_from_immich' })
|
||||
}
|
||||
|
||||
const avatarCrop = toStoredAvatarCrop(payload.data.crop)
|
||||
|
||||
await app.prisma.person.updateMany({
|
||||
where: { id: params.data.personId, treeId: params.data.id, deletedAt: null },
|
||||
data: {
|
||||
avatarCrop: avatarCrop ?? Prisma.DbNull,
|
||||
updatedBy: request.actor.userId,
|
||||
},
|
||||
})
|
||||
|
||||
await app.prisma.auditLog.create({
|
||||
data: {
|
||||
treeId: params.data.id,
|
||||
actorType: 'user',
|
||||
actorId: request.actor.userId,
|
||||
action: 'person_avatar_cropped',
|
||||
entityType: 'person',
|
||||
entityId: params.data.personId,
|
||||
},
|
||||
})
|
||||
|
||||
return reply.send({ ok: true, avatarCrop: readAvatarCrop(avatarCrop) })
|
||||
})
|
||||
|
||||
app.patch('/trees/:id/persons/:personId/media/reorder', async (request, reply) => {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
@@ -668,38 +814,148 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
return reply.code(400).send({ error: 'invalid_media_order_payload' })
|
||||
}
|
||||
|
||||
for (let index = 0; index < orderedIds.length; index += 1) {
|
||||
await app.prisma.mediaItem.updateMany({
|
||||
where: {
|
||||
id: orderedIds[index],
|
||||
treeId: params.data.id,
|
||||
personId: params.data.personId,
|
||||
deletedAt: null,
|
||||
},
|
||||
const actorId = request.actor.userId
|
||||
await app.prisma.$transaction(async (tx) => {
|
||||
for (let index = 0; index < orderedIds.length; index += 1) {
|
||||
await tx.mediaItem.updateMany({
|
||||
where: {
|
||||
id: orderedIds[index],
|
||||
treeId: params.data.id,
|
||||
personId: params.data.personId,
|
||||
deletedAt: null,
|
||||
},
|
||||
data: {
|
||||
displayOrder: index + 1,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
await syncPersonMediaOrder(tx, params.data.id, params.data.personId)
|
||||
|
||||
await tx.auditLog.create({
|
||||
data: {
|
||||
displayOrder: index + 1,
|
||||
treeId: params.data.id,
|
||||
actorType: 'user',
|
||||
actorId,
|
||||
action: 'media_reordered',
|
||||
entityType: 'media_item',
|
||||
entityId: params.data.personId,
|
||||
payloadJson: {
|
||||
personId: params.data.personId,
|
||||
orderedMediaIds: payload.data.orderedMediaIds,
|
||||
},
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
return reply.send({ ok: true })
|
||||
})
|
||||
|
||||
// Modifier un souvenir : titre (caption) et moment de vie. Pour une citation, caption est aussi le texte
|
||||
// du fichier citation.txt, réécrit ici pour que la lecture et le téléchargement restent identiques.
|
||||
app.patch('/trees/:id/persons/:personId/media/:mediaId', async (request, reply) => {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
}
|
||||
|
||||
await syncPersonMediaOrder(app.prisma, params.data.id, params.data.personId)
|
||||
const params = z
|
||||
.object({
|
||||
id: z.string().min(1),
|
||||
personId: z.string().min(1),
|
||||
mediaId: z.string().min(1),
|
||||
})
|
||||
.safeParse(request.params)
|
||||
|
||||
if (!params.success) {
|
||||
return reply.code(400).send({ error: 'invalid_params' })
|
||||
}
|
||||
|
||||
const membership = await requireAdminMembership(app, request.actor.userId, params.data.id)
|
||||
if (!membership) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
|
||||
const payload = updateMediaSchema.safeParse(request.body)
|
||||
if (!payload.success) {
|
||||
return reply.code(400).send({ error: 'invalid_payload' })
|
||||
}
|
||||
|
||||
const existingMedia = await app.prisma.mediaItem.findFirst({
|
||||
where: { id: params.data.mediaId, treeId: params.data.id, personId: params.data.personId, deletedAt: null },
|
||||
select: { id: true, type: true, filePath: true },
|
||||
})
|
||||
if (!existingMedia) {
|
||||
return reply.code(404).send({ error: 'media_not_found' })
|
||||
}
|
||||
|
||||
const isCitation = existingMedia.type === 'citation'
|
||||
if (!isCitation && payload.data.caption.length > MAX_CAPTION_LENGTH) {
|
||||
return reply.code(400).send({ error: 'caption_too_long' })
|
||||
}
|
||||
|
||||
const lifeEventId = payload.data.lifeEventId
|
||||
if (lifeEventId) {
|
||||
const event = await app.prisma.lifeEvent.findFirst({
|
||||
where: { id: lifeEventId, treeId: params.data.id, deletedAt: null },
|
||||
select: { personId: true, unionId: true, status: true },
|
||||
})
|
||||
let ownsEvent = event?.personId === params.data.personId
|
||||
if (event && !ownsEvent && event.unionId) {
|
||||
const union = await app.prisma.union.findFirst({
|
||||
where: { id: event.unionId, treeId: params.data.id },
|
||||
select: { partner1PersonId: true, partner2PersonId: true },
|
||||
})
|
||||
ownsEvent = union?.partner1PersonId === params.data.personId || union?.partner2PersonId === params.data.personId
|
||||
}
|
||||
if (!event || !ownsEvent || event.status !== 'approved') {
|
||||
return reply.code(400).send({ error: 'invalid_life_event_reference' })
|
||||
}
|
||||
}
|
||||
|
||||
const data: { caption: string; lifeEventId?: string | null; sizeBytes?: number } = {
|
||||
caption: payload.data.caption,
|
||||
}
|
||||
if (lifeEventId !== undefined) data.lifeEventId = lifeEventId
|
||||
|
||||
if (isCitation) {
|
||||
const buffer = Buffer.from(payload.data.caption, 'utf8')
|
||||
const storageRoot = getStorageRoot()
|
||||
const absolutePath = path.resolve(storageRoot, existingMedia.filePath)
|
||||
if (!absolutePath.startsWith(storageRoot + path.sep)) {
|
||||
return reply.code(400).send({ error: 'invalid_media_path' })
|
||||
}
|
||||
await writeFile(absolutePath, buffer)
|
||||
data.sizeBytes = buffer.length
|
||||
}
|
||||
|
||||
await app.prisma.mediaItem.updateMany({
|
||||
where: { id: params.data.mediaId, treeId: params.data.id, personId: params.data.personId, deletedAt: null },
|
||||
data,
|
||||
})
|
||||
|
||||
await app.prisma.auditLog.create({
|
||||
data: {
|
||||
treeId: params.data.id,
|
||||
actorType: 'user',
|
||||
actorId: request.actor.userId,
|
||||
action: 'media_reordered',
|
||||
action: 'media_updated',
|
||||
entityType: 'media_item',
|
||||
entityId: params.data.personId,
|
||||
entityId: params.data.mediaId,
|
||||
payloadJson: {
|
||||
personId: params.data.personId,
|
||||
orderedMediaIds: payload.data.orderedMediaIds,
|
||||
lifeEventChanged: lifeEventId !== undefined,
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
return reply.send({ ok: true })
|
||||
return reply.send({
|
||||
ok: true,
|
||||
media: {
|
||||
id: params.data.mediaId,
|
||||
caption: payload.data.caption,
|
||||
lifeEventId,
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
app.delete('/trees/:id/persons/:personId/media/:mediaId', async (request, reply) => {
|
||||
@@ -745,8 +1001,9 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
return reply.code(404).send({ error: 'media_not_found' })
|
||||
}
|
||||
|
||||
// Supprimé = effacé du disque (la ligne reste pour le journal)
|
||||
// Supprimé = effacé du disque (la ligne reste pour le journal), et plus personne n'y est identifié
|
||||
await removeStoredFile(getStorageRoot(), existingMedia?.filePath)
|
||||
await app.prisma.mediaPersonTag.deleteMany({ where: { treeId: params.data.id, mediaId: params.data.mediaId } })
|
||||
|
||||
await syncPersonMediaOrder(app.prisma, params.data.id, params.data.personId)
|
||||
|
||||
@@ -840,6 +1097,8 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
select: {
|
||||
filePath: true,
|
||||
mimeType: true,
|
||||
status: true,
|
||||
uploadedBy: true,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -847,6 +1106,16 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
return reply.code(404).send({ error: 'media_not_found' })
|
||||
}
|
||||
|
||||
// Un souvenir qui attend la relecture ne se lit que par qui gère l'arbre ou par qui l'a envoyé, pas par toute la
|
||||
// famille qui connaîtrait son identifiant. Même réponse qu'un média absent : rien n'indique qu'il existe.
|
||||
if (media.status === 'pending') {
|
||||
const userId = await mediaRequesterUserId(app, request, query.data.token)
|
||||
const allowed = Boolean(userId) && (media.uploadedBy === userId || Boolean(await requireAdminMembership(app, userId as string, params.data.id)))
|
||||
if (!allowed) {
|
||||
return reply.code(404).send({ error: 'media_not_found' })
|
||||
}
|
||||
}
|
||||
|
||||
// YouTube videos: filePath is the YouTube URL, redirect the browser
|
||||
if (media.mimeType === 'video/youtube') {
|
||||
return reply.code(302).redirect(media.filePath)
|
||||
@@ -858,16 +1127,13 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
return reply.code(400).send({ error: 'invalid_media_path' })
|
||||
}
|
||||
|
||||
let fileBuffer: Buffer
|
||||
try {
|
||||
fileBuffer = await readFile(absolutePath)
|
||||
} catch {
|
||||
const size = await storedFileSize(absolutePath)
|
||||
if (size === null) {
|
||||
return reply.code(404).send({ error: 'media_file_missing' })
|
||||
}
|
||||
|
||||
applyMediaResponseHeaders(reply, media.mimeType, path.basename(media.filePath))
|
||||
|
||||
return reply.send(fileBuffer)
|
||||
return sendFileWithRanges(request, reply, absolutePath, size)
|
||||
})
|
||||
|
||||
// ---- Annotation Photos ----
|
||||
@@ -885,8 +1151,10 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
photoId: z.string().min(1),
|
||||
})
|
||||
|
||||
// Photo posée sur l'arbre. Un gestionnaire la pose tout de suite ; la famille (lien de partage ou membre) la
|
||||
// propose : le fichier attend la relecture, noté dans annotation_photo_uploads (lib/annotation-changes.ts).
|
||||
app.post('/trees/:id/annotation-photos', UPLOAD_RATE_LIMIT, async (request, reply) => {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
if (!request.actor) {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
}
|
||||
|
||||
@@ -900,9 +1168,16 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
return reply.code(400).send({ error: 'invalid_payload', details: payload.error.flatten() })
|
||||
}
|
||||
|
||||
const membership = await requireAdminMembership(app, request.actor.userId, params.data.id)
|
||||
if (!membership) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
const isManager = request.actor.kind === 'user' && Boolean(await requireAdminMembership(app, request.actor.userId, params.data.id))
|
||||
if (!isManager) {
|
||||
try {
|
||||
await resolveSubmissionContext(app, request.actor, params.data.id)
|
||||
} catch (error) {
|
||||
if (error instanceof ContributionRouteError) return reply.code(error.statusCode).send({ error: error.code })
|
||||
throw error
|
||||
}
|
||||
const stale = await sweepStalePendingPhotos(app.prisma, params.data.id)
|
||||
await Promise.all(stale.map((filePath) => removeStoredFile(getStorageRoot(), filePath)))
|
||||
}
|
||||
|
||||
const fileBuffer = Buffer.from(stripDataUrlPrefix(payload.data.dataBase64), 'base64')
|
||||
@@ -942,8 +1217,18 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
return reply.code(400).send({ error: 'invalid_photo_path' })
|
||||
}
|
||||
|
||||
await mkdir(path.dirname(absolutePath), { recursive: true })
|
||||
await writeFile(absolutePath, prepared.buffer)
|
||||
// Famille : la place est réservée sous un verrou par arbre avant d'écrire, pour tenir le plafond même quand
|
||||
// plusieurs envois arrivent ensemble
|
||||
if (!isManager && !(await reservePendingPhoto(app.prisma, params.data.id, photoId, relativePath))) {
|
||||
return reply.code(429).send({ error: 'too_many_pending_photos' })
|
||||
}
|
||||
try {
|
||||
await mkdir(path.dirname(absolutePath), { recursive: true })
|
||||
await writeFile(absolutePath, prepared.buffer)
|
||||
} catch (error) {
|
||||
if (!isManager) await forgetPendingPhoto(app.prisma, photoId)
|
||||
throw error
|
||||
}
|
||||
|
||||
return reply.code(201).send({
|
||||
photoId,
|
||||
|
||||
@@ -0,0 +1,293 @@
|
||||
import type { FastifyInstance, FastifyPluginAsync, FastifyReply } from 'fastify'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { Prisma } from '../generated/prisma/client.js'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { env } from '../config/env.js'
|
||||
import {
|
||||
appBaseUrl,
|
||||
finishAuthorization,
|
||||
isOidcEnabled,
|
||||
safeReturnTo,
|
||||
startAuthorization,
|
||||
type OidcIdentity,
|
||||
type OidcPending,
|
||||
} from '../lib/oidc.js'
|
||||
import { confirmsWithPassword } from '../lib/auth.js'
|
||||
import { createAccountIfAllowed } from '../lib/registration.js'
|
||||
import { claimInvitationsForVerifiedEmail, hasPendingInvitationForEmail } from '../lib/tree-invitations.js'
|
||||
import { signUserSession } from '../lib/user-session.js'
|
||||
|
||||
// Parcours : /auth/oidc/start pose un cookie signé (state, nonce, vérificateur PKCE) et part chez le fournisseur ;
|
||||
// /auth/oidc/callback vérifie tout, trouve ou crée le compte, et renvoie vers l'app avec un jeton de passage dans le
|
||||
// fragment (#oidc=…, jamais envoyé à un serveur ni écrit dans un journal) ; l'app l'échange une seule fois contre
|
||||
// une session sur /auth/oidc/exchange. Le cookie lie le retour au navigateur qui a commencé la connexion.
|
||||
|
||||
const PENDING_COOKIE = 'parenthese_oidc'
|
||||
const PENDING_MAX_AGE_S = 10 * 60
|
||||
const HANDOFF_TTL_S = 60
|
||||
|
||||
type HandoffPayload = { kind: 'oidc_handoff'; sub: string; jti: string; exp?: number }
|
||||
|
||||
// Jetons de passage déjà échangés, jusqu'à leur expiration (une seule instance de l'API, comme les sessions révoquées)
|
||||
const usedHandoffs = new Map<string, number>()
|
||||
function consumeHandoff(jti: string, expSeconds: number): boolean {
|
||||
const now = Date.now()
|
||||
for (const [key, expiresAt] of usedHandoffs) {
|
||||
if (expiresAt < now) usedHandoffs.delete(key)
|
||||
}
|
||||
if (usedHandoffs.has(jti)) return false
|
||||
usedHandoffs.set(jti, expSeconds * 1000)
|
||||
return true
|
||||
}
|
||||
|
||||
const pendingSchema = z.object({
|
||||
state: z.string().min(1),
|
||||
nonce: z.string().min(1),
|
||||
codeVerifier: z.string().min(43),
|
||||
returnTo: z.string(),
|
||||
linkUserId: z.string().min(1).optional(),
|
||||
})
|
||||
|
||||
// Rattacher une identité du fournisseur à un compte à mot de passe. Le compte connecté demande un ticket (court, à
|
||||
// usage unique), le départ OIDC le porte, et le retour relie l'identité à ce compte. La personne prouve les deux :
|
||||
// son mot de passe (session) et son compte chez le fournisseur. C'est le chemin pour passer une instance en
|
||||
// PASSWORD_LOGIN=false sans enfermer dehors les comptes à mot de passe : le rattachement automatique par email reste
|
||||
// refusé pour eux (resolveAccount), parce que l'inscription par mot de passe ne vérifie pas l'adresse.
|
||||
const LINK_TICKET_TTL_S = 120
|
||||
type LinkTicketPayload = { kind: 'oidc_link'; sub: string; jti: string; exp?: number }
|
||||
const usedLinkTickets = new Map<string, number>()
|
||||
function consumeLinkTicket(jti: string, expSeconds: number): boolean {
|
||||
const now = Date.now()
|
||||
for (const [key, expiresAt] of usedLinkTickets) {
|
||||
if (expiresAt < now) usedLinkTickets.delete(key)
|
||||
}
|
||||
if (usedLinkTickets.has(jti)) return false
|
||||
usedLinkTickets.set(jti, expSeconds * 1000)
|
||||
return true
|
||||
}
|
||||
|
||||
type LinkResult = { userId: string } | { error: 'oidc_identity_taken' | 'oidc_failed' }
|
||||
|
||||
async function linkIdentity(app: FastifyInstance, userId: string, identity: OidcIdentity): Promise<LinkResult> {
|
||||
const user = await app.prisma.user.findUnique({ where: { id: userId }, select: { id: true } })
|
||||
if (!user) return { error: 'oidc_failed' }
|
||||
const linked = await app.prisma.userIdentity.findUnique({
|
||||
where: { issuer_subject: { issuer: identity.issuer, subject: identity.subject } },
|
||||
select: { userId: true },
|
||||
})
|
||||
// Déjà reliée à ce compte : rien à faire. Reliée à un autre : jamais déplacée d'un compte à l'autre
|
||||
if (linked) return linked.userId === userId ? { userId } : { error: 'oidc_identity_taken' }
|
||||
await app.prisma.userIdentity.create({ data: { userId, issuer: identity.issuer, subject: identity.subject } })
|
||||
return { userId }
|
||||
}
|
||||
|
||||
const exchangeSchema = z.object({
|
||||
code: z.string().min(1).max(4096),
|
||||
})
|
||||
|
||||
type AccountResult = { userId: string } | { error: 'registration_closed' | 'oidc_email_missing' | 'oidc_email_unverified' | 'oidc_email_taken' }
|
||||
|
||||
// Compte relié à cette identité ; sinon le compte qui a cet email, si le fournisseur le garantit ; sinon un compte
|
||||
// neuf, seulement si l'instance en accepte (ALLOW_REGISTRATION, ou instance encore vide).
|
||||
async function resolveAccount(app: FastifyInstance, identity: OidcIdentity): Promise<AccountResult> {
|
||||
const linked = await app.prisma.userIdentity.findUnique({
|
||||
where: { issuer_subject: { issuer: identity.issuer, subject: identity.subject } },
|
||||
select: { userId: true },
|
||||
})
|
||||
if (linked) return { userId: linked.userId }
|
||||
|
||||
if (!identity.email) return { error: 'oidc_email_missing' }
|
||||
if (env.OIDC_REQUIRE_VERIFIED_EMAIL && !identity.emailVerified) return { error: 'oidc_email_unverified' }
|
||||
|
||||
const existing = await app.prisma.user.findUnique({
|
||||
where: { email: identity.email },
|
||||
select: { id: true, passwordHash: true, identities: { select: { id: true }, take: 1 } },
|
||||
})
|
||||
if (existing) {
|
||||
// Relier un compte existant demande toujours un email vérifié, même avec OIDC_REQUIRE_VERIFIED_EMAIL=false :
|
||||
// sinon quiconque déclare l'adresse d'un autre chez le fournisseur prendrait son compte
|
||||
if (!identity.emailVerified) return { error: 'oidc_email_unverified' }
|
||||
// Jamais vers un compte à mot de passe : l'inscription ne vérifie pas l'adresse, un tiers aurait pu créer ce
|
||||
// compte avec l'email de la victime, et sa connexion par le fournisseur y serait reliée, lisible par le tiers
|
||||
if (existing.passwordHash) return { error: 'oidc_email_taken' }
|
||||
// Un compte déjà relié à une autre identité (un autre sujet) n'est jamais repris par un nouveau sujet qui
|
||||
// présente le même email : le fournisseur a pu réattribuer l'adresse. Le compte reste à celui qui l'a relié.
|
||||
if (existing.identities?.length) return { error: 'oidc_email_taken' }
|
||||
|
||||
await app.prisma.userIdentity.create({
|
||||
data: { userId: existing.id, issuer: identity.issuer, subject: identity.subject },
|
||||
})
|
||||
return { userId: existing.id }
|
||||
}
|
||||
|
||||
// Une invitation à co-gérer un arbre ouvre un compte même inscription fermée, si le fournisseur garantit l'adresse
|
||||
const created = await createAccountIfAllowed(app.prisma, (tx) => tx.user.create({
|
||||
data: {
|
||||
email: identity.email as string,
|
||||
firstName: identity.firstName,
|
||||
passwordHash: null,
|
||||
identities: { create: { issuer: identity.issuer, subject: identity.subject } },
|
||||
},
|
||||
select: { id: true },
|
||||
}), { invited: identity.emailVerified && await hasPendingInvitationForEmail(app.prisma, identity.email) })
|
||||
return created ? { userId: created.id } : { error: 'registration_closed' }
|
||||
}
|
||||
|
||||
function redirectToApp(reply: FastifyReply, returnTo: string, fragment: string) {
|
||||
reply.clearCookie(PENDING_COOKIE, { path: '/' })
|
||||
return reply.redirect(`${appBaseUrl()}${returnTo}#${fragment}`, 302)
|
||||
}
|
||||
|
||||
export const oidcRoutes: FastifyPluginAsync = async (app) => {
|
||||
if (!isOidcEnabled()) return
|
||||
|
||||
const secureCookie = new URL(env.OIDC_REDIRECT_URI).protocol === 'https:'
|
||||
|
||||
app.get(
|
||||
'/start',
|
||||
{ config: { rateLimit: { max: 20, timeWindow: '1 minute' } } },
|
||||
async (request, reply) => {
|
||||
const query = (request.query as Record<string, unknown> | undefined) ?? {}
|
||||
// Ticket de rattachement : vérifié et consommé ici, le compte voyage dans le cookie signé
|
||||
let linkUserId: string | undefined
|
||||
if (typeof query.link === 'string') {
|
||||
let ticket: LinkTicketPayload | null = null
|
||||
try { ticket = app.jwt.verify<LinkTicketPayload>(query.link) } catch { ticket = null }
|
||||
if (!ticket || ticket.kind !== 'oidc_link' || typeof ticket.exp !== 'number' || !consumeLinkTicket(ticket.jti, ticket.exp)) {
|
||||
return redirectToApp(reply, '/', 'oidc_error=oidc_link_expired')
|
||||
}
|
||||
linkUserId = ticket.sub
|
||||
}
|
||||
const returnTo = linkUserId ? '/' : safeReturnTo(query.returnTo)
|
||||
let start: Awaited<ReturnType<typeof startAuthorization>>
|
||||
try {
|
||||
start = await startAuthorization(returnTo)
|
||||
} catch (error) {
|
||||
request.log.error({ err: error }, 'OIDC discovery failed')
|
||||
return redirectToApp(reply, returnTo, 'oidc_error=oidc_unavailable')
|
||||
}
|
||||
|
||||
reply.setCookie(PENDING_COOKIE, JSON.stringify(linkUserId ? { ...start.pending, linkUserId } : start.pending), {
|
||||
path: '/',
|
||||
httpOnly: true,
|
||||
sameSite: 'lax', // envoyé au retour du fournisseur, qui est une navigation de premier niveau
|
||||
secure: secureCookie,
|
||||
signed: true,
|
||||
maxAge: PENDING_MAX_AGE_S,
|
||||
})
|
||||
return reply.redirect(start.url.href, 302)
|
||||
},
|
||||
)
|
||||
|
||||
app.get(
|
||||
'/callback',
|
||||
{ config: { rateLimit: { max: 20, timeWindow: '1 minute' } } },
|
||||
async (request, reply) => {
|
||||
const raw = request.cookies[PENDING_COOKIE]
|
||||
const unsigned = raw ? request.unsignCookie(raw) : null
|
||||
let pending: OidcPending | null = null
|
||||
if (unsigned?.valid && unsigned.value) {
|
||||
try {
|
||||
const parsed = pendingSchema.safeParse(JSON.parse(unsigned.value))
|
||||
pending = parsed.success ? parsed.data : null
|
||||
} catch {
|
||||
pending = null
|
||||
}
|
||||
}
|
||||
if (!pending) {
|
||||
// Pas de connexion commencée dans ce navigateur (cookie absent, expiré ou modifié)
|
||||
return redirectToApp(reply, '/', 'oidc_error=oidc_failed')
|
||||
}
|
||||
|
||||
const returnTo = safeReturnTo(pending.returnTo)
|
||||
const query = request.url.includes('?') ? request.url.slice(request.url.indexOf('?')) : ''
|
||||
|
||||
let identity: OidcIdentity
|
||||
try {
|
||||
identity = await finishAuthorization(query, pending)
|
||||
} catch (error) {
|
||||
// Refus chez le fournisseur, state ou nonce faux, ID token invalide (signature, émetteur, audience, date)
|
||||
request.log.warn({ err: error }, 'OIDC callback rejected')
|
||||
return redirectToApp(reply, returnTo, 'oidc_error=oidc_failed')
|
||||
}
|
||||
|
||||
let result: AccountResult | LinkResult
|
||||
try {
|
||||
result = pending.linkUserId ? await linkIdentity(app, pending.linkUserId, identity) : await resolveAccount(app, identity)
|
||||
} catch (error) {
|
||||
// Deux retours simultanés pour la même identité : le second retrouve le lien créé par le premier
|
||||
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2002') {
|
||||
result = pending.linkUserId ? await linkIdentity(app, pending.linkUserId, identity) : await resolveAccount(app, identity)
|
||||
} else {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
if ('error' in result) {
|
||||
return redirectToApp(reply, returnTo, `oidc_error=${result.error}`)
|
||||
}
|
||||
// Invitations à co-gérer un arbre : acceptées sans le lien, l'adresse étant garantie par le fournisseur (et
|
||||
// devant être celle du compte, voir claimInvitationsForVerifiedEmail)
|
||||
if (identity.email && identity.emailVerified) {
|
||||
await claimInvitationsForVerifiedEmail(app.prisma, result.userId, identity.email)
|
||||
}
|
||||
|
||||
const handoff = app.jwt.sign(
|
||||
{ kind: 'oidc_handoff', sub: result.userId, jti: randomUUID() },
|
||||
{ expiresIn: `${HANDOFF_TTL_S}s` },
|
||||
)
|
||||
return redirectToApp(reply, returnTo, `oidc=${encodeURIComponent(handoff)}`)
|
||||
},
|
||||
)
|
||||
|
||||
// Ticket de rattachement pour le compte connecté (session par en-tête) : la navigation vers /start ne peut pas
|
||||
// porter l'en-tête, le ticket le remplace, deux minutes et une seule fois
|
||||
app.post(
|
||||
'/link',
|
||||
{ config: { rateLimit: { max: 10, timeWindow: '1 minute' } } },
|
||||
async (request, reply) => {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
return reply.code(401).send({ error: 'authentication_required' })
|
||||
}
|
||||
const ticket = app.jwt.sign(
|
||||
{ kind: 'oidc_link', sub: request.actor.userId, jti: randomUUID() },
|
||||
{ expiresIn: `${LINK_TICKET_TTL_S}s` },
|
||||
)
|
||||
return reply.send({ ticket })
|
||||
},
|
||||
)
|
||||
|
||||
app.post(
|
||||
'/exchange',
|
||||
{ config: { rateLimit: { max: 20, timeWindow: '1 minute' } } },
|
||||
async (request, reply) => {
|
||||
const parsed = exchangeSchema.safeParse(request.body)
|
||||
if (!parsed.success) {
|
||||
return reply.code(400).send({ error: 'invalid_payload' })
|
||||
}
|
||||
|
||||
let payload: HandoffPayload
|
||||
try {
|
||||
payload = app.jwt.verify<HandoffPayload>(parsed.data.code)
|
||||
} catch {
|
||||
return reply.code(401).send({ error: 'invalid_handoff' })
|
||||
}
|
||||
if (payload.kind !== 'oidc_handoff' || typeof payload.exp !== 'number' || !consumeHandoff(payload.jti, payload.exp)) {
|
||||
return reply.code(401).send({ error: 'invalid_handoff' })
|
||||
}
|
||||
|
||||
const user = await app.prisma.user.findUnique({
|
||||
where: { id: payload.sub },
|
||||
select: { id: true, email: true, firstName: true, passwordHash: true },
|
||||
})
|
||||
if (!user) {
|
||||
return reply.code(401).send({ error: 'invalid_handoff' })
|
||||
}
|
||||
|
||||
return reply.send({
|
||||
token: signUserSession(app, user),
|
||||
user: { id: user.id, email: user.email, firstName: user.firstName, hasPassword: confirmsWithPassword(user.passwordHash) },
|
||||
})
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import type { FastifyPluginAsync } from 'fastify'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { canReadTree } from '../lib/tree-access.js'
|
||||
import { enabledSearchSources, searchSource, SearchSourceUnavailableError } from '../lib/search-sources.js'
|
||||
|
||||
// Panneau « Chercher quelqu'un » : le serveur interroge les sources allumées par l'opérateur
|
||||
// (SEARCH_SOURCES) au nom d'une personne qui lit l'arbre. Rattaché à un arbre pour ne pas faire de
|
||||
// l'instance un relais ouvert vers ces services ; rien n'est enregistré, seule la question part.
|
||||
|
||||
const paramsSchema = z.object({ id: z.string().min(1), source: z.string().min(1).max(40) })
|
||||
|
||||
const querySchema = z.object({
|
||||
firstName: z.string().trim().min(1).max(80),
|
||||
lastName: z.string().trim().min(1).max(80),
|
||||
birthYear: z.coerce.number().int().min(1500).max(2100).optional(),
|
||||
place: z.string().trim().max(120).optional(),
|
||||
})
|
||||
|
||||
export const searchSourceRoutes: FastifyPluginAsync = async (app) => {
|
||||
// Sources que le front peut proposer : rien d'autre que leurs identifiants. Sous /trees comme le reste :
|
||||
// nginx ne relaie vers l'API que /api, /auth, /trees et /health
|
||||
app.get('/trees/:id/search-sources', async (request, reply) => {
|
||||
const params = z.object({ id: z.string().min(1) }).safeParse(request.params)
|
||||
if (!params.success) return reply.code(400).send({ error: 'invalid_params' })
|
||||
if (!request.actor) return reply.code(401).send({ error: 'authentication_required' })
|
||||
if (!(await canReadTree(app, params.data.id, request.actor))) return reply.code(403).send({ error: 'forbidden' })
|
||||
return reply.send({ sources: enabledSearchSources() })
|
||||
})
|
||||
|
||||
app.post(
|
||||
'/trees/:id/search-sources/:source',
|
||||
{ config: { rateLimit: { max: 30, timeWindow: '1 minute' } } },
|
||||
async (request, reply) => {
|
||||
const params = paramsSchema.safeParse(request.params)
|
||||
if (!params.success) return reply.code(400).send({ error: 'invalid_params' })
|
||||
|
||||
if (!request.actor) return reply.code(401).send({ error: 'authentication_required' })
|
||||
if (!(await canReadTree(app, params.data.id, request.actor))) return reply.code(403).send({ error: 'forbidden' })
|
||||
|
||||
if (!enabledSearchSources().includes(params.data.source)) return reply.code(404).send({ error: 'source_not_enabled' })
|
||||
|
||||
const body = querySchema.safeParse(request.body)
|
||||
if (!body.success) return reply.code(400).send({ error: 'invalid_query' })
|
||||
|
||||
try {
|
||||
const results = await searchSource(params.data.source, body.data)
|
||||
return reply.send({ results })
|
||||
} catch (error) {
|
||||
if (error instanceof SearchSourceUnavailableError) {
|
||||
request.log.warn({ source: params.data.source, reason: error.message }, 'search source unavailable')
|
||||
// Quota : l'opérateur peut y remédier (MATCHID_TOKEN), le front le dit autrement qu'une panne
|
||||
return reply.code(502).send({ error: error.message === 'quota' ? 'source_quota' : 'source_unavailable' })
|
||||
}
|
||||
throw error
|
||||
}
|
||||
},
|
||||
)
|
||||
}
|
||||
+445
-11
@@ -1,7 +1,7 @@
|
||||
import path from 'node:path'
|
||||
|
||||
import type { FastifyInstance, FastifyPluginAsync, FastifyReply, FastifyRequest } from 'fastify'
|
||||
import { Prisma } from '@prisma/client'
|
||||
import { Prisma } from '../generated/prisma/client.js'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { env } from '../config/env.js'
|
||||
@@ -11,9 +11,14 @@ import { removeStoredFile } from '../lib/media-files.js'
|
||||
import { matchSharePassword } from '../lib/password-variants.js'
|
||||
import { decryptSharePassword, encryptSharePassword } from '../lib/share-password.js'
|
||||
import { purgeTrees } from '../lib/tree-purge.js'
|
||||
import { nextSiblingOrder } from '../lib/sibling-order.js'
|
||||
import { reserveTreeUnlockAttempt, serializePasswordCheck } from '../lib/unlock-guard.js'
|
||||
import type { MembershipRole } from '../types/auth.js'
|
||||
import { findParentChildValidationError, findUnionValidationError } from '../utils/relationship-guards.js'
|
||||
import { personPrecisionResets, unionPrecisionResets } from '../lib/date-precision.js'
|
||||
import { hasAnyName } from '../lib/person-names.js'
|
||||
import { sexSchema } from '../lib/person-sex.js'
|
||||
import { ContributionRouteError, resolveSubmissionContext } from './contributions.js'
|
||||
|
||||
const MAX_TREES_PER_ACCOUNT = 10
|
||||
|
||||
@@ -35,6 +40,8 @@ const patchTreeSchema = z
|
||||
slug: z.string().min(1).max(128).optional(),
|
||||
description: z.string().max(500).optional().nullable(),
|
||||
rootPersonId: z.string().min(1).optional().nullable(),
|
||||
// Un emoji (graphème composé compris), ou null pour revenir à la première lettre
|
||||
icon: z.string().trim().max(16).regex(/^\p{Extended_Pictographic}/u).optional().nullable(),
|
||||
})
|
||||
.refine((value) => Object.keys(value).length > 0, {
|
||||
message: 'at_least_one_field_required',
|
||||
@@ -81,31 +88,40 @@ const listAuditQuerySchema = z.object({
|
||||
const isoDateRegex = /^\d{4}-\d{2}-\d{2}$/
|
||||
|
||||
const createPersonSchema = z.object({
|
||||
firstName: z.string().min(1).max(120),
|
||||
lastName: z.string().min(1).max(120),
|
||||
firstName: z.string().trim().max(120),
|
||||
lastName: z.string().trim().max(120),
|
||||
birthName: z.string().max(120).optional().nullable(),
|
||||
nickname: z.string().max(120).optional().nullable(),
|
||||
birthDate: z.string().regex(isoDateRegex).optional().nullable(),
|
||||
deathDate: z.string().regex(isoDateRegex).optional().nullable(),
|
||||
isDeceased: z.boolean().optional(),
|
||||
toVerify: z.boolean().optional(),
|
||||
birthPlace: z.string().max(200).optional().nullable(),
|
||||
deathPlace: z.string().max(200).optional().nullable(),
|
||||
profession: z.string().max(200).optional().nullable(),
|
||||
region: z.string().max(120).optional().nullable(),
|
||||
nationality: z.string().max(120).optional().nullable(),
|
||||
sex: z.string().max(20).optional().nullable(),
|
||||
sex: sexSchema,
|
||||
notes: z.string().max(2000).optional().nullable(),
|
||||
})
|
||||
}).refine((value) => hasAnyName(value.firstName, value.lastName), { message: 'name_required', path: ['lastName'] })
|
||||
|
||||
const patchPersonSchema = z
|
||||
.object({
|
||||
firstName: z.string().min(1).max(120).optional(),
|
||||
lastName: z.string().min(1).max(120).optional(),
|
||||
firstName: z.string().trim().max(120).optional(),
|
||||
lastName: z.string().trim().max(120).optional(),
|
||||
birthName: z.string().max(120).optional().nullable(),
|
||||
nickname: z.string().max(120).optional().nullable(),
|
||||
birthDate: z.string().regex(isoDateRegex).optional().nullable(),
|
||||
deathDate: z.string().regex(isoDateRegex).optional().nullable(),
|
||||
isDeceased: z.boolean().optional(),
|
||||
// « À vérifier » : la famille n'est pas sûre de cette personne (retour d'Anaïs, 23/10)
|
||||
toVerify: z.boolean().optional(),
|
||||
birthPlace: z.string().max(200).optional().nullable(),
|
||||
deathPlace: z.string().max(200).optional().nullable(),
|
||||
profession: z.string().max(200).optional().nullable(),
|
||||
region: z.string().max(120).optional().nullable(),
|
||||
nationality: z.string().max(120).optional().nullable(),
|
||||
sex: z.string().max(20).optional().nullable(),
|
||||
sex: sexSchema,
|
||||
notes: z.string().max(2000).optional().nullable(),
|
||||
})
|
||||
.refine((value) => Object.keys(value).length > 0, {
|
||||
@@ -127,6 +143,9 @@ const patchUnionSchema = z
|
||||
partner2PersonId: z.string().min(1).optional().nullable(),
|
||||
unionType: z.string().max(50).optional().nullable(),
|
||||
startDate: z.string().regex(isoDateRegex).optional().nullable(),
|
||||
// Lieu et précision de la date du couple, saisis dans l'onglet Vie (« vers 1980 »)
|
||||
startPlace: z.string().trim().max(300).optional().nullable(),
|
||||
startDatePrecision: z.enum(['about', 'estimated', 'calculated', 'before', 'after']).optional().nullable(),
|
||||
endDate: z.string().regex(isoDateRegex).optional().nullable(),
|
||||
displayOrder: z.number().int().positive().optional(),
|
||||
})
|
||||
@@ -154,6 +173,54 @@ const patchParentChildLinkSchema = z
|
||||
message: 'at_least_one_field_required',
|
||||
})
|
||||
|
||||
// Moments de l'onglet Vie (« Ajouter un moment »). Un administrateur ajoute, modifie, supprime ; la famille
|
||||
// propose, et son moment attend la relecture comme un souvenir. Naissance, décès et mariage gardent leur date
|
||||
// et leur lieu sur la personne ou l'union : leur ligne ne porte que des sources, une note et des souvenirs.
|
||||
const LIFE_EVENT_PRECISIONS = ['about', 'estimated', 'calculated', 'before', 'after', 'between', 'from', 'to', 'interpreted'] as const
|
||||
const RESERVED_LIFE_EVENT_TYPES = new Set(['birth', 'death', 'marriage'])
|
||||
const lifeEventDateRegex = /^\d{4}(-\d{2}-\d{2})?$/
|
||||
const lifeEventPayloadSchema = z.object({
|
||||
type: z.string().trim().min(1).max(40).regex(/^[a-z_]+$/).default('custom'),
|
||||
unionId: z.string().min(1).nullable().optional(),
|
||||
label: z.string().trim().max(120).nullable().optional(),
|
||||
description: z.string().trim().max(1000).nullable().optional(),
|
||||
date: z.string().regex(lifeEventDateRegex).nullable().optional(),
|
||||
dateEnd: z.string().regex(lifeEventDateRegex).nullable().optional(),
|
||||
datePrecision: z.enum(LIFE_EVENT_PRECISIONS).nullable().optional(),
|
||||
place: z.string().trim().max(300).nullable().optional(),
|
||||
notes: z.string().trim().max(4000).nullable().optional(),
|
||||
sources: z.string().trim().max(4000).nullable().optional(),
|
||||
// Souvenirs déjà dans la fiche à rattacher au moment (les nouveaux fichiers s'envoient ensuite avec lifeEventId)
|
||||
mediaIds: z.array(z.string().min(1)).max(50).optional(),
|
||||
submittedByLabel: z.string().trim().min(1).max(120).optional(),
|
||||
})
|
||||
const lifeEventPatchSchema = lifeEventPayloadSchema.omit({ type: true, unionId: true, submittedByLabel: true }).partial()
|
||||
const lifeEventParamsSchema = z.object({ id: z.string().min(1), eventId: z.string().min(1) })
|
||||
|
||||
const lifeEventDate = (value: string | null | undefined) => {
|
||||
if (value === undefined) return undefined
|
||||
if (!value) return null
|
||||
return new Date(`${value.length === 4 ? `${value}-01-01` : value}T00:00:00.000Z`)
|
||||
}
|
||||
const emptyToNull = (value: string | null | undefined) => (value === undefined ? undefined : value?.trim() ? value.trim() : null)
|
||||
|
||||
function lifeEventData(payload: z.infer<typeof lifeEventPatchSchema>, reserved: boolean) {
|
||||
const common = { notes: emptyToNull(payload.notes), sources: emptyToNull(payload.sources) }
|
||||
// Naissance, décès, mariage : rien d'autre que les sources et la note
|
||||
if (reserved) return common
|
||||
return {
|
||||
...common,
|
||||
label: emptyToNull(payload.label),
|
||||
description: emptyToNull(payload.description),
|
||||
date: lifeEventDate(payload.date),
|
||||
dateEnd: lifeEventDate(payload.dateEnd),
|
||||
datePrecision: payload.datePrecision,
|
||||
// Saisi dans l'app : pas de texte GEDCOM d'origine à garder
|
||||
dateText: null,
|
||||
place: emptyToNull(payload.place),
|
||||
}
|
||||
}
|
||||
|
||||
const personParamsSchema = z.object({
|
||||
id: z.string().min(1),
|
||||
personId: z.string().min(1),
|
||||
@@ -169,6 +236,19 @@ const linkParamsSchema = z.object({
|
||||
linkId: z.string().min(1),
|
||||
})
|
||||
|
||||
// Ordre d'une fratrie : pour chaque enfant, dans l'ordre voulu, les liens qui le rattachent à ses parents
|
||||
const childrenOrderSchema = z.object({
|
||||
order: z
|
||||
.array(
|
||||
z.object({
|
||||
childId: z.string().min(1),
|
||||
linkIds: z.array(z.string().min(1)).min(1).max(4),
|
||||
}),
|
||||
)
|
||||
.min(2)
|
||||
.max(200),
|
||||
})
|
||||
|
||||
function requireUser(request: FastifyRequest, reply: FastifyReply): { userId: string; email: string } | null {
|
||||
if (!request.actor || request.actor.kind !== 'user') {
|
||||
reply.code(401).send({ error: 'authentication_required' })
|
||||
@@ -317,6 +397,7 @@ export const treeRoutes: FastifyPluginAsync = async (app) => {
|
||||
slug: true,
|
||||
name: true,
|
||||
description: true,
|
||||
icon: true,
|
||||
rootPersonId: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
@@ -338,6 +419,7 @@ export const treeRoutes: FastifyPluginAsync = async (app) => {
|
||||
slug: true,
|
||||
name: true,
|
||||
description: true,
|
||||
icon: true,
|
||||
rootPersonId: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
@@ -367,20 +449,36 @@ export const treeRoutes: FastifyPluginAsync = async (app) => {
|
||||
slug: string
|
||||
name: string
|
||||
description: string | null
|
||||
icon: string | null
|
||||
rootPersonId: string | null
|
||||
createdAt: Date
|
||||
updatedAt: Date
|
||||
role: string
|
||||
accessMode: 'member' | 'share'
|
||||
lastAccessedAt: Date | null
|
||||
coManagers?: string[]
|
||||
}> = []
|
||||
|
||||
// Co-gestionnaires des arbres possédés : l'écran de suppression du compte les nomme (l'arbre part avec le compte)
|
||||
const ownedIds = memberships.filter((m: { role: string }) => m.role === 'owner').map((m: { tree: { id: string } }) => m.tree.id)
|
||||
const coManagerRows = ownedIds.length
|
||||
? await app.prisma.treeMembership.findMany({
|
||||
where: { treeId: { in: ownedIds }, role: 'admin' },
|
||||
select: { treeId: true, user: { select: { firstName: true, email: true } } },
|
||||
})
|
||||
: []
|
||||
|
||||
for (const membership of memberships) {
|
||||
mergedTrees.push({
|
||||
...membership.tree,
|
||||
role: membership.role,
|
||||
accessMode: 'member',
|
||||
lastAccessedAt: null,
|
||||
...(membership.role === 'owner' ? {
|
||||
coManagers: coManagerRows
|
||||
.filter((row: { treeId: string }) => row.treeId === membership.tree.id)
|
||||
.map((row: { user: { firstName: string | null; email: string } }) => row.user.firstName || row.user.email),
|
||||
} : {}),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -575,6 +673,7 @@ export const treeRoutes: FastifyPluginAsync = async (app) => {
|
||||
name?: string
|
||||
slug?: string
|
||||
description?: string | null
|
||||
icon?: string | null
|
||||
rootPersonId?: string | null
|
||||
} = {}
|
||||
|
||||
@@ -603,6 +702,10 @@ export const treeRoutes: FastifyPluginAsync = async (app) => {
|
||||
updateData.description = payload.data.description
|
||||
}
|
||||
|
||||
if (payload.data.icon !== undefined) {
|
||||
updateData.icon = payload.data.icon
|
||||
}
|
||||
|
||||
if (payload.data.rootPersonId !== undefined) {
|
||||
if (payload.data.rootPersonId === null) {
|
||||
updateData.rootPersonId = null
|
||||
@@ -1244,9 +1347,14 @@ export const treeRoutes: FastifyPluginAsync = async (app) => {
|
||||
firstName: payload.data.firstName.trim(),
|
||||
lastName: payload.data.lastName.trim(),
|
||||
birthName: toTrimmedStringOrNull(payload.data.birthName),
|
||||
nickname: toTrimmedStringOrNull(payload.data.nickname),
|
||||
birthDate: toDateOrNull(payload.data.birthDate),
|
||||
deathDate: toDateOrNull(payload.data.deathDate),
|
||||
// Une date de décès dit déjà que la personne est décédée : le drapeau ne sert que sans date
|
||||
isDeceased: !payload.data.deathDate && Boolean(payload.data.isDeceased),
|
||||
toVerify: Boolean(payload.data.toVerify),
|
||||
birthPlace: toTrimmedStringOrNull(payload.data.birthPlace),
|
||||
deathPlace: toTrimmedStringOrNull(payload.data.deathPlace),
|
||||
profession: toTrimmedStringOrNull(payload.data.profession),
|
||||
region: toTrimmedStringOrNull(payload.data.region),
|
||||
nationality: toTrimmedStringOrNull(payload.data.nationality),
|
||||
@@ -1296,13 +1404,28 @@ export const treeRoutes: FastifyPluginAsync = async (app) => {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
|
||||
// Au moins un nom : on regarde le résultat de la modification, pas seulement ce qu'elle envoie
|
||||
if (payload.data.firstName !== undefined || payload.data.lastName !== undefined) {
|
||||
const before = await app.prisma.person.findFirst({
|
||||
where: { id: params.data.personId, treeId: params.data.id, deletedAt: null },
|
||||
select: { firstName: true, lastName: true },
|
||||
})
|
||||
if (before && !hasAnyName(payload.data.firstName ?? before.firstName, payload.data.lastName ?? before.lastName)) {
|
||||
return reply.code(400).send({ error: 'invalid_payload', details: 'name_required' })
|
||||
}
|
||||
}
|
||||
|
||||
const data: {
|
||||
firstName?: string
|
||||
lastName?: string
|
||||
birthName?: string | null
|
||||
nickname?: string | null
|
||||
birthDate?: Date | null
|
||||
deathDate?: Date | null
|
||||
isDeceased?: boolean
|
||||
toVerify?: boolean
|
||||
birthPlace?: string | null
|
||||
deathPlace?: string | null
|
||||
profession?: string | null
|
||||
region?: string | null
|
||||
nationality?: string | null
|
||||
@@ -1323,6 +1446,10 @@ export const treeRoutes: FastifyPluginAsync = async (app) => {
|
||||
data.birthName = toTrimmedStringOrNull(payload.data.birthName)
|
||||
}
|
||||
|
||||
if (payload.data.nickname !== undefined) {
|
||||
data.nickname = toTrimmedStringOrNull(payload.data.nickname)
|
||||
}
|
||||
|
||||
if (payload.data.birthDate !== undefined) {
|
||||
data.birthDate = toDateOrNull(payload.data.birthDate)
|
||||
}
|
||||
@@ -1331,10 +1458,26 @@ export const treeRoutes: FastifyPluginAsync = async (app) => {
|
||||
data.deathDate = toDateOrNull(payload.data.deathDate)
|
||||
}
|
||||
|
||||
if (payload.data.isDeceased !== undefined) {
|
||||
data.isDeceased = payload.data.isDeceased
|
||||
}
|
||||
// Avec une date de décès, le drapeau « sans date » n'a plus lieu d'être
|
||||
if (data.deathDate) {
|
||||
data.isDeceased = false
|
||||
}
|
||||
|
||||
if (payload.data.toVerify !== undefined) {
|
||||
data.toVerify = payload.data.toVerify
|
||||
}
|
||||
|
||||
if (payload.data.birthPlace !== undefined) {
|
||||
data.birthPlace = toTrimmedStringOrNull(payload.data.birthPlace)
|
||||
}
|
||||
|
||||
if (payload.data.deathPlace !== undefined) {
|
||||
data.deathPlace = toTrimmedStringOrNull(payload.data.deathPlace)
|
||||
}
|
||||
|
||||
if (payload.data.profession !== undefined) {
|
||||
data.profession = toTrimmedStringOrNull(payload.data.profession)
|
||||
}
|
||||
@@ -1357,13 +1500,21 @@ export const treeRoutes: FastifyPluginAsync = async (app) => {
|
||||
|
||||
data.updatedBy = user.userId
|
||||
|
||||
const datesChanged = data.birthDate !== undefined || data.deathDate !== undefined
|
||||
const current = datesChanged
|
||||
? await app.prisma.person.findFirst({
|
||||
where: { id: params.data.personId, treeId: params.data.id, deletedAt: null },
|
||||
select: { birthDate: true, deathDate: true },
|
||||
})
|
||||
: null
|
||||
|
||||
const updated = await app.prisma.person.updateMany({
|
||||
where: {
|
||||
id: params.data.personId,
|
||||
treeId: params.data.id,
|
||||
deletedAt: null,
|
||||
},
|
||||
data,
|
||||
data: { ...data, ...personPrecisionResets(current, data) },
|
||||
})
|
||||
|
||||
if (updated.count === 0) {
|
||||
@@ -1572,6 +1723,7 @@ export const treeRoutes: FastifyPluginAsync = async (app) => {
|
||||
select: {
|
||||
partner1PersonId: true,
|
||||
partner2PersonId: true,
|
||||
startDate: true,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -1622,6 +1774,7 @@ export const treeRoutes: FastifyPluginAsync = async (app) => {
|
||||
return reply.code(400).send({ error: unionValidationError })
|
||||
}
|
||||
|
||||
const startDate = payload.data.startDate !== undefined ? toDateOrNull(payload.data.startDate) : undefined
|
||||
const updated = await app.prisma.union.updateMany({
|
||||
where: {
|
||||
id: params.data.unionId,
|
||||
@@ -1629,10 +1782,13 @@ export const treeRoutes: FastifyPluginAsync = async (app) => {
|
||||
deletedAt: null,
|
||||
},
|
||||
data: {
|
||||
...unionPrecisionResets(existingUnion, { startDate }),
|
||||
...(payload.data.startDatePrecision !== undefined ? { startDatePrecision: payload.data.startDatePrecision } : {}),
|
||||
startPlace: payload.data.startPlace !== undefined ? payload.data.startPlace || null : undefined,
|
||||
partner1PersonId: payload.data.partner1PersonId,
|
||||
partner2PersonId: payload.data.partner2PersonId,
|
||||
unionType: payload.data.unionType,
|
||||
startDate: payload.data.startDate !== undefined ? toDateOrNull(payload.data.startDate) : undefined,
|
||||
startDate,
|
||||
endDate: payload.data.endDate !== undefined ? toDateOrNull(payload.data.endDate) : undefined,
|
||||
displayOrder: payload.data.displayOrder,
|
||||
},
|
||||
@@ -1804,7 +1960,7 @@ export const treeRoutes: FastifyPluginAsync = async (app) => {
|
||||
childPersonId: payload.data.childPersonId,
|
||||
viaUnionId: payload.data.viaUnionId ?? null,
|
||||
parentageType: payload.data.parentageType ?? 'biologique',
|
||||
displayOrder: payload.data.displayOrder ?? 1,
|
||||
displayOrder: payload.data.displayOrder ?? await nextSiblingOrder(app.prisma, params.data.id, payload.data.parentPersonId),
|
||||
},
|
||||
})
|
||||
|
||||
@@ -1979,6 +2135,284 @@ export const treeRoutes: FastifyPluginAsync = async (app) => {
|
||||
return reply.send({ link })
|
||||
})
|
||||
|
||||
// Souvenirs rattachables : approuvés, d'une de ces personnes, dans cet arbre. La famille ne prend
|
||||
// que des souvenirs libres : elle ne détache pas un souvenir du moment d'un autre.
|
||||
const validLifeEventMedia = async (treeId: string, ownerIds: string[], mediaIds: string[] | undefined, onlyFree = false) => {
|
||||
if (!mediaIds?.length) return true
|
||||
const unique = [...new Set(mediaIds)]
|
||||
const count = await app.prisma.mediaItem.count({
|
||||
where: { id: { in: unique }, treeId, personId: { in: ownerIds }, status: 'approved', deletedAt: null, ...(onlyFree ? { lifeEventId: null } : {}) },
|
||||
})
|
||||
return count === unique.length
|
||||
}
|
||||
|
||||
// Rattache exactement ces souvenirs au moment (et détache ceux qui ne sont plus dans la liste)
|
||||
const setLifeEventMedia = async (db: Prisma.TransactionClient, treeId: string, eventId: string, mediaIds: string[] | undefined) => {
|
||||
if (mediaIds === undefined) return
|
||||
const unique = [...new Set(mediaIds)]
|
||||
await db.mediaItem.updateMany({ where: { treeId, lifeEventId: eventId, id: { notIn: unique } }, data: { lifeEventId: null } })
|
||||
if (unique.length) await db.mediaItem.updateMany({ where: { treeId, id: { in: unique } }, data: { lifeEventId: eventId } })
|
||||
}
|
||||
|
||||
app.post('/trees/:id/persons/:personId/life/events', async (request, reply) => {
|
||||
const actor = request.actor
|
||||
if (!actor) return reply.code(401).send({ error: 'authentication_required' })
|
||||
const params = personParamsSchema.safeParse(request.params)
|
||||
if (!params.success) return reply.code(400).send({ error: 'invalid_params' })
|
||||
const payload = lifeEventPayloadSchema.safeParse(request.body ?? {})
|
||||
if (!payload.success) return reply.code(400).send({ error: 'invalid_payload', details: payload.error.flatten() })
|
||||
const reserved = RESERVED_LIFE_EVENT_TYPES.has(payload.data.type)
|
||||
if (!reserved && payload.data.type === 'custom' && !payload.data.label?.trim() && !payload.data.description?.trim()) {
|
||||
return reply.code(400).send({ error: 'invalid_payload' })
|
||||
}
|
||||
|
||||
// Administrateur : visible tout de suite. Famille : une contribution relue, sauf si l'arbre applique tout de suite
|
||||
const membership = actor.kind === 'user' ? await getAdminMembership(app, actor.userId, params.data.id) : null
|
||||
const isAdmin = hasActiveAdminMembership(membership)
|
||||
let contribution: Awaited<ReturnType<typeof resolveSubmissionContext>> | null = null
|
||||
if (!isAdmin) {
|
||||
// Les sources d'une naissance ou d'un mariage restent l'affaire de l'administrateur
|
||||
if (reserved) return reply.code(403).send({ error: 'forbidden' })
|
||||
try {
|
||||
contribution = await resolveSubmissionContext(app, actor, params.data.id)
|
||||
} catch (error) {
|
||||
if (error instanceof ContributionRouteError) return reply.code(error.statusCode).send({ error: error.code })
|
||||
throw error
|
||||
}
|
||||
if (contribution.autoStatus === 'pending') {
|
||||
const pendingCount = await app.prisma.contributionSession.count({ where: { treeId: params.data.id, status: 'pending' } })
|
||||
if (pendingCount >= 200) return reply.code(429).send({ error: 'too_many_pending_contributions' })
|
||||
}
|
||||
}
|
||||
|
||||
const person = await app.prisma.person.findFirst({
|
||||
where: { id: params.data.personId, treeId: params.data.id, deletedAt: null },
|
||||
select: { id: true, firstName: true, lastName: true },
|
||||
})
|
||||
if (!person) return reply.code(404).send({ error: 'person_not_found' })
|
||||
|
||||
// Naissance et décès : une seule ligne par personne ; mariage : une par union de cette personne
|
||||
let unionId: string | null = null
|
||||
let ownerIds = [person.id]
|
||||
if (reserved) {
|
||||
if (payload.data.type === 'marriage') {
|
||||
const union = payload.data.unionId
|
||||
? await app.prisma.union.findFirst({
|
||||
where: { id: payload.data.unionId, treeId: params.data.id, deletedAt: null, OR: [{ partner1PersonId: person.id }, { partner2PersonId: person.id }] },
|
||||
select: { id: true, partner1PersonId: true, partner2PersonId: true },
|
||||
})
|
||||
: null
|
||||
if (!union) return reply.code(400).send({ error: 'invalid_union_reference' })
|
||||
unionId = union.id
|
||||
ownerIds = [union.partner1PersonId, union.partner2PersonId].filter((id): id is string => Boolean(id))
|
||||
}
|
||||
const existing = await app.prisma.lifeEvent.findFirst({
|
||||
where: { treeId: params.data.id, deletedAt: null, type: payload.data.type, ...(unionId ? { unionId } : { personId: person.id }) },
|
||||
select: { id: true },
|
||||
})
|
||||
if (existing) return reply.code(409).send({ error: 'event_exists', eventId: existing.id })
|
||||
}
|
||||
if (!(await validLifeEventMedia(params.data.id, ownerIds, payload.data.mediaIds, !isAdmin))) {
|
||||
return reply.code(400).send({ error: 'invalid_media_reference' })
|
||||
}
|
||||
|
||||
const isPending = contribution?.autoStatus === 'pending'
|
||||
const title = payload.data.label?.trim() || payload.data.description?.trim() || payload.data.type
|
||||
// Session, moment, souvenirs et trace de la contribution : tout ou rien
|
||||
const event = await app.prisma.$transaction(async (tx) => {
|
||||
const session = contribution
|
||||
? await tx.contributionSession.create({
|
||||
data: {
|
||||
treeId: params.data.id,
|
||||
submittedByUserId: contribution.submittedByUserId,
|
||||
submittedByLabel: payload.data.submittedByLabel?.trim() || contribution.submittedByLabel,
|
||||
mode: contribution.mode,
|
||||
status: contribution.autoStatus,
|
||||
title: `Moment pour ${person.firstName || person.lastName}`.slice(0, 120),
|
||||
reviewedAt: isPending ? undefined : new Date(),
|
||||
reviewedBy: isPending ? undefined : contribution.submittedByUserId,
|
||||
},
|
||||
})
|
||||
: null
|
||||
|
||||
const event = await tx.lifeEvent.create({
|
||||
data: {
|
||||
treeId: params.data.id,
|
||||
personId: unionId ? null : person.id,
|
||||
unionId,
|
||||
type: payload.data.type,
|
||||
...lifeEventData(payload.data, reserved),
|
||||
status: isPending ? 'pending' : 'approved',
|
||||
contributionSessionId: session?.id ?? null,
|
||||
},
|
||||
})
|
||||
await setLifeEventMedia(tx, params.data.id, event.id, payload.data.mediaIds)
|
||||
|
||||
if (session) {
|
||||
await tx.contributionChange.create({
|
||||
data: {
|
||||
sessionId: session.id,
|
||||
entityType: 'life_event',
|
||||
entityId: event.id,
|
||||
action: 'create',
|
||||
afterJson: {
|
||||
personId: person.id, type: event.type, title, date: payload.data.date ?? null, dateEnd: payload.data.dateEnd ?? null,
|
||||
datePrecision: payload.data.datePrecision ?? null, place: event.place, notes: event.notes, sources: event.sources,
|
||||
},
|
||||
decision: isPending ? undefined : 'approved',
|
||||
},
|
||||
})
|
||||
}
|
||||
return event
|
||||
})
|
||||
return reply.code(201).send({ event: { id: event.id, status: event.status } })
|
||||
})
|
||||
|
||||
app.patch('/trees/:id/life/events/:eventId', async (request, reply) => {
|
||||
const user = requireUser(request, reply)
|
||||
if (!user) return
|
||||
const params = lifeEventParamsSchema.safeParse(request.params)
|
||||
if (!params.success) return reply.code(400).send({ error: 'invalid_params' })
|
||||
const payload = lifeEventPatchSchema.safeParse(request.body ?? {})
|
||||
if (!payload.success) return reply.code(400).send({ error: 'invalid_payload', details: payload.error.flatten() })
|
||||
|
||||
const membership = await getAdminMembership(app, user.userId, params.data.id)
|
||||
if (!hasActiveAdminMembership(membership)) return reply.code(403).send({ error: 'forbidden' })
|
||||
|
||||
const existing = await app.prisma.lifeEvent.findFirst({
|
||||
where: { id: params.data.eventId, treeId: params.data.id, deletedAt: null, status: 'approved' },
|
||||
select: { personId: true, unionId: true, type: true },
|
||||
})
|
||||
if (!existing) return reply.code(404).send({ error: 'event_not_found' })
|
||||
|
||||
// Souvenirs d'une ligne de mariage : ceux de l'un ou l'autre conjoint
|
||||
let ownerIds: string[] = existing.personId ? [existing.personId] : []
|
||||
if (existing.unionId) {
|
||||
const union = await app.prisma.union.findFirst({ where: { id: existing.unionId, treeId: params.data.id }, select: { partner1PersonId: true, partner2PersonId: true } })
|
||||
ownerIds = [union?.partner1PersonId, union?.partner2PersonId].filter((id): id is string => Boolean(id))
|
||||
}
|
||||
if (!(await validLifeEventMedia(params.data.id, ownerIds, payload.data.mediaIds))) {
|
||||
return reply.code(400).send({ error: 'invalid_media_reference' })
|
||||
}
|
||||
|
||||
await app.prisma.$transaction(async (tx) => {
|
||||
await tx.lifeEvent.update({
|
||||
where: { id: params.data.eventId },
|
||||
data: lifeEventData(payload.data, RESERVED_LIFE_EVENT_TYPES.has(existing.type)),
|
||||
})
|
||||
await setLifeEventMedia(tx, params.data.id, params.data.eventId, payload.data.mediaIds)
|
||||
})
|
||||
return reply.send({ ok: true })
|
||||
})
|
||||
|
||||
app.delete('/trees/:id/life/events/:eventId', async (request, reply) => {
|
||||
const user = requireUser(request, reply)
|
||||
if (!user) return
|
||||
const params = lifeEventParamsSchema.safeParse(request.params)
|
||||
if (!params.success) return reply.code(400).send({ error: 'invalid_params' })
|
||||
|
||||
const membership = await getAdminMembership(app, user.userId, params.data.id)
|
||||
if (!hasActiveAdminMembership(membership)) return reply.code(403).send({ error: 'forbidden' })
|
||||
|
||||
const deletedCount = await app.prisma.$transaction(async (tx) => {
|
||||
const deleted = await tx.lifeEvent.updateMany({
|
||||
where: { id: params.data.eventId, treeId: params.data.id, deletedAt: null, personId: { not: null }, type: { notIn: [...RESERVED_LIFE_EVENT_TYPES] } },
|
||||
data: { deletedAt: new Date() },
|
||||
})
|
||||
// Les souvenirs restent dans la fiche, simplement détachés du moment
|
||||
if (deleted.count > 0) await tx.mediaItem.updateMany({ where: { treeId: params.data.id, lifeEventId: params.data.eventId }, data: { lifeEventId: null } })
|
||||
return deleted.count
|
||||
})
|
||||
if (deletedCount === 0) return reply.code(404).send({ error: 'event_not_found' })
|
||||
return reply.code(204).send()
|
||||
})
|
||||
|
||||
app.put('/trees/:id/links/order', async (request, reply) => {
|
||||
const user = requireUser(request, reply)
|
||||
if (!user) {
|
||||
return
|
||||
}
|
||||
|
||||
const params = treeIdParamSchema.safeParse(request.params)
|
||||
if (!params.success) {
|
||||
return reply.code(400).send({ error: 'invalid_params' })
|
||||
}
|
||||
|
||||
const payload = childrenOrderSchema.safeParse(request.body)
|
||||
if (!payload.success) {
|
||||
return reply.code(400).send({ error: 'invalid_payload', details: payload.error.flatten() })
|
||||
}
|
||||
|
||||
const membership = await getAdminMembership(app, user.userId, params.data.id)
|
||||
if (!hasActiveAdminMembership(membership)) {
|
||||
return reply.code(403).send({ error: 'forbidden' })
|
||||
}
|
||||
|
||||
const childIds = payload.data.order.map((entry) => entry.childId)
|
||||
const linkIds = payload.data.order.flatMap((entry) => entry.linkIds)
|
||||
if (new Set(childIds).size !== childIds.length || new Set(linkIds).size !== linkIds.length) {
|
||||
return reply.code(400).send({ error: 'invalid_payload' })
|
||||
}
|
||||
|
||||
const links = await app.prisma.parentChildLink.findMany({
|
||||
where: { id: { in: linkIds }, treeId: params.data.id, deletedAt: null },
|
||||
select: { id: true, parentPersonId: true, childPersonId: true, viaUnionId: true },
|
||||
})
|
||||
const linkById = new Map(links.map((link) => [link.id, link]))
|
||||
if (links.length !== linkIds.length) {
|
||||
return reply.code(404).send({ error: 'link_not_found' })
|
||||
}
|
||||
|
||||
// Chaque lien appartient bien à son enfant, et les enfants partagent au moins un parent
|
||||
const parentSets: Set<string>[] = []
|
||||
for (const entry of payload.data.order) {
|
||||
const parents = new Set<string>()
|
||||
for (const linkId of entry.linkIds) {
|
||||
const link = linkById.get(linkId)
|
||||
if (!link || link.childPersonId !== entry.childId) {
|
||||
return reply.code(400).send({ error: 'invalid_link_reference' })
|
||||
}
|
||||
parents.add(link.parentPersonId)
|
||||
}
|
||||
parentSets.push(parents)
|
||||
}
|
||||
const hasSharedParent = [...parentSets[0]].some((parentId) => parentSets.every((parents) => parents.has(parentId)))
|
||||
if (!hasSharedParent) {
|
||||
return reply.code(400).send({ error: 'not_siblings' })
|
||||
}
|
||||
|
||||
// L'arbre ne montre qu'un lien par enfant et par union : le lien vers l'autre parent de la même union
|
||||
// prend le même ordre, pour que les deux restent d'accord
|
||||
await app.prisma.$transaction(
|
||||
payload.data.order.map((entry, index) => {
|
||||
const unionIds = [...new Set(entry.linkIds.map((id) => linkById.get(id)?.viaUnionId).filter((id): id is string => Boolean(id)))]
|
||||
return app.prisma.parentChildLink.updateMany({
|
||||
where: {
|
||||
treeId: params.data.id,
|
||||
deletedAt: null,
|
||||
childPersonId: entry.childId,
|
||||
OR: [{ id: { in: entry.linkIds } }, ...(unionIds.length ? [{ viaUnionId: { in: unionIds } }] : [])],
|
||||
},
|
||||
data: { displayOrder: index + 1 },
|
||||
})
|
||||
}),
|
||||
)
|
||||
|
||||
await app.prisma.auditLog.create({
|
||||
data: {
|
||||
treeId: params.data.id,
|
||||
actorType: 'user',
|
||||
actorId: user.userId,
|
||||
action: 'children_reordered',
|
||||
entityType: 'parent_child_link',
|
||||
entityId: payload.data.order[0].linkIds[0],
|
||||
payloadJson: { childIds },
|
||||
},
|
||||
})
|
||||
|
||||
return reply.send({ ok: true })
|
||||
})
|
||||
|
||||
app.delete('/trees/:id/links/:linkId', async (request, reply) => {
|
||||
const user = requireUser(request, reply)
|
||||
if (!user) {
|
||||
|
||||
@@ -28,7 +28,22 @@ export type MediaJwtPayload = {
|
||||
accessVersion?: number
|
||||
}
|
||||
|
||||
export type AnyJwtPayload = UserJwtPayload | TreeAccessJwtPayload | MediaJwtPayload
|
||||
// Passage d'une connexion OIDC à l'app (60 s, à usage unique, échangé sur /auth/oidc/exchange) : jamais une session
|
||||
export type OidcHandoffJwtPayload = {
|
||||
kind: 'oidc_handoff'
|
||||
sub: string
|
||||
jti: string
|
||||
}
|
||||
|
||||
// Ticket de rattachement d'une identité OIDC au compte connecté (120 s, à usage unique, porté par /auth/oidc/start) :
|
||||
// jamais une session, le décodeur de l'en-tête ne retient que les sortes user et tree_access
|
||||
export type OidcLinkJwtPayload = {
|
||||
kind: 'oidc_link'
|
||||
sub: string
|
||||
jti: string
|
||||
}
|
||||
|
||||
export type AnyJwtPayload = UserJwtPayload | TreeAccessJwtPayload | MediaJwtPayload | OidcHandoffJwtPayload | OidcLinkJwtPayload
|
||||
|
||||
export type UserActor = {
|
||||
kind: 'user'
|
||||
|
||||
Vendored
+1
-1
@@ -1,4 +1,4 @@
|
||||
import type { PrismaClient } from '@prisma/client'
|
||||
import type { PrismaClient } from '../generated/prisma/client.js'
|
||||
import type { Actor, AnyJwtPayload } from './auth.js'
|
||||
|
||||
declare module '@fastify/jwt' {
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import type { Annotation, MediaItem, ParentChildLink, Person, Union } from '@prisma/client'
|
||||
import type { Annotation, MediaItem, MediaPersonTag, ParentChildLink, Person, Union } from '../generated/prisma/client.js'
|
||||
|
||||
import { sanitizeAnnotationContentForRead } from '../lib/annotation-content.js'
|
||||
import { readAvatarCrop, type AvatarCrop } from '../lib/avatar-crop.js'
|
||||
import { isImmichAvatarPath } from '../lib/media-files.js'
|
||||
import { sexOrNull } from '../lib/person-sex.js'
|
||||
|
||||
export type GraphPayload = {
|
||||
persons: Array<{
|
||||
@@ -8,15 +11,22 @@ export type GraphPayload = {
|
||||
firstName: string
|
||||
lastName: string
|
||||
birthName: string | null
|
||||
nickname: string | null
|
||||
birthDate: string | null
|
||||
deathDate: string | null
|
||||
isDeceased: boolean
|
||||
toVerify: boolean
|
||||
birthPlace: string | null
|
||||
deathPlace: string | null
|
||||
profession: string | null
|
||||
region: string | null
|
||||
nationality: string | null
|
||||
avatarUrlPath: string | null
|
||||
sex: string | null
|
||||
notes: string | null
|
||||
avatarFromImmich: boolean
|
||||
avatarCrop: AvatarCrop | null
|
||||
avatarBlurhash: string | null
|
||||
}>
|
||||
unions: Array<{
|
||||
id: string
|
||||
@@ -45,6 +55,9 @@ export type GraphPayload = {
|
||||
source: string | null
|
||||
displayOrder: number
|
||||
isFeatured: boolean
|
||||
blurhash: string | null
|
||||
// Personnes identifiées sur le souvenir, point facultatif sur le visage (0 à 1)
|
||||
people: Array<{ personId: string; x: number | null; y: number | null }>
|
||||
}>
|
||||
annotations: Array<{
|
||||
id: string
|
||||
@@ -73,7 +86,17 @@ export function buildGraphPayload(
|
||||
links: ParentChildLink[],
|
||||
medias: MediaItem[] = [],
|
||||
annotations: Annotation[] = [],
|
||||
mediaPeople: Pick<MediaPersonTag, 'mediaId' | 'personId' | 'x' | 'y'>[] = [],
|
||||
): GraphPayload {
|
||||
// Une personne supprimée n'est plus montrée sur les photos où elle était identifiée
|
||||
const livingIds = new Set(persons.map((person) => person.id))
|
||||
const peopleByMedia = new Map<string, Array<{ personId: string; x: number | null; y: number | null }>>()
|
||||
for (const tag of mediaPeople) {
|
||||
if (!livingIds.has(tag.personId)) continue
|
||||
const list = peopleByMedia.get(tag.mediaId) ?? []
|
||||
list.push({ personId: tag.personId, x: tag.x, y: tag.y })
|
||||
peopleByMedia.set(tag.mediaId, list)
|
||||
}
|
||||
// Keep DB order from route queries to preserve sibling and union ordering semantics.
|
||||
return {
|
||||
persons: persons.map((person) => ({
|
||||
@@ -81,15 +104,22 @@ export function buildGraphPayload(
|
||||
firstName: person.firstName,
|
||||
lastName: person.lastName,
|
||||
birthName: person.birthName,
|
||||
nickname: person.nickname,
|
||||
birthDate: formatDate(person.birthDate),
|
||||
deathDate: formatDate(person.deathDate),
|
||||
isDeceased: Boolean(person.isDeceased) && !person.deathDate,
|
||||
toVerify: Boolean(person.toVerify),
|
||||
birthPlace: person.birthPlace,
|
||||
deathPlace: person.deathPlace,
|
||||
profession: person.profession,
|
||||
region: person.region,
|
||||
nationality: person.nationality,
|
||||
avatarUrlPath: person.avatarPath ? `/trees/${treeId}/persons/${person.id}/avatar` : null,
|
||||
sex: person.sex,
|
||||
sex: sexOrNull(person.sex),
|
||||
notes: person.notes,
|
||||
avatarFromImmich: isImmichAvatarPath(person.avatarPath),
|
||||
avatarCrop: person.avatarPath ? readAvatarCrop(person.avatarCrop) : null,
|
||||
avatarBlurhash: (person.avatarPath && person.avatarBlurhash) || null,
|
||||
})),
|
||||
unions: unions.map((union) => ({
|
||||
id: union.id,
|
||||
@@ -118,6 +148,8 @@ export function buildGraphPayload(
|
||||
source: media.source,
|
||||
displayOrder: media.displayOrder,
|
||||
isFeatured: media.isFeatured,
|
||||
blurhash: media.blurhash || null,
|
||||
people: peopleByMedia.get(media.id) ?? [],
|
||||
})),
|
||||
annotations: annotations.map((ann) => ({
|
||||
id: ann.id,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Prisma, PrismaClient } from '@prisma/client'
|
||||
import type { Prisma, PrismaClient } from '../generated/prisma/client.js'
|
||||
|
||||
type RelationReader = Pick<PrismaClient, 'parentChildLink' | 'union'>
|
||||
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { mkdtempSync, readFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
||||
|
||||
// Aperçus flous (lib/blurhash.ts), sur une vraie base : calculés à l'envoi d'une photo et d'un portrait,
|
||||
// publiés dans le graphe, et rattrapés en tâche de fond pour ce qui n'en a pas (photos d'avant la migration,
|
||||
// imports). Lancé seulement avec TEST_DATABASE_URL (base jetable, migrée, en UTF-8) :
|
||||
// TEST_DATABASE_URL=postgresql://postgres:postgres@localhost:5432/genealogy_test npx vitest run test/apercus-flous.db.test.ts
|
||||
const TEST_DB = process.env.TEST_DATABASE_URL
|
||||
|
||||
let app: FastifyInstance
|
||||
let env: { ALLOW_REGISTRATION: boolean; MEDIA_STORAGE_PATH: string }
|
||||
let ip = 0
|
||||
const nextIp = () => `10.4.${Math.floor(++ip / 250)}.${ip % 250 + 1}`
|
||||
const run = Date.now().toString(36)
|
||||
const storage = mkdtempSync(path.join(tmpdir(), 'pth-apercus-'))
|
||||
const PHOTO_BYTES = readFileSync(fileURLToPath(new URL('../../frontend/public/demo/souvenir-mariage-1918.webp', import.meta.url)))
|
||||
const PHOTO = PHOTO_BYTES.toString('base64')
|
||||
|
||||
async function call(method: string, url: string, token?: string, payload?: unknown) {
|
||||
const res = await app.inject({
|
||||
method: method as 'GET',
|
||||
url,
|
||||
payload: payload as Record<string, unknown>,
|
||||
headers: token ? { authorization: `Bearer ${token}` } : {},
|
||||
remoteAddress: nextIp(),
|
||||
})
|
||||
let body = null
|
||||
try { body = res.body ? res.json() : null } catch { body = null }
|
||||
return { status: res.statusCode, body }
|
||||
}
|
||||
|
||||
describe.skipIf(!TEST_DB)('aperçus flous, vraie base', () => {
|
||||
let token: string
|
||||
let treeId: string
|
||||
let personId: string
|
||||
|
||||
beforeAll(async () => {
|
||||
process.env.NODE_ENV = 'test'
|
||||
process.env.DATABASE_URL = TEST_DB
|
||||
process.env.JWT_SECRET = 'test-secret-with-sufficient-length'
|
||||
process.env.CORS_ORIGIN = 'http://localhost:5173'
|
||||
process.env.MEDIA_STORAGE_PATH = storage
|
||||
;({ env } = await import('../src/config/env.js'))
|
||||
const { createApp } = await import('../src/app.js')
|
||||
app = createApp()
|
||||
env.ALLOW_REGISTRATION = true
|
||||
env.MEDIA_STORAGE_PATH = storage
|
||||
const owner = await call('POST', '/auth/register', undefined, { email: `apercus-${run}@exemple.fr`, password: 'mot-de-passe-solide', firstName: 'Patch' })
|
||||
expect(owner.status).toBe(201)
|
||||
token = owner.body.token
|
||||
const tree = await call('POST', '/trees', token, { name: 'Aperçus', slug: `apercus-${run}`, visitorPassword: 'partage-demo-1', contributorPassword: 'partage-demo-1' })
|
||||
treeId = tree.body.tree?.id ?? tree.body.id
|
||||
const person = await call('POST', `/trees/${treeId}/persons`, token, { firstName: 'Odette', lastName: 'Duval' })
|
||||
personId = person.body.person?.id ?? person.body.id
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
await app?.close()
|
||||
})
|
||||
|
||||
const graph = async () => (await call('GET', `/trees/${treeId}/graph`, token)).body
|
||||
|
||||
it('une photo et un portrait envoyés ont leur aperçu tout de suite, publié dans le graphe', async () => {
|
||||
const media = await call('POST', `/trees/${treeId}/persons/${personId}/media`, token, { type: 'photo', fileName: 'mariage.webp', mimeType: 'image/webp', sizeBytes: PHOTO_BYTES.length, dataBase64: PHOTO })
|
||||
expect(media.status).toBe(201)
|
||||
const avatar = await call('POST', `/trees/${treeId}/persons/${personId}/avatar`, token, { fileName: 'portrait.webp', mimeType: 'image/webp', sizeBytes: PHOTO_BYTES.length, dataBase64: PHOTO })
|
||||
expect(avatar.status).toBeLessThan(300)
|
||||
const g = await graph()
|
||||
expect(g.graph?.medias?.[0]?.blurhash ?? g.medias?.[0]?.blurhash).toMatch(/^[0-9A-Za-z#$%*+,-.:;=?@[\]^_{|}~]{28}$/)
|
||||
const person = (g.graph?.persons ?? g.persons).find((p: { id: string }) => p.id === personId)
|
||||
expect(person.avatarBlurhash).toHaveLength(28)
|
||||
})
|
||||
|
||||
it('la tâche de fond rattrape une photo et un portrait sans aperçu', async () => {
|
||||
await app.prisma.mediaItem.updateMany({ where: { treeId }, data: { blurhash: null } })
|
||||
await app.prisma.person.updateMany({ where: { id: personId }, data: { avatarBlurhash: null } })
|
||||
const { fillMissingBlurhashes } = await import('../src/lib/blurhash.js')
|
||||
const done = await fillMissingBlurhashes(app, path.resolve(storage))
|
||||
expect(done).toBeGreaterThanOrEqual(2)
|
||||
expect((await app.prisma.mediaItem.findFirst({ where: { treeId } }))?.blurhash).toHaveLength(28)
|
||||
expect((await app.prisma.person.findUnique({ where: { id: personId } }))?.avatarBlurhash).toHaveLength(28)
|
||||
})
|
||||
|
||||
it('un fichier illisible reçoit un aperçu vide, pour ne pas être relu à chaque passage', async () => {
|
||||
const media = await app.prisma.mediaItem.findFirst({ where: { treeId } })
|
||||
await app.prisma.mediaItem.update({ where: { id: media!.id }, data: { blurhash: null, filePath: `${treeId}/absent.webp` } })
|
||||
const { fillMissingBlurhashes } = await import('../src/lib/blurhash.js')
|
||||
await fillMissingBlurhashes(app, path.resolve(storage))
|
||||
expect((await app.prisma.mediaItem.findUnique({ where: { id: media!.id } }))?.blurhash).toBe('')
|
||||
})
|
||||
})
|
||||
@@ -1,9 +1,18 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { adoptedFamilies, familyExtras, personExtras } from '../src/lib/gedcom-events'
|
||||
import { indexGedcomRecords } from '../src/lib/gedcom-photos'
|
||||
import { parseGedcom } from '../src/routes/gedcom'
|
||||
|
||||
const { prismaMock } = vi.hoisted(() => ({
|
||||
prismaMock: {
|
||||
// Sessions fermées (lib/token-revocation.ts), rechargées au démarrage
|
||||
revokedSession: {
|
||||
upsert: vi.fn().mockResolvedValue({}),
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
deleteMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
},
|
||||
user: {
|
||||
findUnique: vi.fn(),
|
||||
count: vi.fn().mockResolvedValue(1),
|
||||
@@ -67,8 +76,19 @@ const { prismaMock } = vi.hoisted(() => ({
|
||||
update: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
},
|
||||
lifeEvent: {
|
||||
findFirst: vi.fn(),
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
createMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
updateMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
},
|
||||
annotation: {
|
||||
findMany: vi.fn(),
|
||||
count: vi.fn().mockResolvedValue(0),
|
||||
create: vi.fn(),
|
||||
updateMany: vi.fn().mockResolvedValue({ count: 1 }),
|
||||
},
|
||||
contributionSession: {
|
||||
create: vi.fn(),
|
||||
@@ -81,6 +101,11 @@ const { prismaMock } = vi.hoisted(() => ({
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
mediaPersonTag: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
deleteMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
createMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
},
|
||||
auditLog: {
|
||||
create: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
@@ -419,6 +444,112 @@ describe('Graph routes', () => {
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('frise de vie : lisible avec un accès à l’arbre, refusée pour un autre arbre, 404 pour une personne inconnue', async () => {
|
||||
const app = createApp()
|
||||
await app.ready()
|
||||
const sign = (treeId: string) => (app as any).jwt.sign({
|
||||
kind: 'tree_access',
|
||||
sub: `tree:${treeId}:visitor`,
|
||||
treeId,
|
||||
role: 'visitor',
|
||||
accessVersion: new Date('2026-02-11T10:00:00.000Z').getTime(),
|
||||
})
|
||||
|
||||
prismaMock.tree.findFirst.mockResolvedValue({ id: 'tree-1', rootPersonId: null })
|
||||
prismaMock.person.findFirst.mockResolvedValue({
|
||||
id: 'p-1', birthDatePrecision: 'about', birthDateEnd: null, deathDatePrecision: null, deathDateEnd: null,
|
||||
deathPlace: 'Nantes, France', nickname: 'Loulou',
|
||||
})
|
||||
prismaMock.union.findMany.mockResolvedValue([
|
||||
{ id: 'u-1', partner1PersonId: 'p-1', partner2PersonId: 'p-2', startDate: new Date('1905-01-01T00:00:00Z'), startPlace: 'Limoges', startDatePrecision: 'estimated', endDate: null },
|
||||
])
|
||||
prismaMock.lifeEvent.findMany.mockResolvedValue([
|
||||
{ id: 'e-1', personId: 'p-1', unionId: null, type: 'baptism', label: null, date: new Date('1879-03-09T00:00:00Z'), dateEnd: null, datePrecision: null, dateText: null, place: 'La Roche-sur-Yon', description: null, notes: null, sources: 'Registre', displayOrder: 1 },
|
||||
])
|
||||
|
||||
const ok = await app.inject({ method: 'GET', url: '/trees/tree-1/persons/p-1/life', headers: { authorization: `Bearer ${sign('tree-1')}` } })
|
||||
expect(ok.statusCode).toBe(200)
|
||||
expect(ok.json()).toMatchObject({
|
||||
person: { birthDatePrecision: 'about', deathPlace: 'Nantes, France', nickname: 'Loulou' },
|
||||
unions: [{ id: 'u-1', partnerId: 'p-2', startDate: '1905-01-01', startPlace: 'Limoges', startDatePrecision: 'estimated' }],
|
||||
events: [{ id: 'e-1', type: 'baptism', date: '1879-03-09', place: 'La Roche-sur-Yon', sources: 'Registre' }],
|
||||
})
|
||||
|
||||
const other = await app.inject({ method: 'GET', url: '/trees/tree-1/persons/p-1/life', headers: { authorization: `Bearer ${sign('tree-2')}` } })
|
||||
expect(other.statusCode).toBe(403)
|
||||
|
||||
prismaMock.person.findFirst.mockResolvedValue(null)
|
||||
const missing = await app.inject({ method: 'GET', url: '/trees/tree-1/persons/p-404/life', headers: { authorization: `Bearer ${sign('tree-1')}` } })
|
||||
expect(missing.statusCode).toBe(404)
|
||||
|
||||
const anonymous = await app.inject({ method: 'GET', url: '/trees/tree-1/persons/p-1/life' })
|
||||
expect(anonymous.statusCode).toBe(401)
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('export GEDCOM : précisions, événements, sources et adoption relus à l’identique', async () => {
|
||||
const app = createApp()
|
||||
await app.ready()
|
||||
const token = (app as any).jwt.sign({
|
||||
kind: 'tree_access',
|
||||
sub: 'tree:tree-1:visitor',
|
||||
treeId: 'tree-1',
|
||||
role: 'visitor',
|
||||
accessVersion: new Date('2026-02-11T10:00:00.000Z').getTime(),
|
||||
})
|
||||
const base = { birthDateEnd: null, deathDateEnd: null, deathDatePrecision: null, deathPlace: null, nickname: null, notes: null, profession: null, deathDate: null }
|
||||
prismaMock.tree.findFirst.mockResolvedValue({ id: 'tree-1', name: 'Ragot', rootPersonId: null })
|
||||
prismaMock.person.findMany.mockResolvedValue([
|
||||
{ ...base, id: 'p-1', firstName: 'Louis', lastName: 'Ragot', sex: 'male', birthDate: new Date('1879-01-01T00:00:00Z'), birthDatePrecision: 'about', birthPlace: 'La Roche-sur-Yon', deathDate: new Date('1950-05-02T00:00:00Z'), deathPlace: 'Nantes', nickname: 'Loulou', profession: 'Instituteur' },
|
||||
{ ...base, id: 'p-2', firstName: 'Marie', lastName: 'Bodin', sex: 'female', birthDate: null, birthDatePrecision: null, birthPlace: null, isDeceased: true },
|
||||
{ ...base, id: 'p-3', firstName: 'Jean', lastName: 'Ragot', sex: 'M', birthDate: null, birthDatePrecision: null, birthPlace: null },
|
||||
])
|
||||
prismaMock.union.findMany.mockResolvedValue([
|
||||
{ id: 'u-1', partner1PersonId: 'p-1', partner2PersonId: 'p-2', startDate: new Date('1905-01-01T00:00:00Z'), startDatePrecision: 'estimated', startPlace: 'Limoges', endDate: null },
|
||||
])
|
||||
prismaMock.parentChildLink.findMany.mockResolvedValue([
|
||||
{ id: 'l-1', parentPersonId: 'p-1', childPersonId: 'p-3', viaUnionId: 'u-1', parentageType: 'adoption' },
|
||||
{ id: 'l-2', parentPersonId: 'p-2', childPersonId: 'p-3', viaUnionId: 'u-1', parentageType: 'adoption' },
|
||||
])
|
||||
const event = { label: null, dateEnd: null, datePrecision: null, dateText: null, place: null, description: null, notes: null, sources: null, displayOrder: 1 }
|
||||
prismaMock.lifeEvent.findMany.mockResolvedValue([
|
||||
{ ...event, id: 'e-1', personId: 'p-1', unionId: null, type: 'birth', date: null, sources: 'Registre des naissances, Acte n° 12' },
|
||||
{ ...event, id: 'e-2', personId: 'p-1', unionId: null, type: 'baptism', date: new Date('1879-03-09T00:00:00Z'), place: 'La Roche-sur-Yon' },
|
||||
{ ...event, id: 'e-3', personId: 'p-1', unionId: null, type: 'occupation', date: new Date('1900-01-01T00:00:00Z'), dateEnd: new Date('1935-01-01T00:00:00Z'), datePrecision: 'from', description: 'Instituteur' },
|
||||
{ ...event, id: 'e-4', personId: 'p-1', unionId: null, type: 'custom', label: 'Militaire', date: new Date('1914-01-01T00:00:00Z'), dateEnd: new Date('1918-01-01T00:00:00Z'), datePrecision: 'between', notes: 'Blessé à Verdun.\nRentré en 1919.' },
|
||||
{ ...event, id: 'e-6', personId: null, unionId: 'u-1', type: 'marriage', date: null, sources: 'Registre des mariages de Limoges' },
|
||||
{ ...event, id: 'e-7', personId: null, unionId: 'u-1', type: 'divorce', date: new Date('1920-06-01T00:00:00Z') },
|
||||
])
|
||||
|
||||
const response = await app.inject({ method: 'GET', url: '/trees/tree-1/export/gedcom', headers: { authorization: `Bearer ${token}` } })
|
||||
expect(response.statusCode).toBe(200)
|
||||
const text = response.body.replace(/\r\n/g, '\n')
|
||||
expect(text).toContain('1 OCCU Instituteur\n2 DATE FROM 1900 TO 1935')
|
||||
expect(text.match(/1 OCCU/g)).toHaveLength(1)
|
||||
expect(text).toContain('2 PEDI adopted')
|
||||
// Décédée sans date (issue #77) : la forme courte de la norme
|
||||
expect(text).toContain('1 NAME Marie /Bodin/\n1 SEX F\n1 DEAT Y\n')
|
||||
// Ancienne écriture « M » en base : exportée comme un homme (issue #114)
|
||||
expect(text).toContain('1 NAME Jean /Ragot/\n1 SEX M\n')
|
||||
|
||||
const roots = parseGedcom(text)
|
||||
const records = indexGedcomRecords(roots)
|
||||
const louis = roots.find((n) => n.tag === 'INDI' && n.children.some((c) => c.tag === 'NAME' && c.value.startsWith('Louis')))!
|
||||
const extras = personExtras(louis as never, records)
|
||||
expect(extras).toMatchObject({ birthDatePrecision: 'about', deathPlace: 'Nantes', nickname: 'Loulou' })
|
||||
expect(extras.events.map((e) => e.type)).toEqual(['birth', 'baptism', 'occupation', 'custom'])
|
||||
expect(extras.events[0].sources).toBe('Registre des naissances, Acte n° 12')
|
||||
expect(extras.events[3]).toMatchObject({ label: 'Militaire', datePrecision: 'between', notes: 'Blessé à Verdun.\nRentré en 1919.' })
|
||||
|
||||
const fam = roots.find((n) => n.tag === 'FAM')!
|
||||
const family = familyExtras(fam as never, records)
|
||||
expect(family).toMatchObject({ startPlace: 'Limoges', startDatePrecision: 'estimated' })
|
||||
expect(family.events.map((e) => e.type)).toEqual(['marriage', 'divorce'])
|
||||
const jean = roots.find((n) => n.tag === 'INDI' && n.children.some((c) => c.tag === 'NAME' && c.value.startsWith('Jean')))!
|
||||
expect(adoptedFamilies(jean as never).size).toBe(1)
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('allows tree access token to fetch graph', async () => {
|
||||
const app = createApp()
|
||||
await app.ready()
|
||||
@@ -518,6 +649,318 @@ describe('Graph routes', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('Décès sans date (issue #77)', () => {
|
||||
it('marque décédé sans date, et une date de décès retire le drapeau', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
const patch = (payload: object) => app.inject({ method: 'PATCH', url: '/trees/tree-1/persons/person-1', headers: { authorization: `Bearer ${token}` }, payload })
|
||||
|
||||
expect((await patch({ isDeceased: true })).statusCode).toBe(200)
|
||||
expect(prismaMock.person.updateMany.mock.calls.at(-1)[0].data).toMatchObject({ isDeceased: true })
|
||||
|
||||
expect((await patch({ deathDate: '1950-01-01', isDeceased: true })).statusCode).toBe(200)
|
||||
expect(prismaMock.person.updateMany.mock.calls.at(-1)[0].data).toMatchObject({ isDeceased: false, deathDate: new Date('1950-01-01T00:00:00.000Z') })
|
||||
|
||||
expect((await patch({ isDeceased: false, deathDate: null })).statusCode).toBe(200)
|
||||
expect(prismaMock.person.updateMany.mock.calls.at(-1)[0].data).toMatchObject({ isDeceased: false, deathDate: null })
|
||||
await app.close()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Moments de l’onglet Vie', () => {
|
||||
it('un admin ajoute un moment avec deux souvenirs, le modifie sans changer son type, le supprime', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
const auth = { authorization: `Bearer ${token}` }
|
||||
prismaMock.mediaItem.count.mockResolvedValue(2)
|
||||
prismaMock.mediaItem.updateMany.mockResolvedValue({ count: 2 })
|
||||
prismaMock.lifeEvent.create.mockResolvedValue({ id: 'e-1', status: 'approved' })
|
||||
|
||||
const created = await app.inject({
|
||||
method: 'POST', url: '/trees/tree-1/persons/person-1/life/events', headers: auth,
|
||||
payload: { label: 'Mariage à la mairie', date: '1940', datePrecision: 'about', place: 'Limoges', mediaIds: ['m-1', 'm-2'] },
|
||||
})
|
||||
expect(created.statusCode).toBe(201)
|
||||
expect(created.json()).toEqual({ event: { id: 'e-1', status: 'approved' } })
|
||||
expect(prismaMock.lifeEvent.create).toHaveBeenCalledWith({ data: expect.objectContaining({
|
||||
treeId: 'tree-1', personId: 'person-1', type: 'custom', label: 'Mariage à la mairie', status: 'approved',
|
||||
date: new Date('1940-01-01T00:00:00.000Z'), datePrecision: 'about', place: 'Limoges', contributionSessionId: null,
|
||||
}) })
|
||||
expect(prismaMock.mediaItem.updateMany).toHaveBeenCalledWith({ where: { treeId: 'tree-1', id: { in: ['m-1', 'm-2'] } }, data: { lifeEventId: 'e-1' } })
|
||||
expect(prismaMock.contributionSession.create).not.toHaveBeenCalled()
|
||||
|
||||
prismaMock.lifeEvent.findFirst.mockResolvedValue({ personId: 'person-1', unionId: null, type: 'occupation' })
|
||||
const patched = await app.inject({ method: 'PATCH', url: '/trees/tree-1/life/events/e-1', headers: auth, payload: { place: '', mediaIds: [] } })
|
||||
expect(patched.statusCode).toBe(200)
|
||||
expect(prismaMock.lifeEvent.update).toHaveBeenCalledWith({ where: { id: 'e-1' }, data: expect.objectContaining({ place: null }) })
|
||||
expect(prismaMock.lifeEvent.update.mock.calls[0][0].data).not.toHaveProperty('type')
|
||||
expect(prismaMock.mediaItem.updateMany).toHaveBeenCalledWith({ where: { treeId: 'tree-1', lifeEventId: 'e-1', id: { notIn: [] } }, data: { lifeEventId: null } })
|
||||
|
||||
prismaMock.lifeEvent.updateMany.mockResolvedValue({ count: 1 })
|
||||
const deleted = await app.inject({ method: 'DELETE', url: '/trees/tree-1/life/events/e-1', headers: auth })
|
||||
expect(deleted.statusCode).toBe(204)
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('naissance : un admin y accroche un acte et une source, une seule ligne par personne, sans date ni lieu', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
const auth = { authorization: `Bearer ${token}` }
|
||||
prismaMock.mediaItem.count.mockResolvedValue(1)
|
||||
prismaMock.lifeEvent.findFirst.mockResolvedValueOnce(null)
|
||||
prismaMock.lifeEvent.create.mockResolvedValue({ id: 'e-b', status: 'approved' })
|
||||
const post = (payload: object) => app.inject({ method: 'POST', url: '/trees/tree-1/persons/person-1/life/events', headers: auth, payload })
|
||||
|
||||
expect((await post({ type: 'birth', sources: 'Registre de Limoges', place: 'ignoré', mediaIds: ['acte'] })).statusCode).toBe(201)
|
||||
const data = prismaMock.lifeEvent.create.mock.calls[0][0].data
|
||||
expect(data).toMatchObject({ type: 'birth', personId: 'person-1', sources: 'Registre de Limoges' })
|
||||
expect(data).not.toHaveProperty('place')
|
||||
|
||||
prismaMock.lifeEvent.findFirst.mockResolvedValueOnce({ id: 'e-b' })
|
||||
expect((await post({ type: 'birth', sources: 'x' })).statusCode).toBe(409)
|
||||
|
||||
prismaMock.lifeEvent.findFirst.mockResolvedValue({ personId: 'person-1', unionId: null, type: 'birth' })
|
||||
expect((await app.inject({ method: 'PATCH', url: '/trees/tree-1/life/events/e-b', headers: auth, payload: { place: 'x', sources: 'Acte 12' } })).statusCode).toBe(200)
|
||||
expect(prismaMock.lifeEvent.update).toHaveBeenCalledWith({ where: { id: 'e-b' }, data: { notes: undefined, sources: 'Acte 12' } })
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('la famille propose un moment : en attente, dans une contribution relue', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
const auth = { authorization: `Bearer ${token}` }
|
||||
prismaMock.treeMembership.findUnique.mockResolvedValue({ role: 'member', tree: { deletedAt: null, settings: null } })
|
||||
prismaMock.contributionSession.count.mockResolvedValue(0)
|
||||
prismaMock.contributionSession.create.mockResolvedValue({ id: 's-1' })
|
||||
prismaMock.lifeEvent.create.mockResolvedValue({ id: 'e-2', status: 'pending', type: 'custom', place: 'Paris', notes: null, sources: null })
|
||||
|
||||
const created = await app.inject({
|
||||
method: 'POST', url: '/trees/tree-1/persons/person-1/life/events', headers: auth,
|
||||
payload: { label: 'Départ pour Paris', date: '1925', submittedByLabel: 'Hélène' },
|
||||
})
|
||||
expect(created.statusCode).toBe(201)
|
||||
expect(created.json()).toEqual({ event: { id: 'e-2', status: 'pending' } })
|
||||
expect(prismaMock.contributionSession.create).toHaveBeenCalledWith({ data: expect.objectContaining({ status: 'pending', submittedByLabel: 'Hélène' }) })
|
||||
expect(prismaMock.lifeEvent.create).toHaveBeenCalledWith({ data: expect.objectContaining({ status: 'pending', contributionSessionId: 's-1' }) })
|
||||
expect(prismaMock.contributionChange.create).toHaveBeenCalledWith({ data: expect.objectContaining({
|
||||
sessionId: 's-1', entityType: 'life_event', entityId: 'e-2', action: 'create', afterJson: expect.objectContaining({ title: 'Départ pour Paris' }),
|
||||
}) })
|
||||
|
||||
// La famille ne touche ni aux naissances ni aux moments existants
|
||||
expect((await app.inject({ method: 'POST', url: '/trees/tree-1/persons/person-1/life/events', headers: auth, payload: { type: 'birth', sources: 'x' } })).statusCode).toBe(403)
|
||||
expect((await app.inject({ method: 'PATCH', url: '/trees/tree-1/life/events/e-1', headers: auth, payload: { place: 'x' } })).statusCode).toBe(403)
|
||||
expect((await app.inject({ method: 'DELETE', url: '/trees/tree-1/life/events/e-1', headers: auth })).statusCode).toBe(403)
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('refuse un souvenir d’une autre personne, un moment sans titre, un mariage sans union de la personne', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
const auth = { authorization: `Bearer ${token}` }
|
||||
const post = (payload: object) => app.inject({ method: 'POST', url: '/trees/tree-1/persons/person-1/life/events', headers: auth, payload })
|
||||
|
||||
prismaMock.mediaItem.count.mockResolvedValue(0)
|
||||
expect((await post({ label: 'Mariage', mediaIds: ['autre'] })).statusCode).toBe(400)
|
||||
expect((await post({ label: ' ' })).statusCode).toBe(400)
|
||||
prismaMock.union.findFirst.mockResolvedValue(null)
|
||||
expect((await post({ type: 'marriage', unionId: 'u-x', sources: 'x' })).statusCode).toBe(400)
|
||||
expect(prismaMock.lifeEvent.create).not.toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Écritures en plusieurs temps : tout passe par une transaction', () => {
|
||||
// Le client de la transaction est un autre objet que app.prisma : une écriture faite hors transaction se voit
|
||||
const txClient = () => ({
|
||||
annotation: { create: vi.fn().mockResolvedValue({ id: 'a' }), updateMany: vi.fn().mockResolvedValue({ count: 1 }) },
|
||||
mediaItem: { updateMany: vi.fn().mockResolvedValue({ count: 1 }), findMany: vi.fn().mockResolvedValue([]), update: vi.fn() },
|
||||
lifeEvent: { create: vi.fn().mockResolvedValue({ id: 'e-1', status: 'approved' }), update: vi.fn(), updateMany: vi.fn().mockResolvedValue({ count: 1 }) },
|
||||
contributionSession: { create: vi.fn() },
|
||||
contributionChange: { create: vi.fn() },
|
||||
auditLog: { create: vi.fn() },
|
||||
})
|
||||
|
||||
it('lot d’annotations : créations, modifications, suppressions et trace dans la même transaction', async () => {
|
||||
const app = createApp()
|
||||
const auth = { authorization: `Bearer ${await createUserToken(app)}` }
|
||||
const tx = txClient()
|
||||
prismaMock.$transaction.mockImplementationOnce(async (callback: (client: unknown) => Promise<unknown>) => callback(tx))
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST', url: '/trees/tree-1/annotations/batch', headers: auth,
|
||||
payload: { create: [{ type: 'text', x: 0, y: 0, content: 'Été 1952' }, { type: 'text', x: 1, y: 1, content: 'Noël' }], update: [{ id: 'a-1', x: 5 }], delete: ['a-2'] },
|
||||
})
|
||||
expect(response.statusCode).toBe(200)
|
||||
expect(response.json()).toEqual({ ok: true, created: 2, updated: 1, deleted: 1 })
|
||||
expect(tx.annotation.create).toHaveBeenCalledTimes(2)
|
||||
expect(tx.annotation.updateMany).toHaveBeenCalledTimes(2)
|
||||
expect(tx.auditLog.create).toHaveBeenCalledTimes(1)
|
||||
expect(prismaMock.annotation.create).not.toHaveBeenCalled()
|
||||
expect(prismaMock.annotation.updateMany).not.toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('lot d’annotations : une erreur au milieu fait échouer toute la transaction', async () => {
|
||||
const app = createApp()
|
||||
const auth = { authorization: `Bearer ${await createUserToken(app)}` }
|
||||
const tx = txClient()
|
||||
tx.annotation.create.mockResolvedValueOnce({ id: 'a' }).mockRejectedValueOnce(new Error('base indisponible'))
|
||||
prismaMock.$transaction.mockImplementationOnce(async (callback: (client: unknown) => Promise<unknown>) => callback(tx))
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST', url: '/trees/tree-1/annotations/batch', headers: auth,
|
||||
payload: { create: [{ type: 'text', x: 0, y: 0, content: 'a' }, { type: 'text', x: 1, y: 1, content: 'b' }] },
|
||||
})
|
||||
expect(response.statusCode).toBe(500)
|
||||
expect(tx.auditLog.create).not.toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('réordonner les souvenirs : positions, renumérotation et trace dans la même transaction', async () => {
|
||||
const app = createApp()
|
||||
const auth = { authorization: `Bearer ${await createUserToken(app)}` }
|
||||
const tx = txClient()
|
||||
prismaMock.mediaItem.findMany.mockResolvedValueOnce([{ id: 'm-1' }, { id: 'm-2' }])
|
||||
prismaMock.$transaction.mockImplementationOnce(async (callback: (client: unknown) => Promise<unknown>) => callback(tx))
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'PATCH', url: '/trees/tree-1/persons/person-1/media/reorder', headers: auth,
|
||||
payload: { orderedMediaIds: ['m-2', 'm-1'] },
|
||||
})
|
||||
expect(response.statusCode).toBe(200)
|
||||
expect(tx.mediaItem.updateMany).toHaveBeenCalledTimes(2)
|
||||
expect(tx.auditLog.create).toHaveBeenCalledTimes(1)
|
||||
expect(prismaMock.mediaItem.updateMany).not.toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('moment : création et rattachement des souvenirs dans la même transaction', async () => {
|
||||
const app = createApp()
|
||||
const auth = { authorization: `Bearer ${await createUserToken(app)}` }
|
||||
const tx = txClient()
|
||||
prismaMock.mediaItem.count.mockResolvedValue(1)
|
||||
prismaMock.$transaction.mockImplementationOnce(async (callback: (client: unknown) => Promise<unknown>) => callback(tx))
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST', url: '/trees/tree-1/persons/person-1/life/events', headers: auth,
|
||||
payload: { label: 'Départ pour Paris', mediaIds: ['m-1'] },
|
||||
})
|
||||
expect(response.statusCode).toBe(201)
|
||||
expect(tx.lifeEvent.create).toHaveBeenCalledTimes(1)
|
||||
expect(tx.mediaItem.updateMany).toHaveBeenCalledWith({ where: { treeId: 'tree-1', id: { in: ['m-1'] } }, data: { lifeEventId: 'e-1' } })
|
||||
expect(prismaMock.lifeEvent.create).not.toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('la famille ne prend que des souvenirs libres, l’administrateur peut déplacer un souvenir d’un moment à l’autre', async () => {
|
||||
const app = createApp()
|
||||
const auth = { authorization: `Bearer ${await createUserToken(app)}` }
|
||||
const post = () => app.inject({ method: 'POST', url: '/trees/tree-1/persons/person-1/life/events', headers: auth, payload: { label: 'Communion', mediaIds: ['m-1'] } })
|
||||
prismaMock.mediaItem.count.mockResolvedValue(1)
|
||||
prismaMock.lifeEvent.create.mockResolvedValue({ id: 'e-1', status: 'approved' })
|
||||
|
||||
expect((await post()).statusCode).toBe(201)
|
||||
expect(prismaMock.mediaItem.count.mock.calls.at(-1)[0].where).not.toHaveProperty('lifeEventId')
|
||||
|
||||
prismaMock.treeMembership.findUnique.mockResolvedValue({ role: 'member', tree: { deletedAt: null, settings: null } })
|
||||
prismaMock.contributionSession.create.mockResolvedValue({ id: 's-1' })
|
||||
expect((await post()).statusCode).toBe(201)
|
||||
expect(prismaMock.mediaItem.count.mock.calls.at(-1)[0].where).toMatchObject({ lifeEventId: null })
|
||||
await app.close()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Import GEDCOM', () => {
|
||||
it('une personne des deux côtés d’une union garde un seul partenaire, une boucle parent-enfant est refusée', async () => {
|
||||
const app = createApp()
|
||||
const auth = { authorization: `Bearer ${await createUserToken(app)}` }
|
||||
prismaMock.person.findMany.mockResolvedValue([])
|
||||
prismaMock.union.findMany.mockResolvedValue([])
|
||||
prismaMock.parentChildLink.findMany.mockResolvedValue([])
|
||||
prismaMock.parentChildLink.findFirst.mockResolvedValue(null)
|
||||
prismaMock.person.create.mockImplementation(async ({ data }: { data: { firstName: string } }) => ({ id: `p-${data.firstName}` }))
|
||||
let unionCount = 0
|
||||
prismaMock.union.create.mockImplementation(async () => ({ id: `u-${++unionCount}` }))
|
||||
|
||||
const content = [
|
||||
'0 HEAD',
|
||||
'0 @I1@ INDI', '1 NAME Jean /Martin/',
|
||||
'0 @I2@ INDI', '1 NAME Paul /Martin/',
|
||||
// Jean marié à lui-même (fichier abîmé)
|
||||
'0 @F1@ FAM', '1 HUSB @I1@', '1 WIFE @I1@',
|
||||
// Paul enfant de Jean, puis Jean enfant de Paul : la seconde famille ferait une boucle
|
||||
'0 @F2@ FAM', '1 HUSB @I1@', '1 CHIL @I2@',
|
||||
'0 @F3@ FAM', '1 HUSB @I2@', '1 CHIL @I1@',
|
||||
'0 TRLR',
|
||||
].join('\n')
|
||||
const response = await app.inject({ method: 'POST', url: '/trees/tree-1/import/gedcom', headers: auth, payload: { content } })
|
||||
|
||||
expect(response.statusCode).toBe(200)
|
||||
expect(response.json()).toMatchObject({ personsCreated: 2, linksCreated: 1, relationsSkipped: 2 })
|
||||
expect(prismaMock.union.create.mock.calls[0][0].data).toMatchObject({ partner1PersonId: 'p-Jean', partner2PersonId: null })
|
||||
expect(prismaMock.parentChildLink.create).toHaveBeenCalledTimes(1)
|
||||
expect(prismaMock.parentChildLink.create.mock.calls[0][0].data).toMatchObject({ parentPersonId: 'p-Jean', childPersonId: 'p-Paul' })
|
||||
await app.close()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Sexe dans le GEDCOM (issue #114)', () => {
|
||||
const importer = async (app: FastifyInstance, content: string) => {
|
||||
const auth = { authorization: `Bearer ${await createUserToken(app)}` }
|
||||
prismaMock.person.findMany.mockResolvedValue([])
|
||||
prismaMock.union.findMany.mockResolvedValue([])
|
||||
prismaMock.parentChildLink.findMany.mockResolvedValue([])
|
||||
prismaMock.person.create.mockImplementation(async ({ data }: { data: { firstName: string } }) => ({ id: `p-${data.firstName}` }))
|
||||
prismaMock.person.create.mockClear()
|
||||
const response = await app.inject({ method: 'POST', url: '/trees/tree-1/import/gedcom', headers: auth, payload: { content } })
|
||||
expect(response.statusCode).toBe(200)
|
||||
return Object.fromEntries(prismaMock.person.create.mock.calls.map((call: [{ data: { firstName: string; sex: string | null } }]) => [call[0].data.firstName, call[0].data.sex]))
|
||||
}
|
||||
|
||||
it('import : M, F, X (GEDCOM 7), U et absent donnent male, female, other, null, null', async () => {
|
||||
const app = createApp()
|
||||
const content = [
|
||||
'0 HEAD',
|
||||
'0 @I1@ INDI', '1 NAME Jean /Martin/', '1 SEX M',
|
||||
'0 @I2@ INDI', '1 NAME Marie /Martin/', '1 SEX F',
|
||||
'0 @I3@ INDI', '1 NAME Camille /Martin/', '1 SEX X',
|
||||
'0 @I4@ INDI', '1 NAME Dominique /Martin/', '1 SEX U',
|
||||
'0 @I5@ INDI', '1 NAME Claude /Martin/',
|
||||
'0 TRLR',
|
||||
].join('\n')
|
||||
expect(await importer(app, content)).toEqual({ Jean: 'male', Marie: 'female', Camille: 'other', Dominique: null, Claude: null })
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('aller-retour : other sort en SEX U (GEDCOM 5.5.1), non précisé sans ligne SEX, le reste se relit à l’identique', async () => {
|
||||
const app = createApp()
|
||||
await app.ready()
|
||||
const token = (app as any).jwt.sign({ kind: 'tree_access', sub: 'tree:tree-1:visitor', treeId: 'tree-1', role: 'visitor', accessVersion: new Date('2026-02-11T10:00:00.000Z').getTime() })
|
||||
const base = { lastName: 'Martin', birthDate: null, birthDatePrecision: null, birthPlace: null, birthDateEnd: null, deathDateEnd: null, deathDatePrecision: null, deathPlace: null, nickname: null, notes: null, profession: null, deathDate: null }
|
||||
prismaMock.tree.findFirst.mockResolvedValue({ id: 'tree-1', name: 'Martin', rootPersonId: null })
|
||||
prismaMock.person.findMany.mockResolvedValue([
|
||||
{ ...base, id: 'p-1', firstName: 'Jean', sex: 'male' },
|
||||
{ ...base, id: 'p-2', firstName: 'Marie', sex: 'female' },
|
||||
{ ...base, id: 'p-3', firstName: 'Camille', sex: 'other' },
|
||||
{ ...base, id: 'p-4', firstName: 'Claude', sex: null },
|
||||
])
|
||||
prismaMock.union.findMany.mockResolvedValue([])
|
||||
prismaMock.parentChildLink.findMany.mockResolvedValue([])
|
||||
prismaMock.lifeEvent.findMany.mockResolvedValue([])
|
||||
|
||||
const response = await app.inject({ method: 'GET', url: '/trees/tree-1/export/gedcom', headers: { authorization: `Bearer ${token}` } })
|
||||
expect(response.statusCode).toBe(200)
|
||||
const text = response.body.replace(/\r\n/g, '\n')
|
||||
expect(text).toContain('1 NAME Camille /Martin/\n1 SEX U\n')
|
||||
expect(text).not.toContain('SEX X')
|
||||
expect(text).toMatch(/1 NAME Claude \/Martin\/\n(?!1 SEX)/)
|
||||
|
||||
// SEX U se relit comme non précisé : 5.5.1 n'a pas de valeur pour « autre ». SEX X reste lu à l'import (ligne 915).
|
||||
expect(await importer(app, text)).toEqual({ Jean: 'male', Marie: 'female', Camille: null, Claude: null })
|
||||
await app.close()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Visit log', () => {
|
||||
it('refuses the visit log to a non-admin member', async () => {
|
||||
const app = createApp()
|
||||
@@ -750,3 +1193,99 @@ describe('Relationship guardrails', () => {
|
||||
await app.close()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Surnom (nickname) en écriture directe', () => {
|
||||
it('PATCH accepte le surnom, le coupe, et vide = null', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
const patch = (payload: object) => app.inject({ method: 'PATCH', url: '/trees/tree-1/persons/person-1', headers: { authorization: `Bearer ${token}` }, payload })
|
||||
|
||||
expect((await patch({ nickname: ' Loulou ' })).statusCode).toBe(200)
|
||||
expect(prismaMock.person.updateMany.mock.calls.at(-1)[0].data).toMatchObject({ nickname: 'Loulou' })
|
||||
|
||||
expect((await patch({ nickname: ' ' })).statusCode).toBe(200)
|
||||
expect(prismaMock.person.updateMany.mock.calls.at(-1)[0].data).toMatchObject({ nickname: null })
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('refuse un surnom de plus de 120 caractères', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
const res = await app.inject({ method: 'PATCH', url: '/trees/tree-1/persons/person-1', headers: { authorization: `Bearer ${token}` }, payload: { nickname: 'x'.repeat(121) } })
|
||||
expect(res.statusCode).toBe(400)
|
||||
await app.close()
|
||||
})
|
||||
})
|
||||
|
||||
describe('« À vérifier » en écriture directe (retour d’Anaïs, 23/10)', () => {
|
||||
it('POST et PATCH posent et retirent le drapeau, absent = inchangé', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
const headers = { authorization: `Bearer ${token}` }
|
||||
|
||||
const created = await app.inject({ method: 'POST', url: '/trees/tree-1/persons', headers, payload: { firstName: 'Jeanne', lastName: 'Martin', toVerify: true } })
|
||||
expect(created.statusCode).toBe(201)
|
||||
expect(prismaMock.person.create.mock.calls.at(-1)[0].data).toMatchObject({ toVerify: true })
|
||||
|
||||
const patch = (payload: object) => app.inject({ method: 'PATCH', url: '/trees/tree-1/persons/person-1', headers, payload })
|
||||
expect((await patch({ toVerify: true })).statusCode).toBe(200)
|
||||
expect(prismaMock.person.updateMany.mock.calls.at(-1)[0].data).toMatchObject({ toVerify: true })
|
||||
expect((await patch({ toVerify: false })).statusCode).toBe(200)
|
||||
expect(prismaMock.person.updateMany.mock.calls.at(-1)[0].data).toMatchObject({ toVerify: false })
|
||||
expect((await patch({ nickname: 'Loulou' })).statusCode).toBe(200)
|
||||
expect(prismaMock.person.updateMany.mock.calls.at(-1)[0].data).not.toHaveProperty('toVerify')
|
||||
expect((await patch({ toVerify: 'oui' })).statusCode).toBe(400)
|
||||
await app.close()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Sexe d’une personne en écriture directe (issue #114)', () => {
|
||||
it('PATCH ramène le sexe à male / female / other, null = non précisé, refuse une valeur inconnue', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
const patch = (payload: object) => app.inject({ method: 'PATCH', url: '/trees/tree-1/persons/person-1', headers: { authorization: `Bearer ${token}` }, payload })
|
||||
|
||||
expect((await patch({ sex: 'F' })).statusCode).toBe(200)
|
||||
expect(prismaMock.person.updateMany.mock.calls.at(-1)[0].data).toMatchObject({ sex: 'female' })
|
||||
|
||||
expect((await patch({ sex: 'male' })).statusCode).toBe(200)
|
||||
expect(prismaMock.person.updateMany.mock.calls.at(-1)[0].data).toMatchObject({ sex: 'male' })
|
||||
|
||||
expect((await patch({ sex: 'other' })).statusCode).toBe(200)
|
||||
expect(prismaMock.person.updateMany.mock.calls.at(-1)[0].data).toMatchObject({ sex: 'other' })
|
||||
|
||||
expect((await patch({ sex: null })).statusCode).toBe(200)
|
||||
expect(prismaMock.person.updateMany.mock.calls.at(-1)[0].data).toMatchObject({ sex: null })
|
||||
|
||||
const calls = prismaMock.person.updateMany.mock.calls.length
|
||||
expect((await patch({ sex: 'robot' })).statusCode).toBe(400)
|
||||
expect(prismaMock.person.updateMany.mock.calls.length).toBe(calls)
|
||||
await app.close()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Lieu de décès et filiation adoptive (écriture)', () => {
|
||||
it('PATCH accepte le lieu de décès, le coupe, et vide = null', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
const patch = (payload: object) => app.inject({ method: 'PATCH', url: '/trees/tree-1/persons/person-1', headers: { authorization: `Bearer ${token}` }, payload })
|
||||
|
||||
expect((await patch({ deathPlace: ' Nantes, France ' })).statusCode).toBe(200)
|
||||
expect(prismaMock.person.updateMany.mock.calls.at(-1)[0].data).toMatchObject({ deathPlace: 'Nantes, France' })
|
||||
|
||||
expect((await patch({ deathPlace: ' ' })).statusCode).toBe(200)
|
||||
expect(prismaMock.person.updateMany.mock.calls.at(-1)[0].data).toMatchObject({ deathPlace: null })
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('PATCH d’un lien accepte le type de filiation (naissance ou adoption)', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
prismaMock.parentChildLink.findFirst.mockResolvedValue({ id: 'link-1', parentPersonId: 'person-2', childPersonId: 'person-1', viaUnionId: null, parentageType: 'biologique' })
|
||||
prismaMock.parentChildLink.updateMany.mockResolvedValueOnce({ count: 1 })
|
||||
const res = await app.inject({ method: 'PATCH', url: '/trees/tree-1/links/link-1', headers: { authorization: `Bearer ${token}` }, payload: { parentageType: 'adoption' } })
|
||||
expect(res.statusCode).toBe(200)
|
||||
expect(prismaMock.parentChildLink.updateMany.mock.calls.at(-1)[0].data).toMatchObject({ parentageType: 'adoption' })
|
||||
await app.close()
|
||||
})
|
||||
})
|
||||
@@ -4,6 +4,12 @@ import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { prismaMock } = vi.hoisted(() => ({
|
||||
prismaMock: {
|
||||
// Sessions fermées (lib/token-revocation.ts), rechargées au démarrage
|
||||
revokedSession: {
|
||||
upsert: vi.fn().mockResolvedValue({}),
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
deleteMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
},
|
||||
user: {
|
||||
findUnique: vi.fn(),
|
||||
count: vi.fn().mockResolvedValue(1),
|
||||
@@ -72,6 +78,11 @@ const { prismaMock } = vi.hoisted(() => ({
|
||||
update: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
},
|
||||
lifeEvent: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
createMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
updateMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
},
|
||||
annotation: {
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
@@ -86,6 +97,11 @@ const { prismaMock } = vi.hoisted(() => ({
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
mediaPersonTag: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
deleteMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
createMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
},
|
||||
auditLog: {
|
||||
create: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
@@ -285,7 +301,8 @@ describe('API security and authz', () => {
|
||||
|
||||
expect(response.statusCode).toBe(429)
|
||||
await app.close()
|
||||
})
|
||||
// Onze connexions, chacune avec une vérification bcrypt : plus de 5 s sur les machines lentes de la CI
|
||||
}, 20_000)
|
||||
|
||||
it('rate-limits register endpoint', async () => {
|
||||
const app = createApp()
|
||||
@@ -514,6 +531,130 @@ describe('API security and authz', () => {
|
||||
await app.close()
|
||||
})
|
||||
|
||||
describe('PUT /trees/:id/links/order', () => {
|
||||
const siblingLinks = [
|
||||
{ id: 'link-a1', parentPersonId: 'father', childPersonId: 'anne', viaUnionId: 'union-1' },
|
||||
{ id: 'link-a2', parentPersonId: 'mother', childPersonId: 'anne', viaUnionId: 'union-1' },
|
||||
{ id: 'link-h1', parentPersonId: 'father', childPersonId: 'hugo', viaUnionId: 'union-1' },
|
||||
{ id: 'link-h2', parentPersonId: 'mother', childPersonId: 'hugo', viaUnionId: 'union-1' },
|
||||
]
|
||||
const order = [
|
||||
{ childId: 'hugo', linkIds: ['link-h1', 'link-h2'] },
|
||||
{ childId: 'anne', linkIds: ['link-a1', 'link-a2'] },
|
||||
]
|
||||
|
||||
it('rewrites the order of a sibling group in one transaction', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
prismaMock.parentChildLink.findMany.mockResolvedValue(siblingLinks)
|
||||
prismaMock.$transaction.mockResolvedValue([])
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/trees/tree-1/links/order',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { order },
|
||||
})
|
||||
|
||||
expect(response.statusCode).toBe(200)
|
||||
expect(prismaMock.$transaction).toHaveBeenCalledTimes(1)
|
||||
expect(prismaMock.parentChildLink.updateMany).toHaveBeenNthCalledWith(1, {
|
||||
where: {
|
||||
treeId: 'tree-1', deletedAt: null, childPersonId: 'hugo',
|
||||
OR: [{ id: { in: ['link-h1', 'link-h2'] } }, { viaUnionId: { in: ['union-1'] } }],
|
||||
},
|
||||
data: { displayOrder: 1 },
|
||||
})
|
||||
expect(prismaMock.parentChildLink.updateMany).toHaveBeenNthCalledWith(2, {
|
||||
where: {
|
||||
treeId: 'tree-1', deletedAt: null, childPersonId: 'anne',
|
||||
OR: [{ id: { in: ['link-a1', 'link-a2'] } }, { viaUnionId: { in: ['union-1'] } }],
|
||||
},
|
||||
data: { displayOrder: 2 },
|
||||
})
|
||||
expect(prismaMock.auditLog.create).toHaveBeenCalledWith(expect.objectContaining({
|
||||
data: expect.objectContaining({ action: 'children_reordered', payloadJson: { childIds: ['hugo', 'anne'] } }),
|
||||
}))
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('forbids a member who is not admin', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
prismaMock.treeMembership.findUnique.mockResolvedValue({
|
||||
treeId: 'tree-1',
|
||||
userId: 'user-1',
|
||||
role: 'member',
|
||||
tree: { deletedAt: null, rootPersonId: null },
|
||||
})
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/trees/tree-1/links/order',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { order },
|
||||
})
|
||||
|
||||
expect(response.statusCode).toBe(403)
|
||||
expect(prismaMock.$transaction).not.toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('refuses links that do not belong to the tree', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
prismaMock.parentChildLink.findMany.mockResolvedValue(siblingLinks.slice(0, 3))
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/trees/tree-1/links/order',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { order },
|
||||
})
|
||||
|
||||
expect(response.statusCode).toBe(404)
|
||||
expect(prismaMock.$transaction).not.toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('refuses a link sent for the wrong child', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
prismaMock.parentChildLink.findMany.mockResolvedValue([siblingLinks[0], siblingLinks[2]])
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/trees/tree-1/links/order',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { order: [{ childId: 'hugo', linkIds: ['link-a1'] }, { childId: 'anne', linkIds: ['link-h1'] }] },
|
||||
})
|
||||
|
||||
expect(response.statusCode).toBe(400)
|
||||
expect(response.json()).toEqual({ error: 'invalid_link_reference' })
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('refuses children who share no parent', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
prismaMock.parentChildLink.findMany.mockResolvedValue([
|
||||
{ id: 'link-x', parentPersonId: 'father', childPersonId: 'anne' },
|
||||
{ id: 'link-y', parentPersonId: 'stranger', childPersonId: 'hugo' },
|
||||
])
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url: '/trees/tree-1/links/order',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { order: [{ childId: 'anne', linkIds: ['link-x'] }, { childId: 'hugo', linkIds: ['link-y'] }] },
|
||||
})
|
||||
|
||||
expect(response.statusCode).toBe(400)
|
||||
expect(response.json()).toEqual({ error: 'not_siblings' })
|
||||
await app.close()
|
||||
})
|
||||
})
|
||||
|
||||
it('forbids member from patching person records', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
@@ -1016,6 +1157,33 @@ describe('API security and authz', () => {
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('« à vérifier » proposé par la famille : appliqué à l’approbation, en création comme en modification', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
|
||||
prismaMock.contributionSession.findFirst.mockResolvedValue({
|
||||
id: 'session-1',
|
||||
treeId: 'tree-1',
|
||||
status: 'pending',
|
||||
changes: [
|
||||
{ id: 'change-1', entityType: 'person', action: 'create', entityId: null, beforeJson: null, afterJson: { firstName: 'Alice', lastName: 'Martin', toVerify: true }, conflictState: 'none' },
|
||||
{ id: 'change-2', entityType: 'person', action: 'update', entityId: 'person-1', beforeJson: { toVerify: false }, afterJson: { toVerify: true }, conflictState: 'none' },
|
||||
],
|
||||
})
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/trees/tree-1/contributions/sessions/session-1/review',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { decision: 'approved' },
|
||||
})
|
||||
|
||||
expect(response.statusCode).toBe(200)
|
||||
expect(prismaMock.person.create).toHaveBeenCalledWith(expect.objectContaining({ data: expect.objectContaining({ firstName: 'Alice', toVerify: true }) }))
|
||||
expect(prismaMock.person.updateMany).toHaveBeenCalledWith(expect.objectContaining({ where: expect.objectContaining({ id: 'person-1' }), data: expect.objectContaining({ toVerify: true }) }))
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('allows owner to upload media below image limit', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
@@ -1269,6 +1437,35 @@ describe('API security and authz', () => {
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('un moment proposé par la famille devient visible si accepté, disparaît si refusé', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
const session = (status = 'pending') => ({
|
||||
id: 'session-1',
|
||||
treeId: 'tree-1',
|
||||
status,
|
||||
changes: [
|
||||
{ id: 'change-1', entityType: 'life_event', action: 'create', entityId: 'event-1', beforeJson: null, afterJson: { personId: 'person-1', title: 'Départ pour Paris' }, conflictState: 'none' },
|
||||
],
|
||||
})
|
||||
const review = (decision: string) => app.inject({
|
||||
method: 'POST',
|
||||
url: '/trees/tree-1/contributions/sessions/session-1/review',
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { decision },
|
||||
})
|
||||
|
||||
prismaMock.contributionSession.findFirst.mockResolvedValue(session())
|
||||
prismaMock.lifeEvent.updateMany.mockResolvedValue({ count: 1 })
|
||||
expect((await review('approved')).statusCode).toBe(200)
|
||||
expect(prismaMock.lifeEvent.updateMany).toHaveBeenCalledWith({ where: { id: 'event-1', treeId: 'tree-1', deletedAt: null }, data: { status: 'approved' } })
|
||||
|
||||
prismaMock.contributionSession.findFirst.mockResolvedValue(session())
|
||||
expect((await review('rejected')).statusCode).toBe(200)
|
||||
expect(prismaMock.lifeEvent.updateMany).toHaveBeenCalledWith({ where: { id: 'event-1', treeId: 'tree-1' }, data: expect.objectContaining({ status: 'rejected' }) })
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('reviews a session containing a drawing without failing', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { hashPassword, verifyPassword } from '../src/lib/auth.js'
|
||||
|
||||
// bcrypt natif à la place de bcryptjs : les empreintes déjà en base restent valables
|
||||
describe('mots de passe, bcrypt natif', () => {
|
||||
it('lit une empreinte faite par bcryptjs', async () => {
|
||||
const fromBcryptjs = '$2b$10$4uBVFoNEA8gO3uIGq/RqMueaq4w2Vl9VzPFiSj9v9dc0oI1DcR.YS'
|
||||
expect(await verifyPassword('123soleil 🌞', fromBcryptjs)).toBe(true)
|
||||
expect(await verifyPassword('123soleil', fromBcryptjs)).toBe(false)
|
||||
})
|
||||
|
||||
it('fait une empreinte au coût 12 qui se relit', async () => {
|
||||
const stored = await hashPassword('mot-de-passe-solide')
|
||||
expect(stored).toMatch(/^\$2[aby]\$12\$/)
|
||||
expect(await verifyPassword('mot-de-passe-solide', stored)).toBe(true)
|
||||
expect(await verifyPassword('mot-de-passe-faux', stored)).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,125 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
// Prénom du compte : renvoyé à l'inscription, à la connexion et sur /me.
|
||||
const { prismaMock } = vi.hoisted(() => ({
|
||||
prismaMock: {
|
||||
// Sessions fermées (lib/token-revocation.ts), rechargées au démarrage
|
||||
revokedSession: {
|
||||
upsert: vi.fn().mockResolvedValue({}),
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
deleteMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
},
|
||||
user: {
|
||||
findUnique: vi.fn(),
|
||||
create: vi.fn(),
|
||||
count: vi.fn(),
|
||||
},
|
||||
$disconnect: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../src/lib/prisma.js', () => ({
|
||||
prisma: prismaMock,
|
||||
}))
|
||||
|
||||
let app: FastifyInstance
|
||||
|
||||
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'
|
||||
const { createApp } = await import('../src/app.js')
|
||||
app = createApp()
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
await app?.close()
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
prismaMock.user.findUnique.mockResolvedValue(null)
|
||||
prismaMock.user.count.mockResolvedValue(1)
|
||||
})
|
||||
|
||||
describe('prénom du compte', () => {
|
||||
it("l'inscription enregistre le prénom (sans espaces autour) et le renvoie", async () => {
|
||||
prismaMock.user.create.mockResolvedValue({ id: 'user-1', email: 'anais@example.com', firstName: 'Anaïs' })
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/auth/register',
|
||||
payload: { firstName: ' Anaïs ', email: 'anais@example.com', password: 'securepass123' },
|
||||
})
|
||||
|
||||
expect(res.statusCode).toBe(201)
|
||||
expect(prismaMock.user.create).toHaveBeenCalledWith(expect.objectContaining({
|
||||
data: expect.objectContaining({ firstName: 'Anaïs' }),
|
||||
}))
|
||||
expect(res.json().user).toEqual({ id: 'user-1', email: 'anais@example.com', firstName: 'Anaïs', hasPassword: true })
|
||||
})
|
||||
|
||||
it("l'inscription sans prénom le garde vide, sans erreur", async () => {
|
||||
prismaMock.user.create.mockResolvedValue({ id: 'user-2', email: 'sans@example.com', firstName: null })
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/auth/register',
|
||||
payload: { email: 'sans@example.com', password: 'securepass123' },
|
||||
})
|
||||
|
||||
expect(res.statusCode).toBe(201)
|
||||
expect(prismaMock.user.create).toHaveBeenCalledWith(expect.objectContaining({
|
||||
data: expect.objectContaining({ firstName: null }),
|
||||
}))
|
||||
expect(res.json().user.firstName).toBeNull()
|
||||
})
|
||||
|
||||
it('la connexion renvoie le prénom du compte', async () => {
|
||||
const { hashPassword } = await import('../src/lib/auth.js')
|
||||
prismaMock.user.findUnique.mockResolvedValue({
|
||||
id: 'user-1',
|
||||
email: 'anais@example.com',
|
||||
firstName: 'Anaïs',
|
||||
passwordHash: await hashPassword('securepass123'),
|
||||
})
|
||||
|
||||
const res = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/auth/login',
|
||||
payload: { email: 'anais@example.com', password: 'securepass123' },
|
||||
})
|
||||
|
||||
expect(res.statusCode).toBe(200)
|
||||
expect(res.json().user).toEqual({ id: 'user-1', email: 'anais@example.com', firstName: 'Anaïs', hasPassword: true })
|
||||
})
|
||||
|
||||
it('/me renvoie le profil du compte connecté, et refuse sans session', async () => {
|
||||
const { hashPassword } = await import('../src/lib/auth.js')
|
||||
prismaMock.user.findUnique.mockResolvedValue({
|
||||
id: 'user-1',
|
||||
email: 'anais@example.com',
|
||||
firstName: 'Anaïs',
|
||||
passwordHash: await hashPassword('securepass123'),
|
||||
})
|
||||
const login = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/auth/login',
|
||||
payload: { email: 'anais@example.com', password: 'securepass123' },
|
||||
})
|
||||
const token = login.json().token
|
||||
|
||||
prismaMock.user.findUnique.mockResolvedValue({ id: 'user-1', email: 'anais@example.com', firstName: 'Anaïs', passwordHash: 'hash' })
|
||||
const me = await app.inject({ method: 'GET', url: '/auth/me', headers: { authorization: `Bearer ${token}` } })
|
||||
expect(me.statusCode).toBe(200)
|
||||
expect(me.json().user).toEqual({ id: 'user-1', email: 'anais@example.com', firstName: 'Anaïs', hasPassword: true, oidcLinked: false })
|
||||
|
||||
const anonymous = await app.inject({ method: 'GET', url: '/auth/me' })
|
||||
expect(anonymous.statusCode).toBe(401)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,241 @@
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { mkdtemp, rm } from 'node:fs/promises'
|
||||
import os from 'node:os'
|
||||
import path from 'node:path'
|
||||
import { Prisma } from '../src/generated/prisma/client.js'
|
||||
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { prismaMock } = vi.hoisted(() => ({
|
||||
prismaMock: {
|
||||
// Sessions fermées (lib/token-revocation.ts), rechargées au démarrage
|
||||
revokedSession: {
|
||||
upsert: vi.fn().mockResolvedValue({}),
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
deleteMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
},
|
||||
user: {
|
||||
count: vi.fn(),
|
||||
},
|
||||
person: {
|
||||
findFirst: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
},
|
||||
treeMembership: {
|
||||
findUnique: vi.fn(),
|
||||
},
|
||||
mediaPersonTag: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
deleteMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
createMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
},
|
||||
auditLog: {
|
||||
create: vi.fn(),
|
||||
},
|
||||
$transaction: vi.fn(),
|
||||
$disconnect: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../src/lib/prisma.js', () => ({
|
||||
prisma: prismaMock,
|
||||
}))
|
||||
|
||||
let createApp: () => FastifyInstance
|
||||
let storageRoot: string
|
||||
|
||||
const TREE = 'tree-1'
|
||||
const PERSON = 'person-1'
|
||||
const url = `/trees/${TREE}/persons/${PERSON}/avatar/crop`
|
||||
|
||||
async function createUserToken(app: FastifyInstance, userId = 'user-1'): Promise<string> {
|
||||
await app.ready()
|
||||
return (app as any).jwt.sign(
|
||||
{ kind: 'user', sub: userId, jti: randomUUID(), userId, email: 'user@example.com' },
|
||||
{ expiresIn: '1h' },
|
||||
)
|
||||
}
|
||||
|
||||
function asAdmin(role: 'owner' | 'admin' | 'member' = 'owner') {
|
||||
prismaMock.treeMembership.findUnique.mockResolvedValue({ role, tree: { deletedAt: null } })
|
||||
}
|
||||
|
||||
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'
|
||||
|
||||
storageRoot = await mkdtemp(path.join(os.tmpdir(), 'parenthese-crop-'))
|
||||
process.env.MEDIA_STORAGE_PATH = storageRoot
|
||||
|
||||
const module = await import('../src/app.js')
|
||||
createApp = module.createApp
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
await rm(storageRoot, { recursive: true, force: true })
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
prismaMock.user.count.mockResolvedValue(1)
|
||||
prismaMock.person.updateMany.mockResolvedValue({ count: 1 })
|
||||
prismaMock.person.findFirst.mockResolvedValue({ avatarPath: `${TREE}/${PERSON}/avatar-a.jpg` })
|
||||
asAdmin('owner')
|
||||
})
|
||||
|
||||
describe('PUT /trees/:id/persons/:personId/avatar/crop', () => {
|
||||
it('refuse sans session', async () => {
|
||||
const app = createApp()
|
||||
const response = await app.inject({ method: 'PUT', url, payload: { crop: null } })
|
||||
expect(response.statusCode).toBe(401)
|
||||
expect(prismaMock.person.updateMany).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('réserve le cadrage aux administrateurs de l arbre, comme le changement de photo', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
asAdmin('member')
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { crop: { x: 0.4, y: 0.4, zoom: 2 } },
|
||||
})
|
||||
|
||||
expect(response.statusCode).toBe(403)
|
||||
expect(prismaMock.person.updateMany).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('refuse un cadrage hors plage ou mal formé', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
const headers = { authorization: `Bearer ${token}` }
|
||||
|
||||
const tooZoomed = await app.inject({ method: 'PUT', url, headers, payload: { crop: { x: 0.5, y: 0.5, zoom: 5 } } })
|
||||
const outside = await app.inject({ method: 'PUT', url, headers, payload: { crop: { x: 1.2, y: 0.5, zoom: 1 } } })
|
||||
const missing = await app.inject({ method: 'PUT', url, headers, payload: { crop: { x: 0.5 } } })
|
||||
const noBody = await app.inject({ method: 'PUT', url, headers, payload: {} })
|
||||
|
||||
expect(tooZoomed.statusCode).toBe(400)
|
||||
expect(outside.statusCode).toBe(400)
|
||||
expect(missing.statusCode).toBe(400)
|
||||
expect(noBody.statusCode).toBe(400)
|
||||
expect(prismaMock.person.updateMany).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('enregistre le cadrage arrondi et audite le changement', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'PUT',
|
||||
url,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { crop: { x: 0.123456, y: 0.7, zoom: 1.8 } },
|
||||
})
|
||||
|
||||
expect(response.statusCode).toBe(200)
|
||||
expect(response.json()).toEqual({ ok: true, avatarCrop: { x: 0.1235, y: 0.7, zoom: 1.8 } })
|
||||
|
||||
const call = prismaMock.person.updateMany.mock.calls[0][0]
|
||||
expect(call.where).toEqual({ id: PERSON, treeId: TREE, deletedAt: null })
|
||||
expect(call.data.avatarCrop).toEqual({ x: 0.1235, y: 0.7, zoom: 1.8 })
|
||||
// La photo elle-même n'est jamais touchée
|
||||
expect(call.data).not.toHaveProperty('avatarPath')
|
||||
expect(prismaMock.auditLog.create).toHaveBeenCalledWith({
|
||||
data: expect.objectContaining({ action: 'person_avatar_cropped', entityId: PERSON, treeId: TREE }),
|
||||
})
|
||||
})
|
||||
|
||||
it('remet le cadrage par défaut à zéro (null) plutôt que de le stocker', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
|
||||
const reset = await app.inject({
|
||||
method: 'PUT',
|
||||
url,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { crop: null },
|
||||
})
|
||||
expect(reset.statusCode).toBe(200)
|
||||
expect(prismaMock.person.updateMany.mock.calls[0][0].data.avatarCrop).toBe(Prisma.DbNull)
|
||||
|
||||
prismaMock.person.updateMany.mockClear()
|
||||
await app.inject({
|
||||
method: 'PUT',
|
||||
url,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
payload: { crop: { x: 0.5, y: 0.5, zoom: 1 } },
|
||||
})
|
||||
expect(prismaMock.person.updateMany.mock.calls[0][0].data.avatarCrop).toBe(Prisma.DbNull)
|
||||
})
|
||||
|
||||
it('garde la forme choisie, même avec un cadrage centré, et refuse une forme inconnue', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
const put = (crop: unknown) => app.inject({ method: 'PUT', url, headers: { authorization: `Bearer ${token}` }, payload: { crop } })
|
||||
|
||||
const saved = await put({ x: 0.5, y: 0.5, zoom: 1, shape: 'round' })
|
||||
expect(saved.statusCode).toBe(200)
|
||||
expect(saved.json()).toEqual({ ok: true, avatarCrop: { x: 0.5, y: 0.5, zoom: 1, shape: 'round' } })
|
||||
expect(prismaMock.person.updateMany.mock.calls[0][0].data.avatarCrop).toEqual({ x: 0.5, y: 0.5, zoom: 1, shape: 'round' })
|
||||
|
||||
expect((await put({ x: 0.5, y: 0.5, zoom: 1, shape: 'hexagone' })).statusCode).toBe(400)
|
||||
})
|
||||
|
||||
it('répond 404 sans portrait, et 409 pour un portrait venu d Immich', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
const headers = { authorization: `Bearer ${token}` }
|
||||
|
||||
prismaMock.person.findFirst.mockResolvedValueOnce({ avatarPath: null })
|
||||
const noAvatar = await app.inject({ method: 'PUT', url, headers, payload: { crop: { x: 0.4, y: 0.4, zoom: 2 } } })
|
||||
expect(noAvatar.statusCode).toBe(404)
|
||||
|
||||
prismaMock.person.findFirst.mockResolvedValueOnce({ avatarPath: `${TREE}/${PERSON}/immich-abc.jpg` })
|
||||
const fromImmich = await app.inject({ method: 'PUT', url, headers, payload: { crop: { x: 0.4, y: 0.4, zoom: 2 } } })
|
||||
expect(fromImmich.statusCode).toBe(409)
|
||||
expect(fromImmich.json()).toEqual({ error: 'avatar_from_immich' })
|
||||
expect(prismaMock.person.updateMany).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('DELETE avatar : le cadrage disparaît avec la photo', () => {
|
||||
it('remet avatarCrop à null en même temps que le portrait', async () => {
|
||||
const app = createApp()
|
||||
const token = await createUserToken(app)
|
||||
|
||||
const response = await app.inject({
|
||||
method: 'DELETE',
|
||||
url: `/trees/${TREE}/persons/${PERSON}/avatar`,
|
||||
headers: { authorization: `Bearer ${token}` },
|
||||
})
|
||||
|
||||
expect(response.statusCode).toBe(200)
|
||||
const data = prismaMock.person.updateMany.mock.calls[0][0].data
|
||||
expect(data.avatarPath).toBeNull()
|
||||
expect(data.avatarCrop).toBe(Prisma.DbNull)
|
||||
})
|
||||
})
|
||||
|
||||
describe('lecture du cadrage stocké', () => {
|
||||
it('ignore toute valeur mal formée au lieu de déformer le portrait', async () => {
|
||||
const { readAvatarCrop, toStoredAvatarCrop } = await import('../src/lib/avatar-crop.js')
|
||||
|
||||
expect(readAvatarCrop(null)).toBeNull()
|
||||
expect(readAvatarCrop('oui')).toBeNull()
|
||||
expect(readAvatarCrop({ x: 0.2, y: 0.3 })).toBeNull()
|
||||
expect(readAvatarCrop({ x: 0.2, y: 0.3, zoom: 9 })).toBeNull()
|
||||
expect(readAvatarCrop({ x: 0.2, y: 0.3, zoom: 2 })).toEqual({ x: 0.2, y: 0.3, zoom: 2 })
|
||||
|
||||
expect(toStoredAvatarCrop({ x: 0.5, y: 0.5, zoom: 1 })).toBeNull()
|
||||
expect(toStoredAvatarCrop(null)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,26 @@
|
||||
import { readFile } from 'node:fs/promises'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
import { decode, isBlurhashValid } from 'blurhash'
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { computeBlurhash } from '../src/lib/blurhash.js'
|
||||
|
||||
// Aperçu flou calculé à l'envoi d'une photo : une chaîne valide, aux couleurs de la photo
|
||||
const demo = (name: string) => fileURLToPath(new URL(`../../frontend/public/demo/${name}`, import.meta.url))
|
||||
|
||||
describe('computeBlurhash', () => {
|
||||
it('donne un aperçu valide pour une vraie photo', async () => {
|
||||
const hash = await computeBlurhash(await readFile(demo('souvenir-mariage-1918.webp')))
|
||||
expect(hash).toBeTruthy()
|
||||
expect(isBlurhashValid(hash as string).result).toBe(true)
|
||||
// 4 × 3 composantes : 4 + 2 × 4 × 3 - 2 = 28 caractères
|
||||
expect(hash).toHaveLength(28)
|
||||
// Photo en noir et blanc : l'aperçu reste gris (rouge, vert et bleu proches)
|
||||
const px = decode(hash as string, 8, 8)
|
||||
const [r, g, b] = [px[0], px[1], px[2]]
|
||||
expect(Math.max(r, g, b) - Math.min(r, g, b)).toBeLessThan(24)
|
||||
})
|
||||
|
||||
it('renvoie null pour un fichier qui n’est pas une image', async () => {
|
||||
expect(await computeBlurhash(Buffer.from('pas une image'))).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,272 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
// Co-gestion d'un arbre (#145), sur une vraie base : une fonction de droits se vérifie avec de vraies requêtes,
|
||||
// pas avec des mocks. Lancé seulement avec TEST_DATABASE_URL (base jetable, migrée, en UTF-8 pour les emoji) :
|
||||
// TEST_DATABASE_URL=postgresql://postgres:postgres@localhost:5432/genealogy_test npx vitest run test/co-gestion.db.test.ts
|
||||
const TEST_DB = process.env.TEST_DATABASE_URL
|
||||
|
||||
const { oidcMock } = vi.hoisted(() => ({ oidcMock: { startAuthorization: vi.fn(), finishAuthorization: vi.fn() } }))
|
||||
vi.mock('../src/lib/oidc.js', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('../src/lib/oidc.js')>()),
|
||||
...oidcMock,
|
||||
}))
|
||||
|
||||
const ISSUER = 'https://id.example.org'
|
||||
let app: FastifyInstance
|
||||
let env: { ALLOW_REGISTRATION: boolean; PASSWORD_LOGIN: boolean }
|
||||
let prisma: typeof import('../src/lib/prisma.js')['prisma']
|
||||
let ip = 0
|
||||
const nextIp = () => `10.1.${Math.floor(++ip / 250)}.${ip % 250 + 1}`
|
||||
const run = Date.now().toString(36)
|
||||
const mail = (name: string) => `${name}-${run}@exemple.fr`
|
||||
|
||||
async function call(method: string, url: string, token?: string, payload?: unknown) {
|
||||
const res = await app.inject({
|
||||
method: method as 'GET',
|
||||
url,
|
||||
payload: payload as Record<string, unknown>,
|
||||
headers: token ? { authorization: `Bearer ${token}` } : {},
|
||||
remoteAddress: nextIp(),
|
||||
})
|
||||
return { status: res.statusCode, body: res.body ? res.json() : null }
|
||||
}
|
||||
|
||||
async function register(name: string, extra: Record<string, unknown> = {}) {
|
||||
const res = await call('POST', '/auth/register', undefined, { email: mail(name), password: 'mot-de-passe-solide', firstName: name, ...extra })
|
||||
return res
|
||||
}
|
||||
|
||||
async function account(name: string) {
|
||||
const res = await register(name)
|
||||
expect(res.status).toBe(201)
|
||||
return { token: res.body.token as string, id: res.body.user.id as string, email: mail(name) }
|
||||
}
|
||||
|
||||
describe.skipIf(!TEST_DB)('co-gestion, vraie base', () => {
|
||||
let owner: { token: string; id: string; email: string }
|
||||
let treeId: string
|
||||
|
||||
beforeAll(async () => {
|
||||
process.env.NODE_ENV = 'test'
|
||||
process.env.DATABASE_URL = TEST_DB
|
||||
process.env.JWT_SECRET = 'test-secret-with-sufficient-length'
|
||||
process.env.CORS_ORIGIN = 'http://localhost:5173'
|
||||
process.env.OIDC_ISSUER = ISSUER
|
||||
process.env.OIDC_CLIENT_ID = 'parenthese'
|
||||
process.env.OIDC_CLIENT_SECRET = 'secret'
|
||||
process.env.OIDC_REDIRECT_URI = 'https://arbre.example.org/auth/oidc/callback'
|
||||
;({ env } = await import('../src/config/env.js'))
|
||||
;({ prisma } = await import('../src/lib/prisma.js'))
|
||||
const { createApp } = await import('../src/app.js')
|
||||
app = createApp()
|
||||
env.ALLOW_REGISTRATION = true
|
||||
owner = await account('proprio')
|
||||
const tree = await call('POST', '/trees', owner.token, { name: 'Arbre de démo', slug: `demo-${run}`, visitorPassword: 'partage-demo-1', contributorPassword: 'partage-demo-1' })
|
||||
expect(tree.status).toBe(201)
|
||||
treeId = tree.body.tree?.id ?? tree.body.id
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
env.ALLOW_REGISTRATION = true
|
||||
env.PASSWORD_LOGIN = true
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
await app?.close()
|
||||
})
|
||||
|
||||
async function invite(email: string) {
|
||||
const res = await call('POST', `/trees/${treeId}/invitations`, owner.token, { email })
|
||||
expect(res.status).toBe(201)
|
||||
return res.body as { token: string; invitation: { id: string } }
|
||||
}
|
||||
|
||||
it("un compte sans lien avec l'arbre ne voit ni ne change les gestionnaires", async () => {
|
||||
const stranger = await account('inconnu')
|
||||
expect((await call('GET', `/trees/${treeId}/managers`, stranger.token)).status).toBe(403)
|
||||
expect((await call('POST', `/trees/${treeId}/invitations`, stranger.token, { email: stranger.email })).status).toBe(403)
|
||||
expect((await call('DELETE', `/trees/${treeId}/managers/${owner.id}`, stranger.token)).status).toBe(403)
|
||||
expect((await call('GET', `/trees/${treeId}/managers`)).status).toBe(401)
|
||||
})
|
||||
|
||||
it("le lien n'ouvre rien au mauvais compte, ne sert qu'une fois, et donne les droits d'administration", async () => {
|
||||
const coEmail = mail('cogest')
|
||||
const { token, invitation } = await invite(coEmail)
|
||||
|
||||
const preview = await call('GET', `/invitations/${token}`)
|
||||
expect(preview.status).toBe(200)
|
||||
expect(preview.body.treeName).toBe('Arbre de démo')
|
||||
expect(preview.body.emailHint).not.toContain(coEmail.split('@')[0])
|
||||
|
||||
// Le lien entre de mauvaises mains : un compte à une autre adresse ne l'accepte pas
|
||||
const thief = await account('voleur')
|
||||
expect((await call('POST', `/invitations/${token}/accept`, thief.token)).body.error).toBe('invitation_email_mismatch')
|
||||
expect((await call('PATCH', `/trees/${treeId}`, thief.token, { name: 'Volé' })).status).toBe(403)
|
||||
|
||||
const co = await account('cogest')
|
||||
const accepted = await call('POST', `/invitations/${token}/accept`, co.token)
|
||||
expect(accepted.status).toBe(200)
|
||||
expect(accepted.body).toEqual({ treeId, role: 'admin' })
|
||||
expect((await call('POST', `/invitations/${token}/accept`, co.token)).status).toBe(404)
|
||||
expect((await call('GET', `/invitations/${token}`)).body).toEqual({ error: 'invitation_used' })
|
||||
expect((await prisma.treeInvitation.findUnique({ where: { id: invitation.id } }))?.acceptedUserId).toBe(co.id)
|
||||
|
||||
// Co-gestionnaire : modifie l'arbre, voit la liste, mais n'invite pas, ne retire personne, ne supprime pas l'arbre
|
||||
expect((await call('PATCH', `/trees/${treeId}`, co.token, { description: 'Par la co-gestionnaire' })).status).toBe(200)
|
||||
const list = await call('GET', `/trees/${treeId}/managers`, co.token)
|
||||
expect(list.body.canManage).toBe(false)
|
||||
expect(list.body.managers.map((m: { role: string }) => m.role).sort()).toEqual(['admin', 'owner'])
|
||||
expect((await call('POST', `/trees/${treeId}/invitations`, co.token, { email: mail('autre') })).status).toBe(403)
|
||||
expect((await call('DELETE', `/trees/${treeId}/managers/${owner.id}`, co.token)).status).toBe(403)
|
||||
expect((await call('DELETE', `/trees/${treeId}`, co.token, { confirmName: 'Arbre de démo' })).status).toBe(403)
|
||||
|
||||
// Le propriétaire le retire : son jeton de session ne sert plus à rien sur l'arbre, tout de suite
|
||||
expect((await call('DELETE', `/trees/${treeId}/managers/${co.id}`, owner.token)).status).toBe(200)
|
||||
expect((await call('PATCH', `/trees/${treeId}`, co.token, { description: 'Encore moi' })).status).toBe(403)
|
||||
expect((await call('GET', `/trees/${treeId}/managers`, co.token)).status).toBe(403)
|
||||
})
|
||||
|
||||
it('un co-gestionnaire quitte seul, et ne retire jamais un autre co-gestionnaire', async () => {
|
||||
const a = await account('gestion-a')
|
||||
const b = await account('gestion-b')
|
||||
for (const who of [a, b]) {
|
||||
const { token } = await invite(who.email)
|
||||
expect((await call('POST', `/invitations/${token}/accept`, who.token)).status).toBe(200)
|
||||
}
|
||||
expect((await call('DELETE', `/trees/${treeId}/managers/${b.id}`, a.token)).status).toBe(403)
|
||||
expect((await call('DELETE', `/trees/${treeId}/managers/${a.id}`, a.token)).status).toBe(200)
|
||||
expect((await call('PATCH', `/trees/${treeId}`, a.token, { description: 'x' })).status).toBe(403)
|
||||
expect((await call('PATCH', `/trees/${treeId}`, b.token, { description: 'y' })).status).toBe(200)
|
||||
// Le propriétaire ne se retire pas lui-même
|
||||
expect((await call('DELETE', `/trees/${treeId}/managers/${owner.id}`, owner.token)).status).toBe(403)
|
||||
await call('DELETE', `/trees/${treeId}/managers/${b.id}`, owner.token)
|
||||
})
|
||||
|
||||
it('« Copier le lien » remplace le lien ; annulé ou expiré, il ne sert plus', async () => {
|
||||
const email = mail('rotation')
|
||||
const first = await invite(email)
|
||||
const rotated = await call('POST', `/trees/${treeId}/invitations/${first.invitation.id}/link`, owner.token)
|
||||
expect(rotated.status).toBe(200)
|
||||
expect((await call('GET', `/invitations/${first.token}`)).status).toBe(404)
|
||||
expect((await call('GET', `/invitations/${rotated.body.token}`)).status).toBe(200)
|
||||
|
||||
expect((await call('DELETE', `/trees/${treeId}/invitations/${first.invitation.id}`, owner.token)).status).toBe(200)
|
||||
const user = await account('rotation')
|
||||
expect((await call('POST', `/invitations/${rotated.body.token}/accept`, user.token)).status).toBe(404)
|
||||
|
||||
const late = await invite(email)
|
||||
await prisma.treeInvitation.update({ where: { id: late.invitation.id }, data: { expiresAt: new Date(Date.now() - 1000) } })
|
||||
expect((await call('POST', `/invitations/${late.token}/accept`, user.token)).status).toBe(404)
|
||||
expect((await call('GET', `/invitations/${late.token}`)).body).toEqual({ error: 'invitation_expired' })
|
||||
expect((await call('GET', `/invitations/${rotated.body.token}`)).body).toEqual({ error: 'invitation_invalid' })
|
||||
})
|
||||
|
||||
it("inscription fermée : l'invitation ouvre un compte, à l'adresse invitée seulement", async () => {
|
||||
const email = mail('ferme')
|
||||
const { token } = await invite(email)
|
||||
env.ALLOW_REGISTRATION = false
|
||||
|
||||
expect((await register('sans-invitation')).body.error).toBe('registration_closed')
|
||||
expect((await register('autre-adresse', { invitationToken: token })).body.error).toBe('invitation_email_mismatch')
|
||||
expect((await register('x', { invitationToken: 'faux-jeton' })).status).toBe(410)
|
||||
|
||||
const created = await register('ferme', { invitationToken: token })
|
||||
expect(created.status).toBe(201)
|
||||
expect(created.body.joinedTreeId).toBe(treeId)
|
||||
expect((await call('PATCH', `/trees/${treeId}`, created.body.token, { description: 'z' })).status).toBe(200)
|
||||
// Le lien a servi : il n'ouvre pas un second compte
|
||||
expect((await call('POST', '/auth/register', undefined, { email: mail('ferme2'), password: 'mot-de-passe-solide', invitationToken: token })).status).toBe(410)
|
||||
await call('DELETE', `/trees/${treeId}/managers/${created.body.user.id}`, owner.token)
|
||||
})
|
||||
|
||||
it("un co-gestionnaire n'utilise jamais Immich, qui passe par la clé du propriétaire", async () => {
|
||||
const co = await account('immich')
|
||||
const { token } = await invite(co.email)
|
||||
expect((await call('POST', `/invitations/${token}/accept`, co.token)).status).toBe(200)
|
||||
const config = await call('GET', `/trees/${treeId}/immich/config`, co.token)
|
||||
expect(config.status).toBe(200)
|
||||
expect(config.body).toEqual({ config: null, instances: [], ownerOnly: true })
|
||||
for (const url of ['/immich/assets?page=1&q=plage', '/immich/people', '/immich/status', '/immich/assets/3f2a1b4c-5d6e-4f70-8a9b-0c1d2e3f4a5b/thumbnail', '/immich/thumbnail/3f2a1b4c-5d6e-4f70-8a9b-0c1d2e3f4a5b']) {
|
||||
expect((await call('GET', `/trees/${treeId}${url}`, co.token)).status).toBe(403)
|
||||
}
|
||||
expect((await call('PUT', `/trees/${treeId}/immich/config`, co.token, { instanceId: '0123456789abcdef', apiKey: 'y' })).status).toBe(403)
|
||||
expect((await call('DELETE', `/trees/${treeId}/immich/config`, co.token)).status).toBe(403)
|
||||
await call('DELETE', `/trees/${treeId}/managers/${co.id}`, owner.token)
|
||||
})
|
||||
|
||||
it("retiré, un co-gestionnaire qui avait ouvert l'arbre par le mot de passe de partage ne le lit plus", async () => {
|
||||
const co = await account('partage')
|
||||
const unlocked = await call('POST', `/trees/${treeId}/access/unlock`, co.token, { password: 'partage-demo-1' })
|
||||
expect(unlocked.status).toBe(200)
|
||||
expect((await call('GET', `/trees/${treeId}/graph`, co.token)).status).toBe(200)
|
||||
const { token } = await invite(co.email)
|
||||
expect((await call('POST', `/invitations/${token}/accept`, co.token)).status).toBe(200)
|
||||
expect((await call('DELETE', `/trees/${treeId}/managers/${co.id}`, owner.token)).status).toBe(200)
|
||||
expect((await call('GET', `/trees/${treeId}/graph`, co.token)).status).toBe(403)
|
||||
})
|
||||
|
||||
it("l'icône de l'arbre : un emoji ou rien, posée par un gestionnaire, rendue dans la liste des arbres", async () => {
|
||||
expect((await call('PATCH', `/trees/${treeId}`, owner.token, { icon: 'abc' })).status).toBe(400)
|
||||
expect((await call('PATCH', `/trees/${treeId}`, owner.token, { icon: '🌳' })).status).toBe(200)
|
||||
const list = await call('GET', '/trees', owner.token)
|
||||
expect(list.body.trees.find((t: { id: string }) => t.id === treeId).icon).toBe('🌳')
|
||||
expect((await call('PATCH', `/trees/${treeId}`, owner.token, { icon: null })).status).toBe(200)
|
||||
})
|
||||
|
||||
describe('OIDC', () => {
|
||||
let address = 0
|
||||
async function oidcLogin(identity: { subject: string; email: string; emailVerified: boolean }) {
|
||||
const remoteAddress = `10.9.0.${++address}`
|
||||
oidcMock.startAuthorization.mockImplementation(async (returnTo: string) => ({
|
||||
url: new URL(`${ISSUER}/authorize?state=s`),
|
||||
pending: { state: 's', nonce: 'n', codeVerifier: 'v'.repeat(43), returnTo },
|
||||
}))
|
||||
oidcMock.finishAuthorization.mockResolvedValue({ issuer: ISSUER, firstName: null, ...identity })
|
||||
const start = await app.inject({ method: 'GET', url: '/auth/oidc/start?returnTo=/', remoteAddress })
|
||||
const cookie = String(start.headers['set-cookie']).split(';')[0]
|
||||
const back = await app.inject({ method: 'GET', url: '/auth/oidc/callback?code=c&state=s', headers: { cookie }, remoteAddress })
|
||||
return new URLSearchParams(String(back.headers.location).split('#')[1] ?? '')
|
||||
}
|
||||
|
||||
it("email vérifié par le fournisseur : rattaché sans le lien, même inscription fermée", async () => {
|
||||
const email = mail('oidc-ok')
|
||||
await invite(email)
|
||||
env.ALLOW_REGISTRATION = false
|
||||
const fragment = await oidcLogin({ subject: `sub-ok-${run}`, email, emailVerified: true })
|
||||
expect(fragment.get('oidc')).toBeTruthy()
|
||||
const user = await prisma.user.findUnique({ where: { email }, select: { id: true } })
|
||||
const membership = await prisma.treeMembership.findUnique({ where: { treeId_userId: { treeId, userId: user!.id } } })
|
||||
expect(membership?.role).toBe('admin')
|
||||
})
|
||||
|
||||
it("email non vérifié : jamais rattaché, et pas de compte sur une instance fermée", async () => {
|
||||
const email = mail('oidc-non-verifie')
|
||||
await invite(email)
|
||||
env.ALLOW_REGISTRATION = false
|
||||
const fragment = await oidcLogin({ subject: `sub-nv-${run}`, email, emailVerified: false })
|
||||
expect(fragment.get('oidc_error')).toBe('oidc_email_unverified')
|
||||
expect(await prisma.user.findUnique({ where: { email } })).toBeNull()
|
||||
})
|
||||
|
||||
it("identité déjà reliée dont l'email a changé chez le fournisseur : pas d'invitation prise sans le lien", async () => {
|
||||
const subject = `sub-change-${run}`
|
||||
expect((await oidcLogin({ subject, email: mail('avant'), emailVerified: true })).get('oidc')).toBeTruthy()
|
||||
const target = mail('cible')
|
||||
await invite(target)
|
||||
expect((await oidcLogin({ subject, email: target, emailVerified: true })).get('oidc')).toBeTruthy()
|
||||
const user = await prisma.user.findUnique({ where: { email: mail('avant') }, select: { id: true } })
|
||||
expect(await prisma.treeMembership.findUnique({ where: { treeId_userId: { treeId, userId: user!.id } } })).toBeNull()
|
||||
})
|
||||
|
||||
it("email non vérifié sur un compte déjà relié : l'invitation reste en attente", async () => {
|
||||
const email = mail('oidc-relie')
|
||||
const subject = `sub-relie-${run}`
|
||||
expect((await oidcLogin({ subject, email, emailVerified: true })).get('oidc')).toBeTruthy()
|
||||
await invite(email)
|
||||
expect((await oidcLogin({ subject, email, emailVerified: false })).get('oidc')).toBeTruthy()
|
||||
const user = await prisma.user.findUnique({ where: { email }, select: { id: true } })
|
||||
expect(await prisma.treeMembership.findUnique({ where: { treeId_userId: { treeId, userId: user!.id } } })).toBeNull()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -4,10 +4,16 @@ import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { prismaMock } = vi.hoisted(() => ({
|
||||
prismaMock: {
|
||||
// Sessions fermées (lib/token-revocation.ts), rechargées au démarrage
|
||||
revokedSession: {
|
||||
upsert: vi.fn().mockResolvedValue({}),
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
deleteMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
},
|
||||
user: {
|
||||
findUnique: vi.fn(),
|
||||
count: vi.fn(),
|
||||
@@ -28,6 +34,9 @@ const { prismaMock } = vi.hoisted(() => ({
|
||||
contributionSession: {
|
||||
updateMany: vi.fn(),
|
||||
},
|
||||
treeVisit: {
|
||||
updateMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
},
|
||||
$transaction: vi.fn(),
|
||||
$disconnect: vi.fn(),
|
||||
},
|
||||
@@ -50,6 +59,7 @@ let storageRoot = ''
|
||||
let passwordHash = ''
|
||||
let createApp: () => FastifyInstance
|
||||
let resolveTreeMediaDirectory: (treeId: string, root?: string) => string | null
|
||||
let env: { PASSWORD_LOGIN: boolean }
|
||||
|
||||
function applyTestEnv(): void {
|
||||
process.env.NODE_ENV = 'test'
|
||||
@@ -94,6 +104,7 @@ beforeAll(async () => {
|
||||
|
||||
createApp = (await import('../src/app.js')).createApp
|
||||
resolveTreeMediaDirectory = (await import('../src/lib/tree-purge.js')).resolveTreeMediaDirectory
|
||||
;({ env } = await import('../src/config/env.js'))
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
@@ -152,6 +163,138 @@ describe('DELETE /auth/me', () => {
|
||||
await app.close()
|
||||
})
|
||||
|
||||
describe("compte sans mot de passe (né d'une connexion OIDC)", () => {
|
||||
const signedAt = async (app: FastifyInstance, minutesAgo: number) => {
|
||||
await app.ready()
|
||||
return (app as any).jwt.sign({
|
||||
kind: 'user', sub: 'user-1', jti: randomUUID(), userId: 'user-1', email: 'user@example.com',
|
||||
iat: Math.floor(Date.now() / 1000) - minutesAgo * 60,
|
||||
}, { expiresIn: '1h' })
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
prismaMock.user.findUnique.mockResolvedValue({ id: 'user-1', email: 'user@example.com', passwordHash: null })
|
||||
})
|
||||
|
||||
it('se supprime avec son email retapé, juste après une connexion', async () => {
|
||||
const app = createApp()
|
||||
const response = await app.inject({
|
||||
method: 'DELETE', url: '/auth/me',
|
||||
headers: { authorization: `Bearer ${await signedAt(app, 2)}` },
|
||||
payload: { confirmEmail: ' User@Example.com ' },
|
||||
})
|
||||
expect(response.statusCode).toBe(200)
|
||||
expect(prismaMock.user.delete).toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('refuse un autre email', async () => {
|
||||
const app = createApp()
|
||||
const response = await app.inject({
|
||||
method: 'DELETE', url: '/auth/me',
|
||||
headers: { authorization: `Bearer ${await signedAt(app, 2)}` },
|
||||
payload: { confirmEmail: 'autre@example.com' },
|
||||
})
|
||||
expect(response.statusCode).toBe(403)
|
||||
expect(response.json()).toEqual({ error: 'invalid_password' })
|
||||
expect(prismaMock.user.delete).not.toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('refuse une session de plus de 15 minutes, même avec le bon email', async () => {
|
||||
const app = createApp()
|
||||
const response = await app.inject({
|
||||
method: 'DELETE', url: '/auth/me',
|
||||
headers: { authorization: `Bearer ${await signedAt(app, 20)}` },
|
||||
payload: { confirmEmail: 'user@example.com' },
|
||||
})
|
||||
expect(response.statusCode).toBe(403)
|
||||
expect(response.json()).toEqual({ error: 'recent_sign_in_required' })
|
||||
expect(prismaMock.user.delete).not.toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it("n'accepte pas un email à la place du mot de passe pour un compte qui en a un", async () => {
|
||||
prismaMock.user.findUnique.mockResolvedValue({ id: 'user-1', email: 'user@example.com', passwordHash })
|
||||
const app = createApp()
|
||||
const response = await app.inject({
|
||||
method: 'DELETE', url: '/auth/me',
|
||||
headers: { authorization: `Bearer ${await signedAt(app, 2)}` },
|
||||
payload: { confirmEmail: 'user@example.com' },
|
||||
})
|
||||
expect(response.statusCode).toBe(403)
|
||||
expect(prismaMock.user.delete).not.toHaveBeenCalled()
|
||||
await app.close()
|
||||
}, 15000)
|
||||
})
|
||||
|
||||
describe('compte à mot de passe relié à OIDC, connexion par mot de passe fermée (PASSWORD_LOGIN=false)', () => {
|
||||
const signedAt = async (app: FastifyInstance, minutesAgo: number) => {
|
||||
await app.ready()
|
||||
return (app as any).jwt.sign({
|
||||
kind: 'user', sub: 'user-1', jti: randomUUID(), userId: 'user-1', email: 'user@example.com',
|
||||
iat: Math.floor(Date.now() / 1000) - minutesAgo * 60,
|
||||
}, { expiresIn: '1h' })
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
env.PASSWORD_LOGIN = false
|
||||
prismaMock.user.findUnique.mockResolvedValue({ id: 'user-1', email: 'user@example.com', passwordHash })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
env.PASSWORD_LOGIN = true
|
||||
})
|
||||
|
||||
it('se supprime avec son email retapé, juste après une connexion (le mot de passe ne peut plus servir)', async () => {
|
||||
const app = createApp()
|
||||
const response = await app.inject({
|
||||
method: 'DELETE', url: '/auth/me',
|
||||
headers: { authorization: `Bearer ${await signedAt(app, 2)}` },
|
||||
payload: { confirmEmail: 'user@example.com' },
|
||||
})
|
||||
expect(response.statusCode).toBe(200)
|
||||
expect(prismaMock.user.delete).toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('refuse une session de plus de 15 minutes, même avec le bon email', async () => {
|
||||
const app = createApp()
|
||||
const response = await app.inject({
|
||||
method: 'DELETE', url: '/auth/me',
|
||||
headers: { authorization: `Bearer ${await signedAt(app, 20)}` },
|
||||
payload: { confirmEmail: 'user@example.com' },
|
||||
})
|
||||
expect(response.statusCode).toBe(403)
|
||||
expect(response.json()).toEqual({ error: 'recent_sign_in_required' })
|
||||
expect(prismaMock.user.delete).not.toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('refuse un autre email', async () => {
|
||||
const app = createApp()
|
||||
const response = await app.inject({
|
||||
method: 'DELETE', url: '/auth/me',
|
||||
headers: { authorization: `Bearer ${await signedAt(app, 2)}` },
|
||||
payload: { confirmEmail: 'autre@example.com' },
|
||||
})
|
||||
expect(response.statusCode).toBe(403)
|
||||
expect(prismaMock.user.delete).not.toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('dit à l’écran de demander l’email, pas un mot de passe (hasPassword=false)', async () => {
|
||||
const app = createApp()
|
||||
const response = await app.inject({
|
||||
method: 'GET', url: '/auth/me',
|
||||
headers: { authorization: `Bearer ${await signedAt(app, 2)}` },
|
||||
})
|
||||
expect(response.statusCode).toBe(200)
|
||||
expect(response.json().user.hasPassword).toBe(false)
|
||||
await app.close()
|
||||
})
|
||||
})
|
||||
|
||||
it('rejects a wrong password without deleting anything', async () => {
|
||||
const ownedFile = await writeMediaFile('tree-owned', 'person-1/photo.jpg')
|
||||
const app = createApp()
|
||||
@@ -214,6 +357,10 @@ describe('DELETE /auth/me', () => {
|
||||
where: { submittedByUserId: 'user-1' },
|
||||
data: { submittedByLabel: 'Contributeur' },
|
||||
})
|
||||
// Ses visites d'autres arbres restent comptées, sans son identifiant
|
||||
const visitUpdate = prismaMock.treeVisit.updateMany.mock.calls[0][0]
|
||||
expect(visitUpdate.where).toEqual({ visitorKey: 'user:user-1' })
|
||||
expect(visitUpdate.data.visitorKey).toMatch(/^[0-9a-f]{32}$/)
|
||||
expect(prismaMock.user.delete).toHaveBeenCalledWith({ where: { id: 'user-1' } })
|
||||
|
||||
// Les arbres doivent partir avant l'utilisateur (relation propriétaire en Restrict).
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { personPrecisionResets, unionPrecisionResets } from '../src/lib/date-precision'
|
||||
|
||||
const d = (iso: string) => new Date(`${iso}T00:00:00.000Z`)
|
||||
|
||||
describe('précision d’une date corrigée à la main', () => {
|
||||
const current = { birthDate: d('1879-01-01'), deathDate: d('1950-05-02') }
|
||||
|
||||
it('une date changée perd sa précision, une date renvoyée telle quelle la garde', () => {
|
||||
expect(personPrecisionResets(current, { birthDate: d('1880-03-12'), deathDate: d('1950-05-02') }))
|
||||
.toEqual({ birthDatePrecision: null, birthDateEnd: null })
|
||||
expect(personPrecisionResets(current, { birthDate: d('1879-01-01') })).toEqual({})
|
||||
expect(personPrecisionResets(current, { deathDate: null })).toEqual({ deathDatePrecision: null, deathDateEnd: null })
|
||||
expect(personPrecisionResets(current, {})).toEqual({})
|
||||
})
|
||||
|
||||
it('mariage', () => {
|
||||
expect(unionPrecisionResets({ startDate: d('1905-01-01') }, { startDate: d('1906-01-01') })).toEqual({ startDatePrecision: null })
|
||||
expect(unionPrecisionResets({ startDate: d('1905-01-01') }, { startDate: d('1905-01-01') })).toEqual({})
|
||||
expect(unionPrecisionResets({ startDate: d('1905-01-01') }, {})).toEqual({})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,79 @@
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
||||
|
||||
// Une session fermée reste fermée après un redémarrage de l'API (un déploiement), sur une vraie base. Avant, la
|
||||
// déconnexion ne vivait qu'en mémoire et le jeton redevenait valable jusqu'à 7 jours. Lancé seulement avec
|
||||
// TEST_DATABASE_URL (base jetable, migrée) :
|
||||
// TEST_DATABASE_URL=postgresql://postgres:postgres@localhost:5432/genealogy_test npx vitest run test/deconnexion.db.test.ts
|
||||
const TEST_DB = process.env.TEST_DATABASE_URL
|
||||
|
||||
let app: FastifyInstance
|
||||
let ip = 0
|
||||
const nextIp = () => `10.5.${Math.floor(++ip / 250)}.${ip % 250 + 1}`
|
||||
const run = Date.now().toString(36)
|
||||
|
||||
async function call(method: string, url: string, token?: string, payload?: unknown) {
|
||||
const res = await app.inject({
|
||||
method: method as 'GET',
|
||||
url,
|
||||
payload: payload as Record<string, unknown>,
|
||||
headers: token ? { authorization: `Bearer ${token}` } : {},
|
||||
remoteAddress: nextIp(),
|
||||
})
|
||||
return { status: res.statusCode, body: res.body ? res.json() : null }
|
||||
}
|
||||
|
||||
// Nouveau processus : la mémoire des déconnexions repart de zéro, puis l'API la recharge depuis la base
|
||||
async function restart() {
|
||||
await app.close()
|
||||
const { forgetRevokedTokensInMemory } = await import('../src/lib/token-revocation.js')
|
||||
forgetRevokedTokensInMemory()
|
||||
const { createApp } = await import('../src/app.js')
|
||||
app = createApp()
|
||||
await app.ready()
|
||||
}
|
||||
|
||||
async function login(name: string) {
|
||||
const email = `${name}-${run}@exemple.fr`
|
||||
const reg = await call('POST', '/auth/register', undefined, { email, password: 'mot-de-passe-solide', firstName: name })
|
||||
expect(reg.status).toBe(201)
|
||||
return reg.body.token as string
|
||||
}
|
||||
|
||||
describe.skipIf(!TEST_DB)('déconnexion durable, vraie base', () => {
|
||||
beforeAll(async () => {
|
||||
process.env.NODE_ENV = 'test'
|
||||
process.env.DATABASE_URL = TEST_DB
|
||||
process.env.JWT_SECRET = 'test-secret-with-sufficient-length'
|
||||
process.env.CORS_ORIGIN = 'http://localhost:5173'
|
||||
const { env } = await import('../src/config/env.js')
|
||||
env.ALLOW_REGISTRATION = true
|
||||
const { createApp } = await import('../src/app.js')
|
||||
app = createApp()
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
await app?.close()
|
||||
})
|
||||
|
||||
it('un jeton déconnecté reste refusé après un redémarrage', async () => {
|
||||
const token = await login('deconnecte')
|
||||
const other = await login('reste')
|
||||
expect((await call('GET', '/auth/me', token)).status).toBe(200)
|
||||
expect((await call('POST', '/auth/logout', token)).status).toBe(200)
|
||||
expect((await call('GET', '/auth/me', token)).status).toBe(401)
|
||||
|
||||
await restart()
|
||||
expect((await call('GET', '/auth/me', token)).status).toBe(401)
|
||||
// Une autre session, jamais fermée, passe toujours
|
||||
expect((await call('GET', '/auth/me', other)).status).toBe(200)
|
||||
})
|
||||
|
||||
it('une déconnexion expirée est effacée au démarrage', async () => {
|
||||
const { prisma } = await import('../src/lib/prisma.js')
|
||||
const jti = `expire-${run}`
|
||||
await prisma.revokedSession.create({ data: { jti, expiresAt: new Date(Date.now() - 1000) } })
|
||||
await restart()
|
||||
expect(await prisma.revokedSession.findUnique({ where: { jti } })).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -14,6 +14,12 @@ import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { prismaMock } = vi.hoisted(() => ({
|
||||
prismaMock: {
|
||||
// Sessions fermées (lib/token-revocation.ts), rechargées au démarrage
|
||||
revokedSession: {
|
||||
upsert: vi.fn().mockResolvedValue({}),
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
deleteMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
},
|
||||
user: {
|
||||
findUnique: vi.fn(),
|
||||
count: vi.fn().mockResolvedValue(1),
|
||||
@@ -77,6 +83,11 @@ const { prismaMock } = vi.hoisted(() => ({
|
||||
update: vi.fn(),
|
||||
updateMany: vi.fn(),
|
||||
},
|
||||
lifeEvent: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
createMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
updateMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
},
|
||||
annotation: {
|
||||
findMany: vi.fn(),
|
||||
},
|
||||
@@ -91,6 +102,11 @@ const { prismaMock } = vi.hoisted(() => ({
|
||||
create: vi.fn(),
|
||||
update: vi.fn(),
|
||||
},
|
||||
mediaPersonTag: {
|
||||
findMany: vi.fn().mockResolvedValue([]),
|
||||
deleteMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
createMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
},
|
||||
auditLog: {
|
||||
create: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
@@ -273,6 +289,7 @@ describe('Journey 1 — Owner creates account, tree, and adds family', () => {
|
||||
},
|
||||
})
|
||||
expect(addSelfRes.statusCode).toBe(201)
|
||||
expect(prismaMock.person.create.mock.calls.at(-1)[0].data).toMatchObject({ sex: 'male' })
|
||||
|
||||
// Step 4: Add parent
|
||||
prismaMock.person.create.mockResolvedValue({ id: 'person-2', firstName: 'Jean', lastName: 'Martin' })
|
||||
@@ -729,3 +746,127 @@ describe('Journey 4 — Admin reviews a contribution session', () => {
|
||||
await app.close()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Surnom (nickname) proposé par un contributeur', () => {
|
||||
it('soumis en attente, puis appliqué par le propriétaire avec la valeur nettoyée', async () => {
|
||||
const app = createApp()
|
||||
await app.ready()
|
||||
|
||||
const contributorToken = (app as any).jwt.sign({
|
||||
kind: 'tree_access',
|
||||
sub: 'tree:tree-1:contributor',
|
||||
treeId: 'tree-1',
|
||||
role: 'contributor',
|
||||
accessVersion: new Date('2026-02-11T10:00:00.000Z').getTime(),
|
||||
})
|
||||
prismaMock.tree.findFirst.mockResolvedValue({ id: 'tree-1', deletedAt: null, settings: { contributorPolicy: 'pending' } })
|
||||
|
||||
const submitRes = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/trees/tree-1/contributions/sessions',
|
||||
headers: { authorization: `Bearer ${contributorToken}` },
|
||||
payload: {
|
||||
title: 'Surnom de Robert',
|
||||
submittedByLabel: 'Jeanette Martin',
|
||||
changes: [
|
||||
{
|
||||
entityType: 'person',
|
||||
action: 'update',
|
||||
entityId: 'person-1',
|
||||
before: { nickname: null },
|
||||
after: { nickname: ' Loulou ' },
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
expect(submitRes.statusCode).toBe(201)
|
||||
expect(submitRes.json().session.status).toBe('pending')
|
||||
|
||||
const adminToken = (app as any).jwt.sign(
|
||||
{ kind: 'user', sub: 'user-1', jti: randomUUID(), userId: 'user-1', email: 'owner@example.com' },
|
||||
{ expiresIn: '1h' },
|
||||
)
|
||||
prismaMock.contributionSession.findFirst.mockResolvedValue({
|
||||
id: 'session-n',
|
||||
treeId: 'tree-1',
|
||||
status: 'pending',
|
||||
title: 'Surnom de Robert',
|
||||
changes: [
|
||||
{
|
||||
id: 'change-n',
|
||||
entityType: 'person',
|
||||
action: 'update',
|
||||
entityId: 'person-1',
|
||||
beforeJson: { nickname: null },
|
||||
afterJson: { nickname: ' Loulou ' },
|
||||
conflictState: 'none',
|
||||
},
|
||||
],
|
||||
})
|
||||
prismaMock.person.findFirst.mockResolvedValue({ id: 'person-1', treeId: 'tree-1', firstName: 'Robert', lastName: 'Dupont', nickname: null, deletedAt: null })
|
||||
|
||||
const reviewRes = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/trees/tree-1/contributions/sessions/session-n/review',
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { decision: 'approved' },
|
||||
})
|
||||
expect(reviewRes.statusCode).toBe(200)
|
||||
expect(reviewRes.json().approvedCount).toBe(1)
|
||||
expect(prismaMock.person.updateMany.mock.calls.at(-1)[0].data).toMatchObject({ nickname: 'Loulou' })
|
||||
|
||||
await app.close()
|
||||
})
|
||||
})
|
||||
|
||||
describe('Sexe proposé par un contributeur (issue #114)', () => {
|
||||
it('appliqué par le propriétaire avec la valeur normalisée', async () => {
|
||||
const app = createApp()
|
||||
await app.ready()
|
||||
|
||||
const adminToken = (app as any).jwt.sign(
|
||||
{ kind: 'user', sub: 'user-1', jti: randomUUID(), userId: 'user-1', email: 'owner@example.com' },
|
||||
{ expiresIn: '1h' },
|
||||
)
|
||||
prismaMock.contributionSession.findFirst.mockResolvedValue({
|
||||
id: 'session-s',
|
||||
treeId: 'tree-1',
|
||||
status: 'pending',
|
||||
title: 'Sexe de Camille',
|
||||
changes: [
|
||||
{
|
||||
id: 'change-s1',
|
||||
entityType: 'person',
|
||||
action: 'update',
|
||||
entityId: 'person-1',
|
||||
beforeJson: { sex: null },
|
||||
afterJson: { sex: 'F' },
|
||||
conflictState: 'none',
|
||||
},
|
||||
{
|
||||
id: 'change-s2',
|
||||
entityType: 'person',
|
||||
action: 'create',
|
||||
entityId: null,
|
||||
beforeJson: null,
|
||||
afterJson: { firstName: 'Léon', lastName: 'Martin', sex: 'male' },
|
||||
conflictState: 'none',
|
||||
},
|
||||
],
|
||||
})
|
||||
prismaMock.person.findFirst.mockResolvedValue({ id: 'person-1', treeId: 'tree-1', firstName: 'Camille', lastName: 'Martin', sex: null, deletedAt: null })
|
||||
|
||||
const reviewRes = await app.inject({
|
||||
method: 'POST',
|
||||
url: '/trees/tree-1/contributions/sessions/session-s/review',
|
||||
headers: { authorization: `Bearer ${adminToken}` },
|
||||
payload: { decision: 'approved' },
|
||||
})
|
||||
expect(reviewRes.statusCode).toBe(200)
|
||||
expect(reviewRes.json().approvedCount).toBe(2)
|
||||
expect(prismaMock.person.updateMany.mock.calls.at(-1)[0].data).toMatchObject({ sex: 'female' })
|
||||
expect(prismaMock.person.create.mock.calls.at(-1)[0].data).toMatchObject({ sex: 'male' })
|
||||
|
||||
await app.close()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,58 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { parseGedcomDate } from '../src/lib/gedcom-dates'
|
||||
|
||||
const iso = (value: string) => parseGedcomDate(value)?.iso ?? null
|
||||
|
||||
describe('dates GEDCOM', () => {
|
||||
it('dates simples', () => {
|
||||
expect(iso('15 JAN 1900')).toBe('1900-01-15')
|
||||
expect(iso('JAN 1900')).toBe('1900-01')
|
||||
expect(iso('1900')).toBe('1900')
|
||||
expect(iso('856')).toBe('0856')
|
||||
expect(iso('3 mar 1879')).toBe('1879-03-03')
|
||||
})
|
||||
|
||||
it('précision gardée', () => {
|
||||
expect(parseGedcomDate('ABT 1900')).toMatchObject({ iso: '1900', precision: 'about' })
|
||||
expect(parseGedcomDate('BEF 12 MAY 1920')).toMatchObject({ iso: '1920-05-12', precision: 'before' })
|
||||
expect(parseGedcomDate('AFT 1850')).toMatchObject({ iso: '1850', precision: 'after' })
|
||||
expect(parseGedcomDate('EST 1700')).toMatchObject({ precision: 'estimated' })
|
||||
expect(parseGedcomDate('CAL 1801')).toMatchObject({ precision: 'calculated' })
|
||||
})
|
||||
|
||||
it('intervalles', () => {
|
||||
expect(parseGedcomDate('BET 1794 AND 1796')).toEqual({ iso: '1794', endIso: '1796', precision: 'between', text: 'BET 1794 AND 1796' })
|
||||
expect(parseGedcomDate('FROM 1914 TO 1918')).toMatchObject({ iso: '1914', endIso: '1918', precision: 'from' })
|
||||
})
|
||||
|
||||
it('date interprétée et texte entre parenthèses', () => {
|
||||
expect(parseGedcomDate('INT 1900 (vers la fin du siècle)')).toMatchObject({ iso: '1900', precision: 'interpreted' })
|
||||
expect(iso('(pendant la guerre)')).toBeNull()
|
||||
})
|
||||
|
||||
it('double année', () => {
|
||||
expect(iso('12 FEB 1700/01')).toBe('1701-02-12')
|
||||
expect(iso('1699/00')).toBe('1700')
|
||||
})
|
||||
|
||||
it('calendrier julien : la date reste celle écrite', () => {
|
||||
expect(iso('@#DJULIAN@ 1563')).toBe('1563')
|
||||
expect(iso('@#DJULIAN@ 3 SEP 1599')).toBe('1599-09-03')
|
||||
})
|
||||
|
||||
it('calendrier républicain converti', () => {
|
||||
expect(iso('@#DFRENCH R@ 18 BRUM 8')).toBe('1799-11-09')
|
||||
expect(iso('@#DFRENCH R@ 1 VEND 1')).toBe('1792-09-22')
|
||||
expect(iso('@#DFRENCH R@ 9 THER 2')).toBe('1794-07-27')
|
||||
expect(iso('@#DFRENCH R@ GERM 3')).toBe('1795-03')
|
||||
expect(iso('@#DFRENCH R@ 5')).toBe('1796')
|
||||
})
|
||||
|
||||
it('illisible : rien', () => {
|
||||
expect(iso('')).toBeNull()
|
||||
expect(iso('vers 1900')).toBeNull()
|
||||
expect(iso('@#DHEBREW@ 5660')).toBeNull()
|
||||
expect(iso('32 JAN 1900')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,98 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { adoptedFamilies, familyExtras, personExtras } from '../src/lib/gedcom-events'
|
||||
import { indexGedcomRecords } from '../src/lib/gedcom-photos'
|
||||
import { parseGedcom } from '../src/routes/gedcom'
|
||||
|
||||
const text = [
|
||||
'0 @I1@ INDI',
|
||||
'1 NAME Louis /RAGOT/',
|
||||
'2 NICK Loulou',
|
||||
'1 BIRT',
|
||||
'2 DATE ABT 1879',
|
||||
'2 PLAC La Roche-sur-Yon,85191,Vendée,Pays de la Loire,France,',
|
||||
'2 SOUR @S1@',
|
||||
'3 PAGE Acte n° 12',
|
||||
'1 BAPM',
|
||||
'2 DATE 9 MAR 1879',
|
||||
'2 PLAC La Roche-sur-Yon,85191,Vendée,,France,',
|
||||
'1 OCCU Instituteur',
|
||||
'2 DATE FROM 1900 TO 1935',
|
||||
'2 PLAC Limoges',
|
||||
'1 OCCU Maire',
|
||||
'2 DATE 1936',
|
||||
'1 RESI',
|
||||
'2 ADDR 12 rue des Écoles',
|
||||
'3 CITY Limoges',
|
||||
'1 EVEN',
|
||||
'2 TYPE Militaire',
|
||||
'2 DATE BET 1914 AND 1918',
|
||||
'2 NOTE Blessé à Verdun.',
|
||||
'1 DEAT',
|
||||
'2 DATE @#DFRENCH R@ 18 BRUM 8',
|
||||
'2 PLAC Nantes,44109,Loire-Atlantique,Pays de la Loire,France,',
|
||||
'1 BURI',
|
||||
'2 PLAC Cimetière de Miséricorde, Nantes',
|
||||
'1 FAMC @F0@',
|
||||
'2 PEDI adopted',
|
||||
'1 FAMC @F9@',
|
||||
'0 @F1@ FAM',
|
||||
'1 HUSB @I1@',
|
||||
'1 MARR',
|
||||
'2 DATE EST 1905',
|
||||
'2 PLAC Limoges,87085,Haute-Vienne,Nouvelle-Aquitaine,France,',
|
||||
'2 SOUR Registre des mariages de Limoges',
|
||||
'1 DIV Y',
|
||||
'0 @S1@ SOUR',
|
||||
'1 TITL Registre des naissances',
|
||||
].join('\n')
|
||||
|
||||
const roots = parseGedcom(text)
|
||||
const records = indexGedcomRecords(roots)
|
||||
const indi = roots.find((n) => n.tag === 'INDI')!
|
||||
const fam = roots.find((n) => n.tag === 'FAM')!
|
||||
|
||||
describe('événements de vie d’une personne', () => {
|
||||
const extras = personExtras(indi as never, records)
|
||||
const byType = (type: string) => extras.events.filter((e) => e.type === type)
|
||||
|
||||
it('précision des dates, lieu de décès, surnom', () => {
|
||||
expect(extras.birthDatePrecision).toBe('about')
|
||||
expect(extras.deathDatePrecision).toBeNull()
|
||||
expect(extras.deathPlace).toBe('Nantes, Loire-Atlantique, Pays de la Loire, France')
|
||||
expect(extras.nickname).toBe('Loulou')
|
||||
})
|
||||
|
||||
it('naissance : seulement ses sources, sans recopier la date ni le lieu', () => {
|
||||
expect(byType('birth')).toEqual([expect.objectContaining({ sources: 'Registre des naissances, Acte n° 12', date: null, place: null })])
|
||||
})
|
||||
|
||||
it('baptême, métiers successifs, résidence, inhumation', () => {
|
||||
expect(byType('baptism')[0]).toMatchObject({ place: 'La Roche-sur-Yon, Vendée, France', datePrecision: null })
|
||||
expect(byType('baptism')[0].date?.toISOString().slice(0, 10)).toBe('1879-03-09')
|
||||
expect(byType('occupation').map((e) => e.description)).toEqual(['Instituteur', 'Maire'])
|
||||
expect(byType('occupation')[0]).toMatchObject({ datePrecision: 'from', dateText: 'FROM 1900 TO 1935', place: 'Limoges' })
|
||||
expect(byType('occupation')[0].dateEnd?.getUTCFullYear()).toBe(1935)
|
||||
expect(byType('residence')[0].place).toBe('12 rue des Écoles, Limoges')
|
||||
expect(byType('burial')[0].place).toBe('Cimetière de Miséricorde, Nantes')
|
||||
})
|
||||
|
||||
it('événement libre (Heredis « Militaire ») avec sa note', () => {
|
||||
expect(byType('custom')[0]).toMatchObject({ label: 'Militaire', datePrecision: 'between', notes: 'Blessé à Verdun.' })
|
||||
})
|
||||
|
||||
it('adoption déclarée par PEDI', () => {
|
||||
expect([...adoptedFamilies(indi as never)]).toEqual(['F0'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('événements d’un couple', () => {
|
||||
const extras = familyExtras(fam as never, records)
|
||||
|
||||
it('lieu et précision du mariage, sources du mariage, divorce', () => {
|
||||
expect(extras.startPlace).toBe('Limoges, Haute-Vienne, Nouvelle-Aquitaine, France')
|
||||
expect(extras.startDatePrecision).toBe('estimated')
|
||||
expect(extras.events.map((e) => e.type)).toEqual(['marriage', 'divorce'])
|
||||
expect(extras.events[0]).toMatchObject({ sources: 'Registre des mariages de Limoges', place: null })
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,232 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { indexGedcomRecords, localMediaPath, mediaRefsForPerson, photoPathForPerson, plainNoteText } from '../src/lib/gedcom-photos'
|
||||
import { parseGedcom } from '../src/routes/gedcom'
|
||||
|
||||
// Pour chaque personne : son portrait et ses souvenirs, tels que l'import les renvoie
|
||||
function mediaOf(text: string) {
|
||||
const roots = parseGedcom(text)
|
||||
const records = indexGedcomRecords(roots)
|
||||
const out: Record<string, { portrait: string | null; media: ReturnType<typeof mediaRefsForPerson> }> = {}
|
||||
for (const indi of roots.filter((n) => n.tag === 'INDI' && n.xref)) {
|
||||
const portrait = photoPathForPerson(indi, records.obje)
|
||||
out[indi.xref!] = { portrait, media: mediaRefsForPerson(indi, records, portrait) }
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
describe('souvenirs cités par un GEDCOM', () => {
|
||||
it('Heredis PC : média sous la source citée d\u2019un événement, titre dans la note', () => {
|
||||
const text = [
|
||||
'0 HEAD',
|
||||
'1 SOUR Heredis PC2023',
|
||||
'0 @I1@ INDI',
|
||||
'1 NAME Louis Eugène Lucien /RAGOT/',
|
||||
'1 BIRT',
|
||||
'2 DATE 1879',
|
||||
'2 SOUR @S1@',
|
||||
'3 PAGE Acte n° 12',
|
||||
'3 OBJE @O1@',
|
||||
'0 @S1@ SOUR',
|
||||
'1 TITL Registre des naissances, Vendée',
|
||||
'0 @O1@ OBJE',
|
||||
'1 FILE C:/Users/Moi/Documents/Heredis/Médias/Naissance Ragot Louis Eugène Lucien.jpg',
|
||||
'2 FORM JPG',
|
||||
'1 NOTE Naissance Ragot Louis Eugène Lucien',
|
||||
].join('\n')
|
||||
expect(mediaOf(text).I1).toEqual({
|
||||
portrait: null,
|
||||
media: [{
|
||||
file: 'C:/Users/Moi/Documents/Heredis/Médias/Naissance Ragot Louis Eugène Lucien.jpg',
|
||||
caption: 'Naissance Ragot Louis Eugène Lucien',
|
||||
source: 'Registre des naissances, Vendée, Acte n° 12',
|
||||
}],
|
||||
})
|
||||
})
|
||||
|
||||
it('Heredis : média accroché à la fiche de la source elle-même', () => {
|
||||
const text = [
|
||||
'0 @I1@ INDI',
|
||||
'1 NAME Louis /RAGOT/',
|
||||
'1 EVEN',
|
||||
'2 TYPE Militaire',
|
||||
'2 SOUR @S2@',
|
||||
'0 @S2@ SOUR',
|
||||
'1 TITL Fiche matriculaire',
|
||||
'1 OBJE @O2@',
|
||||
'0 @O2@ OBJE',
|
||||
'1 FILE D:\\Généalogie\\Ragot Louis fiche matriculaire.pdf',
|
||||
'2 FORM PDF',
|
||||
].join('\n')
|
||||
expect(mediaOf(text).I1.media).toEqual([{
|
||||
file: 'D:\\Généalogie\\Ragot Louis fiche matriculaire.pdf',
|
||||
caption: 'Ragot Louis fiche matriculaire',
|
||||
source: 'Fiche matriculaire',
|
||||
}])
|
||||
})
|
||||
|
||||
it('Heredis Mac : note de titre en RTF', () => {
|
||||
expect(plainNoteText([
|
||||
'{\\rtf1\\ansi\\ansicpg1252\\cocoartf1561\\cocoasubrtf400',
|
||||
'{\\fonttbl\\f0\\fswiss\\fcharset0 Helvetica;}',
|
||||
'{\\colortbl;\\red255\\green255\\blue255;}',
|
||||
'{\\*\\expandedcolortbl;;}',
|
||||
'\\pard\\tx560\\tx1120\\pardirnatural\\partightenfactor0',
|
||||
'',
|
||||
"\\f0\\fs24 \\cf0 acte mariage Th\\'e9ophane V\\'c9NIEN avec Emma JEANDOT}",
|
||||
].join('\n'))).toBe('acte mariage Théophane VÉNIEN avec Emma JEANDOT')
|
||||
})
|
||||
|
||||
it('Gramps : renvoi sous un événement, titre sous FILE (GEDCOM 5.5.1)', () => {
|
||||
const text = [
|
||||
'0 @I1@ INDI',
|
||||
'1 NAME Marie /Martin/',
|
||||
'1 OBJE @M1@',
|
||||
'1 MARR',
|
||||
'2 OBJE @M2@',
|
||||
'0 @M1@ OBJE',
|
||||
'1 FILE photos/marie.jpg',
|
||||
'2 FORM jpg',
|
||||
'0 @M2@ OBJE',
|
||||
'1 FILE photos/mariage 1950.png',
|
||||
'2 FORM png',
|
||||
'2 TITL Mariage de Marie et Paul',
|
||||
].join('\n')
|
||||
expect(mediaOf(text).I1).toEqual({
|
||||
portrait: 'photos/marie.jpg',
|
||||
media: [{ file: 'photos/mariage 1950.png', caption: 'Mariage de Marie et Paul', source: null }],
|
||||
})
|
||||
})
|
||||
|
||||
it('RootsMagic : OBJE écrit sous la personne, le portrait _PRIM n\u2019est pas repris en souvenir', () => {
|
||||
const text = [
|
||||
'0 @I1@ INDI',
|
||||
'1 OBJE',
|
||||
'2 FILE C:\\RootsMagic\\Media\\jean portrait.jpg',
|
||||
'2 FORM jpg',
|
||||
'2 TITL Jean',
|
||||
'2 _PRIM Y',
|
||||
'1 OBJE',
|
||||
'2 FILE C:\\RootsMagic\\Media\\recensement 1906.jpg',
|
||||
'2 FORM jpg',
|
||||
'2 TITL Recensement de 1906',
|
||||
'2 _TYPE PHOTO',
|
||||
].join('\n')
|
||||
expect(mediaOf(text).I1).toEqual({
|
||||
portrait: 'C:\\RootsMagic\\Media\\jean portrait.jpg',
|
||||
media: [{ file: 'C:\\RootsMagic\\Media\\recensement 1906.jpg', caption: 'Recensement de 1906', source: null }],
|
||||
})
|
||||
})
|
||||
|
||||
it('Family Tree Maker : _PHOTO désigne le portrait, les autres deviennent des souvenirs', () => {
|
||||
const text = [
|
||||
'0 @I1@ INDI',
|
||||
'1 _PHOTO @O2@',
|
||||
'1 OBJE @O1@',
|
||||
'1 OBJE @O2@',
|
||||
'0 @O1@ OBJE',
|
||||
'1 FILE C:\\FTM\\Media\\groupe 1930.jpg',
|
||||
'2 FORM jpg',
|
||||
'2 TITL Toute la famille en 1930',
|
||||
'0 @O2@ OBJE',
|
||||
'1 FILE C:\\FTM\\Media\\portrait.jpg',
|
||||
'2 FORM jpg',
|
||||
].join('\n')
|
||||
expect(mediaOf(text).I1).toEqual({
|
||||
portrait: 'C:\\FTM\\Media\\portrait.jpg',
|
||||
media: [{ file: 'C:\\FTM\\Media\\groupe 1930.jpg', caption: 'Toute la famille en 1930', source: null }],
|
||||
})
|
||||
})
|
||||
|
||||
it('Ancestry, MyHeritage : les adresses web ne sont pas des fichiers de l\u2019ordinateur', () => {
|
||||
const text = [
|
||||
'0 @I1@ INDI',
|
||||
'1 OBJE',
|
||||
'2 FILE https://mediasvc.ancestry.com/v2/image/namespaces/1093/media/abc.jpg',
|
||||
'2 FORM jpg',
|
||||
'1 OBJE',
|
||||
'2 FORM url',
|
||||
'2 FILE www.exemple.org/acte',
|
||||
].join('\n')
|
||||
expect(mediaOf(text).I1.media).toEqual([])
|
||||
})
|
||||
|
||||
it('GEDCOM 7 : chemin en file://, type MIME et titre sous FILE', () => {
|
||||
const text = [
|
||||
'0 HEAD',
|
||||
'1 GEDC',
|
||||
'2 VERS 7.0',
|
||||
'0 @I1@ INDI',
|
||||
'1 OBJE @O1@',
|
||||
'0 @O1@ OBJE',
|
||||
'1 FILE file:///C:/Archives/acte%20de%20d%C3%A9c%C3%A8s.pdf',
|
||||
'2 FORM application/pdf',
|
||||
'2 TITL Acte de décès',
|
||||
].join('\n')
|
||||
expect(mediaOf(text).I1.media).toEqual([{ file: 'C:/Archives/acte de décès.pdf', caption: 'Acte de décès', source: null }])
|
||||
})
|
||||
|
||||
it('acte de mariage accroché à la famille : souvenir des deux conjoints', () => {
|
||||
const text = [
|
||||
'0 @I1@ INDI',
|
||||
'1 NAME Paul /Durand/',
|
||||
'1 FAMS @F1@',
|
||||
'0 @I2@ INDI',
|
||||
'1 NAME Jeanne /Petit/',
|
||||
'1 FAMS @F1@',
|
||||
'0 @I3@ INDI',
|
||||
'1 NAME Enfant /Durand/',
|
||||
'1 FAMC @F1@',
|
||||
'0 @F1@ FAM',
|
||||
'1 HUSB @I1@',
|
||||
'1 WIFE @I2@',
|
||||
'1 CHIL @I3@',
|
||||
'1 MARR',
|
||||
'2 DATE 1922',
|
||||
'2 SOUR Registre des mariages de Lille',
|
||||
'3 OBJE',
|
||||
'4 FILE mariages/durand-petit 1922.jpg',
|
||||
'4 FORM jpg',
|
||||
].join('\n')
|
||||
const out = mediaOf(text)
|
||||
const expected = [{ file: 'mariages/durand-petit 1922.jpg', caption: 'durand-petit 1922', source: 'Registre des mariages de Lille' }]
|
||||
expect(out.I1.media).toEqual(expected)
|
||||
expect(out.I2.media).toEqual(expected)
|
||||
expect(out.I3.media).toEqual([])
|
||||
})
|
||||
|
||||
it('un fichier cité deux fois n\u2019est gardé qu\u2019une fois', () => {
|
||||
const text = [
|
||||
'0 @I1@ INDI',
|
||||
'1 BIRT',
|
||||
'2 OBJE @O1@',
|
||||
'1 BAPM',
|
||||
'2 OBJE @O1@',
|
||||
'1 OBJE',
|
||||
'2 FILE C:\\medias\\ACTE.PDF',
|
||||
'0 @O1@ OBJE',
|
||||
'1 FILE C:\\medias\\acte.pdf',
|
||||
].join('\n')
|
||||
expect(mediaOf(text).I1.media.map((m) => m.file)).toEqual(['C:\\medias\\acte.pdf'])
|
||||
})
|
||||
})
|
||||
|
||||
describe('localMediaPath', () => {
|
||||
it('garde les chemins locaux de fichiers connus, écarte le reste', () => {
|
||||
expect(localMediaPath('C:\\Photos\\jean.JPG')).toBe('C:\\Photos\\jean.JPG')
|
||||
expect(localMediaPath('/Users/moi/Heredis/acte.pdf')).toBe('/Users/moi/Heredis/acte.pdf')
|
||||
expect(localMediaPath('file:///home/moi/voix.mp3')).toBe('/home/moi/voix.mp3')
|
||||
expect(localMediaPath('https://exemple.org/photo.jpg')).toBeNull()
|
||||
expect(localMediaPath('C:\\Photos\\arbre.ged')).toBeNull()
|
||||
expect(localMediaPath('')).toBeNull()
|
||||
})
|
||||
|
||||
it('fichier piégé : sources en chaîne et niveaux trop profonds, sans débordement ni lenteur', () => {
|
||||
const chain = Array.from({ length: 20000 }, (_, i) => [`0 @S${i}@ SOUR`, `1 SOUR @S${i + 1}@`]).flat()
|
||||
const deep = Array.from({ length: 5000 }, (_, i) => `${i + 2} NOTE niveau`)
|
||||
const text = ['0 @I1@ INDI', '1 NAME A /B/', '1 SOUR @S0@', '1 BIRT', ...deep, ...chain, '0 @S20000@ SOUR', '1 OBJE', '2 FILE C:/fin.jpg'].join('\n')
|
||||
const started = Date.now()
|
||||
expect(() => mediaOf(text)).not.toThrow()
|
||||
expect(Date.now() - started).toBeLessThan(2000)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,45 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { indexGedcomRecords } from '../src/lib/gedcom-photos'
|
||||
import { parseGedcom, personNotes } from '../src/routes/gedcom'
|
||||
|
||||
function notesOf(text: string) {
|
||||
const roots = parseGedcom(text)
|
||||
const records = indexGedcomRecords(roots)
|
||||
const indi = roots.find((n) => n.tag === 'INDI')!
|
||||
return personNotes(indi as never, records)
|
||||
}
|
||||
|
||||
describe('notes d’une personne', () => {
|
||||
it('note écrite sous la personne, sur plusieurs lignes (CONT) et coupée (CONC)', () => {
|
||||
expect(notesOf([
|
||||
'0 @I1@ INDI',
|
||||
'1 NOTE Instituteur à Limoges pendant',
|
||||
'2 CONC trente-cinq ans.',
|
||||
'2 CONT Il aimait la pêche.',
|
||||
].join('\n'))).toBe('Instituteur à Limoges pendant trente-cinq ans.\nIl aimait la pêche.')
|
||||
})
|
||||
|
||||
it('note partagée par renvoi (Gramps, Geneatique, Ancestry)', () => {
|
||||
expect(notesOf([
|
||||
'0 @I1@ INDI',
|
||||
'1 NOTE @N7@',
|
||||
'0 @N7@ NOTE Revenu du front en 1919.',
|
||||
'1 CONT Blessé à Verdun.',
|
||||
].join('\n'))).toBe('Revenu du front en 1919.\nBlessé à Verdun.')
|
||||
})
|
||||
|
||||
it('plusieurs notes, séparées par une ligne vide', () => {
|
||||
expect(notesOf([
|
||||
'0 @I1@ INDI',
|
||||
'1 NOTE Première note.',
|
||||
'1 NOTE @N1@',
|
||||
'0 @N1@ NOTE Deuxième note.',
|
||||
].join('\n'))).toBe('Première note.\n\nDeuxième note.')
|
||||
})
|
||||
|
||||
it('aucune note, ou renvoi cassé', () => {
|
||||
expect(notesOf('0 @I1@ INDI\n1 NAME Jean /Dupont/')).toBeNull()
|
||||
expect(notesOf('0 @I1@ INDI\n1 NOTE @N404@')).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,74 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import { indexObjeRecords, photoPathForPerson } from '../src/lib/gedcom-photos'
|
||||
import { parseGedcom } from '../src/routes/gedcom'
|
||||
|
||||
function photosOf(text: string): Record<string, string | null> {
|
||||
const roots = parseGedcom(text)
|
||||
const objes = indexObjeRecords(roots)
|
||||
const out: Record<string, string | null> = {}
|
||||
for (const indi of roots.filter((n) => n.tag === 'INDI' && n.xref)) {
|
||||
out[indi.xref!] = photoPathForPerson(indi, objes)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
describe('photos citées par un GEDCOM', () => {
|
||||
it('lit un OBJE écrit sous la personne (GEDCOM 5.5)', () => {
|
||||
const text = [
|
||||
'0 @I1@ INDI',
|
||||
'1 NAME Jean /Dupont/',
|
||||
'1 OBJE',
|
||||
'2 FORM jpg',
|
||||
'2 FILE C:\\Genealogie\\Photos\\jean.jpg',
|
||||
].join('\n')
|
||||
expect(photosOf(text)).toEqual({ I1: 'C:\\Genealogie\\Photos\\jean.jpg' })
|
||||
})
|
||||
|
||||
it('suit un renvoi vers un enregistrement OBJE (Gramps, GEDCOM 5.5.1)', () => {
|
||||
const text = [
|
||||
'0 @I1@ INDI',
|
||||
'1 NAME Marie /Martin/',
|
||||
'1 OBJE @M7@',
|
||||
'0 @M7@ OBJE',
|
||||
'1 FILE photos/marie 1920.png',
|
||||
'2 FORM png',
|
||||
].join('\n')
|
||||
expect(photosOf(text)).toEqual({ I1: 'photos/marie 1920.png' })
|
||||
})
|
||||
|
||||
it('préfère la photo marquée principale, sinon la première image', () => {
|
||||
const text = [
|
||||
'0 @I1@ INDI',
|
||||
'1 OBJE',
|
||||
'2 FILE acte-naissance.pdf',
|
||||
'1 OBJE',
|
||||
'2 FILE groupe.jpg',
|
||||
'1 OBJE',
|
||||
'2 FILE portrait.jpg',
|
||||
'2 _PRIM Y',
|
||||
'0 @I2@ INDI',
|
||||
'1 OBJE',
|
||||
'2 FILE acte.pdf',
|
||||
'1 OBJE',
|
||||
'2 FILE premier.JPEG',
|
||||
'1 OBJE',
|
||||
'2 FILE second.jpg',
|
||||
].join('\n')
|
||||
expect(photosOf(text)).toEqual({ I1: 'portrait.jpg', I2: 'premier.JPEG' })
|
||||
})
|
||||
|
||||
it('ignore les adresses web, les documents et les renvois cassés', () => {
|
||||
const text = [
|
||||
'0 @I1@ INDI',
|
||||
'1 OBJE',
|
||||
'2 FILE https://exemple.org/photo.jpg',
|
||||
'1 OBJE @M404@',
|
||||
'1 OBJE',
|
||||
'2 FILE registre.pdf',
|
||||
'0 @I2@ INDI',
|
||||
'1 NAME Sans /Photo/',
|
||||
].join('\n')
|
||||
expect(photosOf(text)).toEqual({ I1: null, I2: null })
|
||||
})
|
||||
})
|
||||
Loaded 100 of 403 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user