mirror of
https://github.com/IliesAllali/parenthese.git
synced 2026-11-06 23:32:08 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 |
No files matched your search
@@ -40,6 +40,10 @@ CORS_ORIGIN=http://localhost
|
||||
# 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 +) :
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -63,16 +63,21 @@ jobs:
|
||||
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 }}
|
||||
@@ -89,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
|
||||
|
||||
@@ -120,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 }}
|
||||
|
||||
+226
@@ -2,6 +2,232 @@
|
||||
|
||||
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
|
||||
|
||||
+4
-4
@@ -18,12 +18,12 @@ RUN apt-get update \
|
||||
WORKDIR /app
|
||||
|
||||
COPY backend/package.json backend/package-lock.json ./
|
||||
COPY backend/prisma ./prisma
|
||||
RUN npm ci --no-audit --no-fund
|
||||
RUN npx prisma generate
|
||||
|
||||
COPY backend/tsconfig.json ./
|
||||
COPY backend/prisma ./prisma
|
||||
COPY backend/prisma.config.ts backend/tsconfig.json ./
|
||||
COPY backend/src ./src
|
||||
RUN npx prisma generate
|
||||
RUN npm run build
|
||||
|
||||
|
||||
@@ -68,8 +68,8 @@ 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
|
||||
|
||||
COPY --from=api-build /app/node_modules/.prisma ./node_modules/.prisma
|
||||
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.
|
||||
|
||||
@@ -7,6 +7,7 @@
|
||||
!deploy/aio
|
||||
backend/node_modules
|
||||
backend/dist
|
||||
backend/src/generated
|
||||
backend/.local
|
||||
backend/storage
|
||||
backend/test
|
||||
|
||||
@@ -59,6 +59,8 @@ Pour ouvrir l'instance à la famille depuis Internet, placez un reverse proxy HT
|
||||
|
||||
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.
|
||||
|
||||
@@ -65,6 +65,8 @@ To open the instance to your family over the Internet, put an HTTPS reverse prox
|
||||
|
||||
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.
|
||||
@@ -83,7 +85,7 @@ Only the first name, last name and birth year leave the server, and the panel sa
|
||||
|
||||
#### Sign in with your identity provider (OIDC)
|
||||
|
||||
*Experimental in 1.2.0: tested against a certified OpenID provider, feedback from real setups is welcome in the issues.*
|
||||
*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`:
|
||||
|
||||
@@ -95,9 +97,11 @@ 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. `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.
|
||||
`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.
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
node_modules
|
||||
dist
|
||||
src/generated
|
||||
.local
|
||||
storage
|
||||
test
|
||||
|
||||
@@ -14,6 +14,9 @@ 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=""
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -563,7 +563,10 @@ paths:
|
||||
properties:
|
||||
name:
|
||||
type: string
|
||||
required: [registration, passwordLogin, oidc]
|
||||
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:
|
||||
|
||||
Generated
+1706
-216
File diff suppressed because it is too large.
Load diff
+10
-6
@@ -17,21 +17,25 @@
|
||||
"prisma:deploy": "prisma migrate deploy"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fastify/cookie": "^11.1.3",
|
||||
"@fastify/cookie": "^11.1.5",
|
||||
"@fastify/cors": "^11.3.0",
|
||||
"@fastify/jwt": "^10.2.5",
|
||||
"@fastify/jwt": "^10.2.6",
|
||||
"@fastify/rate-limit": "^11.2.0",
|
||||
"@prisma/client": "^6.15.0",
|
||||
"bcryptjs": "^3.0.2",
|
||||
"dotenv": "^18.0.8",
|
||||
"@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.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.19.2",
|
||||
"prisma": "^6.15.0",
|
||||
"@types/pg": "^8.23.1",
|
||||
"prisma": "^7.10.1",
|
||||
"tsx": "^4.23.15",
|
||||
"typescript": "^7.0.2",
|
||||
"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,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;
|
||||
@@ -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 {
|
||||
@@ -121,36 +125,37 @@ model UserIdentity {
|
||||
}
|
||||
|
||||
model Tree {
|
||||
id String @id @default(cuid())
|
||||
ownerUserId String
|
||||
slug String @unique
|
||||
name String
|
||||
description String?
|
||||
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[]
|
||||
lastOpenedByUsers User[] @relation("UserLastOpenedTree")
|
||||
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")
|
||||
@@ -214,6 +219,29 @@ model TreeInvitation {
|
||||
@@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
|
||||
@@ -282,6 +310,8 @@ model Person {
|
||||
// { "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?
|
||||
@@ -342,6 +372,8 @@ model MediaItem {
|
||||
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
|
||||
|
||||
+16
-3
@@ -4,18 +4,20 @@ 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 { immichRoutes } from './routes/immich.js'
|
||||
import { managerRoutes } from './routes/managers.js'
|
||||
import { searchSourceRoutes } from './routes/search-sources.js'
|
||||
import { mediaRoutes } from './routes/media.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'
|
||||
@@ -58,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, {
|
||||
@@ -150,6 +160,9 @@ 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)
|
||||
|
||||
@@ -68,6 +68,11 @@ const envSchema = z.object({
|
||||
// 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(''),
|
||||
|
||||
@@ -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}`)
|
||||
}
|
||||
@@ -1,15 +1,18 @@
|
||||
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.
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Prisma, type 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, avatarCrop: Prisma.DbNull, immichPersonId: null },
|
||||
data: { deletedAt: now, updatedBy: actorUserId, avatarPath: null, avatarMimeType: null, avatarCrop: Prisma.DbNull, avatarBlurhash: null, immichPersonId: null },
|
||||
})
|
||||
|
||||
const unions = await db.union.findMany({
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createHash } from 'node:crypto'
|
||||
|
||||
import type { PrismaClient } from '@prisma/client'
|
||||
import type { PrismaClient } from '../generated/prisma/client.js'
|
||||
|
||||
import { env } from '../config/env.js'
|
||||
import { decryptImmichApiKey } from './immich-secret.js'
|
||||
|
||||
@@ -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.
|
||||
@@ -235,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.
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Prisma, PrismaClient } from '@prisma/client'
|
||||
import type { Prisma, PrismaClient } from '../generated/prisma/client.js'
|
||||
import { z } from 'zod'
|
||||
|
||||
type Db = PrismaClient | Prisma.TransactionClient
|
||||
|
||||
@@ -11,6 +11,9 @@ export type OidcPending = {
|
||||
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 = {
|
||||
|
||||
@@ -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 }),
|
||||
})
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Prisma, PrismaClient } from '@prisma/client'
|
||||
import type { Prisma, PrismaClient } from '../generated/prisma/client.js'
|
||||
|
||||
import { env } from '../config/env.js'
|
||||
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Prisma, PrismaClient } from '@prisma/client'
|
||||
import type { Prisma, PrismaClient } from '../generated/prisma/client.js'
|
||||
|
||||
type LinkReader = Pick<PrismaClient, 'parentChildLink'> | Pick<Prisma.TransactionClient, 'parentChildLink'>
|
||||
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import { createHash, randomBytes } from 'node:crypto'
|
||||
|
||||
import type { Prisma, PrismaClient } from '@prisma/client'
|
||||
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.
|
||||
|
||||
@@ -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'
|
||||
|
||||
|
||||
@@ -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()
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+16
-10
@@ -109,11 +109,16 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
|
||||
app.get(
|
||||
'/options',
|
||||
{ config: { rateLimit: { max: 60, timeWindow: '1 minute' } } },
|
||||
async (_request, reply) => reply.send({
|
||||
registration: await isRegistrationOpen(app.prisma),
|
||||
passwordLogin: env.PASSWORD_LOGIN,
|
||||
oidc: isOidcEnabled() ? { name: env.OIDC_PROVIDER_NAME } : null,
|
||||
}),
|
||||
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(
|
||||
@@ -254,14 +259,15 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
|
||||
|
||||
const user = await app.prisma.user.findUnique({
|
||||
where: { id: request.actor.userId },
|
||||
select: { id: true, email: true, firstName: true, passwordHash: true },
|
||||
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
|
||||
return reply.send({ user: { id: user.id, email: user.email, firstName: user.firstName, hasPassword: confirmsWithPassword(user.passwordHash) } })
|
||||
// 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) => {
|
||||
@@ -450,7 +456,7 @@ export const authRoutes: FastifyPluginAsync = async (app) => {
|
||||
})
|
||||
|
||||
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)
|
||||
@@ -470,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,12 +1,14 @@
|
||||
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'
|
||||
|
||||
@@ -32,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' },
|
||||
@@ -246,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
|
||||
}
|
||||
@@ -325,10 +329,15 @@ 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
|
||||
@@ -1214,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()
|
||||
@@ -1275,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,
|
||||
},
|
||||
@@ -1374,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) {
|
||||
@@ -1429,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
|
||||
@@ -1467,10 +1507,12 @@ 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
|
||||
}
|
||||
@@ -1482,6 +1524,7 @@ export const contributionRoutes: FastifyPluginAsync = async (app) => {
|
||||
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 },
|
||||
@@ -1502,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({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Prisma } from '@prisma/client'
|
||||
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'
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
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'
|
||||
@@ -539,6 +540,7 @@ export const immichRoutes: FastifyPluginAsync = async (app) => {
|
||||
avatarMimeType: prepared.mimeType,
|
||||
// Nouveau portrait, nouveau cadrage à faire
|
||||
avatarCrop: Prisma.DbNull,
|
||||
avatarBlurhash: await computeBlurhash(prepared.buffer) ?? '',
|
||||
immichPersonId,
|
||||
updatedBy: request.actor.userId,
|
||||
},
|
||||
@@ -619,11 +621,13 @@ export const immichRoutes: FastifyPluginAsync = async (app) => {
|
||||
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.
|
||||
|
||||
+60
-13
@@ -2,7 +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 '@prisma/client'
|
||||
import { Prisma } from '../generated/prisma/client.js'
|
||||
import type { FastifyPluginAsync, FastifyRequest } from 'fastify'
|
||||
import { z } from 'zod'
|
||||
|
||||
@@ -16,15 +16,19 @@ import {
|
||||
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
|
||||
@@ -240,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
|
||||
@@ -486,6 +502,7 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
status: isPending ? 'pending' : 'approved',
|
||||
contributionSessionId: contributionSession?.id ?? null,
|
||||
lifeEventId,
|
||||
blurhash: payload.data.type === 'photo' ? await computeBlurhash(prepared.buffer) ?? '' : null,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -605,6 +622,7 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
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
|
||||
@@ -661,6 +679,7 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
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,
|
||||
@@ -1078,6 +1097,8 @@ export const mediaRoutes: FastifyPluginAsync = async (app) => {
|
||||
select: {
|
||||
filePath: true,
|
||||
mimeType: true,
|
||||
status: true,
|
||||
uploadedBy: true,
|
||||
},
|
||||
})
|
||||
|
||||
@@ -1085,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)
|
||||
@@ -1096,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 ----
|
||||
@@ -1123,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' })
|
||||
}
|
||||
|
||||
@@ -1138,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')
|
||||
@@ -1180,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,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type { FastifyInstance, FastifyPluginAsync, FastifyReply } from 'fastify'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { Prisma } from '@prisma/client'
|
||||
import { Prisma } from '../generated/prisma/client.js'
|
||||
import { z } from 'zod'
|
||||
|
||||
import { env } from '../config/env.js'
|
||||
@@ -46,8 +46,42 @@ const pendingSchema = z.object({
|
||||
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),
|
||||
})
|
||||
@@ -114,7 +148,18 @@ export const oidcRoutes: FastifyPluginAsync = async (app) => {
|
||||
'/start',
|
||||
{ config: { rateLimit: { max: 20, timeWindow: '1 minute' } } },
|
||||
async (request, reply) => {
|
||||
const returnTo = safeReturnTo((request.query as Record<string, unknown> | undefined)?.returnTo)
|
||||
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)
|
||||
@@ -123,7 +168,7 @@ export const oidcRoutes: FastifyPluginAsync = async (app) => {
|
||||
return redirectToApp(reply, returnTo, 'oidc_error=oidc_unavailable')
|
||||
}
|
||||
|
||||
reply.setCookie(PENDING_COOKIE, JSON.stringify(start.pending), {
|
||||
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
|
||||
@@ -167,13 +212,13 @@ export const oidcRoutes: FastifyPluginAsync = async (app) => {
|
||||
return redirectToApp(reply, returnTo, 'oidc_error=oidc_failed')
|
||||
}
|
||||
|
||||
let result: AccountResult
|
||||
let result: AccountResult | LinkResult
|
||||
try {
|
||||
result = await resolveAccount(app, identity)
|
||||
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 = await resolveAccount(app, identity)
|
||||
result = pending.linkUserId ? await linkIdentity(app, pending.linkUserId, identity) : await resolveAccount(app, identity)
|
||||
} else {
|
||||
throw error
|
||||
}
|
||||
@@ -195,6 +240,23 @@ export const oidcRoutes: FastifyPluginAsync = async (app) => {
|
||||
},
|
||||
)
|
||||
|
||||
// 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' } } },
|
||||
|
||||
@@ -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'
|
||||
@@ -143,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(),
|
||||
})
|
||||
@@ -1780,6 +1783,8 @@ export const treeRoutes: FastifyPluginAsync = async (app) => {
|
||||
},
|
||||
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,
|
||||
|
||||
@@ -35,7 +35,15 @@ export type OidcHandoffJwtPayload = {
|
||||
jti: string
|
||||
}
|
||||
|
||||
export type AnyJwtPayload = UserJwtPayload | TreeAccessJwtPayload | MediaJwtPayload | OidcHandoffJwtPayload
|
||||
// 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,4 +1,4 @@
|
||||
import type { Annotation, MediaItem, MediaPersonTag, 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'
|
||||
@@ -26,6 +26,7 @@ export type GraphPayload = {
|
||||
notes: string | null
|
||||
avatarFromImmich: boolean
|
||||
avatarCrop: AvatarCrop | null
|
||||
avatarBlurhash: string | null
|
||||
}>
|
||||
unions: Array<{
|
||||
id: string
|
||||
@@ -54,6 +55,7 @@ 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 }>
|
||||
}>
|
||||
@@ -117,6 +119,7 @@ export function buildGraphPayload(
|
||||
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,
|
||||
@@ -145,6 +148,7 @@ 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) => ({
|
||||
|
||||
@@ -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('')
|
||||
})
|
||||
})
|
||||
@@ -7,6 +7,12 @@ 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),
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
})
|
||||
@@ -4,6 +4,12 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vites
|
||||
// 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(),
|
||||
@@ -111,7 +117,7 @@ describe('prénom du compte', () => {
|
||||
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 })
|
||||
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)
|
||||
|
||||
@@ -2,13 +2,19 @@ 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 '@prisma/client'
|
||||
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(),
|
||||
},
|
||||
|
||||
@@ -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()
|
||||
})
|
||||
})
|
||||
@@ -8,6 +8,12 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi }
|
||||
|
||||
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(),
|
||||
|
||||
@@ -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),
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
import Fastify, { type FastifyInstance } from 'fastify'
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'
|
||||
import { registerIdempotency, resetIdempotency } from '../src/lib/idempotency.js'
|
||||
|
||||
// Un envoi rejoué avec la même clé (réponse perdue sur un réseau faible) ne crée rien une seconde fois
|
||||
let app: FastifyInstance
|
||||
let created = 0
|
||||
let failNext = false
|
||||
|
||||
const KEY = 'a1b2c3d4-e5f6-4789-9abc-def012345678'
|
||||
const send = (headers: Record<string, string> = {}, url = '/trees/t1/contributions/sessions') =>
|
||||
app.inject({ method: 'POST', url, headers: { authorization: 'Bearer famille', ...headers }, payload: { title: 'x' } })
|
||||
|
||||
beforeAll(async () => {
|
||||
app = Fastify()
|
||||
registerIdempotency(app)
|
||||
app.post('/trees/:id/contributions/sessions', async (_request, reply) => {
|
||||
await new Promise((resolve) => setTimeout(resolve, 30))
|
||||
if (failNext) {
|
||||
failNext = false
|
||||
return reply.code(503).send({ error: 'busy' })
|
||||
}
|
||||
created += 1
|
||||
return reply.code(201).send({ session: { id: `s${created}` } })
|
||||
})
|
||||
app.post('/trees/:id/autre', async () => {
|
||||
created += 1
|
||||
return { ok: created }
|
||||
})
|
||||
await app.ready()
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close()
|
||||
})
|
||||
|
||||
beforeEach(() => {
|
||||
created = 0
|
||||
failNext = false
|
||||
resetIdempotency()
|
||||
})
|
||||
|
||||
describe('Idempotency-Key', () => {
|
||||
it('rejoue la première réponse sans recréer', async () => {
|
||||
const first = await send({ 'idempotency-key': KEY })
|
||||
const second = await send({ 'idempotency-key': KEY })
|
||||
expect(created).toBe(1)
|
||||
expect(second.statusCode).toBe(201)
|
||||
expect(second.json()).toEqual(first.json())
|
||||
expect(second.headers['idempotent-replayed']).toBe('true')
|
||||
})
|
||||
|
||||
it('deux essais simultanés : un seul est traité', async () => {
|
||||
const [a, b] = await Promise.all([send({ 'idempotency-key': KEY }), send({ 'idempotency-key': KEY })])
|
||||
expect(created).toBe(1)
|
||||
expect(a.json()).toEqual(b.json())
|
||||
})
|
||||
|
||||
it('un échec n’est pas gardé : l’essai suivant refait la requête', async () => {
|
||||
failNext = true
|
||||
const first = await send({ 'idempotency-key': KEY })
|
||||
const second = await send({ 'idempotency-key': KEY })
|
||||
expect(first.statusCode).toBe(503)
|
||||
expect(second.statusCode).toBe(201)
|
||||
expect(created).toBe(1)
|
||||
})
|
||||
|
||||
it('la clé d’une autre personne ne rejoue rien', async () => {
|
||||
await send({ 'idempotency-key': KEY })
|
||||
await send({ 'idempotency-key': KEY, authorization: 'Bearer quelquun-dautre' })
|
||||
expect(created).toBe(2)
|
||||
})
|
||||
|
||||
it('sans clé, ou avec une clé mal formée, chaque envoi compte', async () => {
|
||||
await send()
|
||||
await send()
|
||||
await send({ 'idempotency-key': 'court' })
|
||||
await send({ 'idempotency-key': 'court' })
|
||||
expect(created).toBe(4)
|
||||
})
|
||||
|
||||
it('les autres routes ne sont pas concernées', async () => {
|
||||
await send({ 'idempotency-key': KEY }, '/trees/t1/autre')
|
||||
await send({ 'idempotency-key': KEY }, '/trees/t1/autre')
|
||||
expect(created).toBe(2)
|
||||
})
|
||||
})
|
||||
@@ -7,6 +7,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: {
|
||||
count: vi.fn(),
|
||||
},
|
||||
|
||||
@@ -10,6 +10,12 @@ import { beforeAll, 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().mockResolvedValue(1),
|
||||
},
|
||||
|
||||
@@ -9,6 +9,12 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vites
|
||||
|
||||
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(),
|
||||
},
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
import { mkdtempSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
||||
|
||||
// Souvenir en attente de relecture, sur une vraie base : seuls qui gère l'arbre et qui l'a envoyé le lisent,
|
||||
// la famille qui connaîtrait son identifiant reçoit la même réponse qu'un média absent. 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/media-attente.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.3.${Math.floor(++ip / 250)}.${ip % 250 + 1}`
|
||||
const run = Date.now().toString(36)
|
||||
const mail = (name: string) => `${name}-${run}@exemple.fr`
|
||||
// PNG d'un pixel
|
||||
const PIXEL = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='
|
||||
const storage = mkdtempSync(path.join(tmpdir(), 'pth-media-attente-'))
|
||||
|
||||
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 }
|
||||
}
|
||||
|
||||
async function account(name: string) {
|
||||
const res = await call('POST', '/auth/register', undefined, { email: mail(name), password: 'mot-de-passe-solide', firstName: name })
|
||||
expect(res.status).toBe(201)
|
||||
return { token: res.body.token as string, id: res.body.user.id as string }
|
||||
}
|
||||
|
||||
describe.skipIf(!TEST_DB)('souvenir en attente, vraie base', () => {
|
||||
let owner: { token: string; id: string }
|
||||
let member: { token: string; id: string }
|
||||
let reader: { token: string; id: string }
|
||||
let shareToken: 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
|
||||
owner = await account('proprio')
|
||||
const tree = await call('POST', '/trees', owner.token, { name: 'Arbre de démo', slug: `attente-${run}`, visitorPassword: 'partage-demo-1', contributorPassword: 'partage-demo-1' })
|
||||
expect(tree.status).toBe(201)
|
||||
treeId = tree.body.tree?.id ?? tree.body.id
|
||||
const person = await call('POST', `/trees/${treeId}/persons`, owner.token, { firstName: 'Odette', lastName: 'Duval' })
|
||||
expect(person.status).toBe(201)
|
||||
personId = person.body.person?.id ?? person.body.id
|
||||
// Deux comptes de la famille, rattachés par le mot de passe de partage, et le lien de partage seul
|
||||
member = await account('membre')
|
||||
reader = await account('lecteur')
|
||||
for (const who of [member, reader]) {
|
||||
expect((await call('POST', `/trees/${treeId}/access/unlock`, who.token, { password: 'partage-demo-1' })).status).toBe(200)
|
||||
}
|
||||
const shared = await call('POST', `/trees/${treeId}/access/unlock`, undefined, { password: 'partage-demo-1' })
|
||||
expect(shared.status).toBe(200)
|
||||
shareToken = shared.body.token
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
await app?.close()
|
||||
})
|
||||
|
||||
const upload = (token: string) => call('POST', `/trees/${treeId}/persons/${personId}/media`, token, {
|
||||
type: 'photo', fileName: 'photo.png', mimeType: 'image/png', sizeBytes: Buffer.from(PIXEL, 'base64').length, dataBase64: PIXEL,
|
||||
})
|
||||
const read = (mediaId: string, token?: string) => call('GET', `/trees/${treeId}/media/${mediaId}`, token)
|
||||
// Jeton médias, celui que porte l'adresse d'une image (<img src>) : émis avec le graphe de l'arbre
|
||||
const mediaToken = async (token: string) => (await call('GET', `/trees/${treeId}/graph`, token)).body?.mediaToken as string
|
||||
|
||||
it('un souvenir envoyé par un membre attend la relecture, et seuls le gestionnaire et son auteur le lisent', async () => {
|
||||
const sent = await upload(member.token)
|
||||
expect(sent.status).toBe(201)
|
||||
const media = sent.body.media ?? sent.body
|
||||
expect(media.status).toBe('pending')
|
||||
|
||||
expect((await read(media.id, owner.token)).status).toBe(200)
|
||||
expect((await read(media.id, member.token)).status).toBe(200)
|
||||
expect((await read(media.id, reader.token)).status).toBe(404)
|
||||
expect((await read(media.id, shareToken)).status).toBe(404)
|
||||
expect((await read(media.id)).status).toBe(401)
|
||||
|
||||
// Par l'adresse d'une image : le jeton médias du gestionnaire ouvre, celui du lecteur non
|
||||
expect((await read(`${media.id}?token=${await mediaToken(owner.token)}`)).status).toBe(200)
|
||||
expect((await read(`${media.id}?token=${await mediaToken(member.token)}`)).status).toBe(200)
|
||||
expect((await read(`${media.id}?token=${await mediaToken(reader.token)}`)).status).toBe(404)
|
||||
expect((await read(`${media.id}?token=${await mediaToken(shareToken)}`)).status).toBe(404)
|
||||
})
|
||||
|
||||
it('un souvenir accepté se lit par toute la famille', async () => {
|
||||
const sent = await upload(member.token)
|
||||
const media = sent.body.media ?? sent.body
|
||||
expect(media.status).toBe('pending')
|
||||
const session = sent.body.contributionSessionId ?? media.contributionSessionId
|
||||
expect(session).toBeTruthy()
|
||||
const reviewed = await call('POST', `/trees/${treeId}/contributions/sessions/${session}/review`, owner.token, { decision: 'approved' })
|
||||
expect(reviewed.status).toBe(200)
|
||||
expect((await read(media.id, reader.token)).status).toBe(200)
|
||||
expect((await read(media.id, shareToken)).status).toBe(200)
|
||||
})
|
||||
|
||||
it('un souvenir posé par le gestionnaire est visible tout de suite', async () => {
|
||||
const sent = await upload(owner.token)
|
||||
expect(sent.status).toBe(201)
|
||||
const media = sent.body.media ?? sent.body
|
||||
expect(media.status).toBe('approved')
|
||||
expect((await read(media.id, reader.token)).status).toBe(200)
|
||||
})
|
||||
})
|
||||
@@ -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),
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import { mkdtempSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
||||
|
||||
// Un souvenir se lit par morceaux (Range), sur une vraie base. Lancé seulement avec TEST_DATABASE_URL :
|
||||
// TEST_DATABASE_URL=postgresql://postgres:postgres@localhost:5432/genealogy_test npx vitest run test/media-range.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)
|
||||
// PNG d'un pixel
|
||||
const PIXEL = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='
|
||||
const storage = mkdtempSync(path.join(tmpdir(), 'pth-media-range-'))
|
||||
|
||||
async function call(method: string, url: string, token?: string, payload?: unknown, headers: Record<string, string> = {}) {
|
||||
return app.inject({
|
||||
method: method as 'GET',
|
||||
url,
|
||||
payload: payload as Record<string, unknown>,
|
||||
headers: { ...(token ? { authorization: `Bearer ${token}` } : {}), ...headers },
|
||||
remoteAddress: nextIp(),
|
||||
})
|
||||
}
|
||||
|
||||
describe.skipIf(!TEST_DB)('souvenir lu par morceaux, vraie base', () => {
|
||||
let token: string
|
||||
let url: string
|
||||
let treeId: string
|
||||
let personId: string
|
||||
let whole: Buffer
|
||||
|
||||
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: `range-${run}@exemple.fr`, password: 'mot-de-passe-solide', firstName: 'Hélène' })
|
||||
token = owner.json().token
|
||||
const tree = await call('POST', '/trees', token, { name: 'Arbre de démo', slug: `range-${run}`, visitorPassword: 'partage-demo-1', contributorPassword: 'partage-demo-1' })
|
||||
treeId = tree.json().tree?.id ?? tree.json().id
|
||||
const person = await call('POST', `/trees/${treeId}/persons`, token, { firstName: 'Odette', lastName: 'Duval' })
|
||||
personId = person.json().person?.id ?? person.json().id
|
||||
const sent = await call('POST', `/trees/${treeId}/persons/${personId}/media`, token, {
|
||||
type: 'photo', fileName: 'photo.png', mimeType: 'image/png', sizeBytes: Buffer.from(PIXEL, 'base64').length, dataBase64: PIXEL,
|
||||
})
|
||||
expect(sent.statusCode).toBe(201)
|
||||
const media = sent.json().media ?? sent.json()
|
||||
url = `/trees/${treeId}/media/${media.id}`
|
||||
const full = await call('GET', url, token)
|
||||
expect(full.statusCode).toBe(200)
|
||||
whole = full.rawPayload
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
await app?.close()
|
||||
})
|
||||
|
||||
it('sans plage : tout le fichier, et l annonce des plages', async () => {
|
||||
const res = await call('GET', url, token)
|
||||
expect(res.statusCode).toBe(200)
|
||||
expect(res.headers['accept-ranges']).toBe('bytes')
|
||||
expect(Number(res.headers['content-length'])).toBe(whole.length)
|
||||
expect(res.headers['content-type']).toBe('image/png')
|
||||
})
|
||||
|
||||
it('les deux premiers octets, comme Safari avant une vidéo', async () => {
|
||||
const res = await call('GET', url, token, undefined, { range: 'bytes=0-1' })
|
||||
expect(res.statusCode).toBe(206)
|
||||
expect(res.headers['content-range']).toBe(`bytes 0-1/${whole.length}`)
|
||||
expect(res.rawPayload.equals(whole.subarray(0, 2))).toBe(true)
|
||||
})
|
||||
|
||||
it('la fin du fichier, et une plage hors du fichier', async () => {
|
||||
const tail = await call('GET', url, token, undefined, { range: 'bytes=-10' })
|
||||
expect(tail.statusCode).toBe(206)
|
||||
expect(tail.rawPayload.equals(whole.subarray(whole.length - 10))).toBe(true)
|
||||
const out = await call('GET', url, token, undefined, { range: `bytes=${whole.length}-` })
|
||||
expect(out.statusCode).toBe(416)
|
||||
expect(out.headers['content-range']).toBe(`bytes */${whole.length}`)
|
||||
})
|
||||
|
||||
it('les droits passent avant la plage, souvenir en attente compris', async () => {
|
||||
expect((await call('GET', url, undefined, undefined, { range: 'bytes=0-1' })).statusCode).toBe(401)
|
||||
// Un membre envoie un souvenir, qui attend la relecture ; un autre membre le demande par morceaux
|
||||
const register = async (name: string) => (await call('POST', '/auth/register', undefined, { email: `${name}-${run}@exemple.fr`, password: 'mot-de-passe-solide', firstName: name })).json().token as string
|
||||
const author = await register('auteur')
|
||||
const reader = await register('lecteur')
|
||||
for (const t of [author, reader]) expect((await call('POST', `/trees/${treeId}/access/unlock`, t, { password: 'partage-demo-1' })).statusCode).toBe(200)
|
||||
const sent = await call('POST', `/trees/${treeId}/persons/${personId}/media`, author, {
|
||||
type: 'photo', fileName: 'photo.png', mimeType: 'image/png', sizeBytes: Buffer.from(PIXEL, 'base64').length, dataBase64: PIXEL,
|
||||
})
|
||||
const pending = sent.json().media ?? sent.json()
|
||||
expect(pending.status).toBe('pending')
|
||||
const pendingUrl = `/trees/${treeId}/media/${pending.id}`
|
||||
expect((await call('GET', pendingUrl, reader, undefined, { range: 'bytes=0-1' })).statusCode).toBe(404)
|
||||
expect((await call('GET', pendingUrl, author, undefined, { range: 'bytes=0-1' })).statusCode).toBe(206)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,31 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseByteRange } from '../src/lib/media-files.js'
|
||||
|
||||
// Plages demandées par les navigateurs pour lire une vidéo (Safari ne lit rien sans elles)
|
||||
describe('parseByteRange', () => {
|
||||
it('lit les plages que demandent Safari et Chrome', () => {
|
||||
expect(parseByteRange('bytes=0-1', 1000)).toEqual({ start: 0, end: 1 })
|
||||
expect(parseByteRange('bytes=0-', 1000)).toEqual({ start: 0, end: 999 })
|
||||
expect(parseByteRange('bytes=500-', 1000)).toEqual({ start: 500, end: 999 })
|
||||
expect(parseByteRange('bytes=-100', 1000)).toEqual({ start: 900, end: 999 })
|
||||
})
|
||||
|
||||
it('borne la fin à la taille du fichier', () => {
|
||||
expect(parseByteRange('bytes=900-5000', 1000)).toEqual({ start: 900, end: 999 })
|
||||
expect(parseByteRange('bytes=-5000', 1000)).toEqual({ start: 0, end: 999 })
|
||||
})
|
||||
|
||||
it('refuse une plage hors du fichier', () => {
|
||||
expect(parseByteRange('bytes=1000-', 1000)).toBe('unsatisfiable')
|
||||
expect(parseByteRange('bytes=5-2', 1000)).toBe('unsatisfiable')
|
||||
expect(parseByteRange('bytes=-0', 1000)).toBe('unsatisfiable')
|
||||
expect(parseByteRange('bytes=-5', 0)).toBe('unsatisfiable')
|
||||
})
|
||||
|
||||
it('envoie tout sans plage lisible', () => {
|
||||
expect(parseByteRange(undefined, 1000)).toBeNull()
|
||||
expect(parseByteRange('bytes=-', 1000)).toBeNull()
|
||||
expect(parseByteRange('bytes=0-1,5-9', 1000)).toBeNull()
|
||||
expect(parseByteRange('items=0-1', 1000)).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -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),
|
||||
|
||||
@@ -6,6 +6,12 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vites
|
||||
// fournisseur à part. Ce fichier vérifie ce que Parenthèse décide avec ce que le fournisseur renvoie.
|
||||
const { prismaMock, oidcMock } = 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(),
|
||||
@@ -108,7 +114,7 @@ function fragmentOf(location: string | undefined) {
|
||||
describe('départ et retour', () => {
|
||||
it("annonce le fournisseur à l'écran de connexion", async () => {
|
||||
const res = await app.inject({ method: 'GET', url: '/auth/options' })
|
||||
expect(res.json()).toEqual({ registration: true, passwordLogin: true, oidc: { name: 'Authentik' } })
|
||||
expect(res.json()).toEqual({ registration: true, passwordLogin: true, oidc: { name: 'Authentik' }, signupPrompts: false })
|
||||
})
|
||||
|
||||
it('part chez le fournisseur avec un cookie signé, httpOnly, lax, sécurisé en https', async () => {
|
||||
@@ -337,6 +343,89 @@ describe('connexion par le fournisseur seulement (PASSWORD_LOGIN=false)', () =>
|
||||
}, 15000)
|
||||
})
|
||||
|
||||
describe('rattacher le fournisseur à un compte à mot de passe (avant PASSWORD_LOGIN=false)', () => {
|
||||
const sessionOf = (userId: string) => app.jwt.sign({ kind: 'user', sub: userId, jti: `s-${userId}`, userId, email: 'anais@example.com' })
|
||||
|
||||
async function ticketFor(userId: string) {
|
||||
const res = await app.inject({ method: 'POST', url: '/auth/oidc/link', headers: { authorization: `Bearer ${sessionOf(userId)}` }, remoteAddress: nextAddress() })
|
||||
expect(res.statusCode).toBe(200)
|
||||
return res.json().ticket as string
|
||||
}
|
||||
|
||||
async function startLink(ticket: string) {
|
||||
currentAddress = nextAddress()
|
||||
const res = await app.inject({ method: 'GET', url: `/auth/oidc/start?link=${encodeURIComponent(ticket)}&returnTo=${encodeURIComponent('/arbre/abc')}`, remoteAddress: currentAddress })
|
||||
return { res, cookie: String(res.headers['set-cookie']).split(';')[0] }
|
||||
}
|
||||
|
||||
it('sans session, pas de ticket', async () => {
|
||||
const res = await app.inject({ method: 'POST', url: '/auth/oidc/link', remoteAddress: nextAddress() })
|
||||
expect(res.statusCode).toBe(401)
|
||||
})
|
||||
|
||||
it("relie l'identité au compte qui a demandé le ticket, même avec un mot de passe et sans regarder l'email", async () => {
|
||||
const ticket = await ticketFor('user-pw')
|
||||
const { res: started, cookie } = await startLink(ticket)
|
||||
expect(started.statusCode).toBe(302)
|
||||
// Le retour de l'app ne vient pas de la requête : un rattachement revient toujours à la racine
|
||||
expect(oidcMock.startAuthorization).toHaveBeenCalledWith('/')
|
||||
prismaMock.user.findUnique.mockResolvedValue({ id: 'user-pw' })
|
||||
oidcMock.finishAuthorization.mockResolvedValue({ ...identity, email: 'autre@example.com', emailVerified: false })
|
||||
const res = await callback(cookie)
|
||||
expect(prismaMock.userIdentity.create).toHaveBeenCalledWith({ data: { userId: 'user-pw', issuer: ISSUER, subject: 'sub-1' } })
|
||||
const code = fragmentOf(res.headers.location).get('oidc') as string
|
||||
expect(app.jwt.decode<{ sub: string }>(code)?.sub).toBe('user-pw')
|
||||
// Le rattachement ne passe jamais par la recherche d'un compte par email ni par la création d'un compte
|
||||
expect(prismaMock.user.create).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it("une identité déjà reliée à un autre compte n'est jamais déplacée", async () => {
|
||||
const ticket = await ticketFor('user-pw')
|
||||
const { cookie } = await startLink(ticket)
|
||||
prismaMock.user.findUnique.mockResolvedValue({ id: 'user-pw' })
|
||||
prismaMock.userIdentity.findUnique.mockResolvedValue({ userId: 'user-other' })
|
||||
const res = await callback(cookie)
|
||||
expect(fragmentOf(res.headers.location).get('oidc_error')).toBe('oidc_identity_taken')
|
||||
expect(prismaMock.userIdentity.create).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('déjà reliée à ce compte : connexion, rien de recréé', async () => {
|
||||
const ticket = await ticketFor('user-pw')
|
||||
const { cookie } = await startLink(ticket)
|
||||
prismaMock.user.findUnique.mockResolvedValue({ id: 'user-pw' })
|
||||
prismaMock.userIdentity.findUnique.mockResolvedValue({ userId: 'user-pw' })
|
||||
const res = await callback(cookie)
|
||||
expect(fragmentOf(res.headers.location).get('oidc')).toBeTruthy()
|
||||
expect(prismaMock.userIdentity.create).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('le ticket sert une fois, et un faux ticket ou une session ne lancent rien', async () => {
|
||||
const ticket = await ticketFor('user-pw')
|
||||
expect((await startLink(ticket)).res.statusCode).toBe(302)
|
||||
const again = await startLink(ticket)
|
||||
expect(fragmentOf(again.res.headers.location).get('oidc_error')).toBe('oidc_link_expired')
|
||||
const forged = await startLink('nimportequoi')
|
||||
expect(fragmentOf(forged.res.headers.location).get('oidc_error')).toBe('oidc_link_expired')
|
||||
const session = await startLink(sessionOf('user-pw'))
|
||||
expect(fragmentOf(session.res.headers.location).get('oidc_error')).toBe('oidc_link_expired')
|
||||
})
|
||||
|
||||
it("le ticket n'ouvre aucune session", async () => {
|
||||
const ticket = await ticketFor('user-pw')
|
||||
const asBearer = await app.inject({ method: 'GET', url: '/auth/me', headers: { authorization: `Bearer ${ticket}` } })
|
||||
expect(asBearer.statusCode).toBe(401)
|
||||
})
|
||||
|
||||
it('compte supprimé entre le ticket et le retour : refusé', async () => {
|
||||
const ticket = await ticketFor('user-pw')
|
||||
const { cookie } = await startLink(ticket)
|
||||
prismaMock.user.findUnique.mockResolvedValue(null)
|
||||
const res = await callback(cookie)
|
||||
expect(fragmentOf(res.headers.location).get('oidc_error')).toBe('oidc_failed')
|
||||
expect(prismaMock.userIdentity.create).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
describe('journaux', () => {
|
||||
it("le code d'autorisation du retour n'est pas journalisé", async () => {
|
||||
const { redactUrl } = await import('../src/app.js')
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
import { existsSync, mkdtempSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import path from 'node:path'
|
||||
|
||||
import type { FastifyInstance } from 'fastify'
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
||||
|
||||
// Propositions de la famille sur l'arbre (1.5.1) : photos posées sur l'arbre, annotations posées par le serveur
|
||||
// à l'acceptation, état d'une proposition. Sur une vraie base, comme toute règle de droits :
|
||||
// TEST_DATABASE_URL=postgresql://postgres:postgres@localhost:5432/genealogy_test npx vitest run test/propositions-fantomes.db.test.ts
|
||||
const TEST_DB = process.env.TEST_DATABASE_URL
|
||||
|
||||
let app: FastifyInstance
|
||||
let env: { ALLOW_REGISTRATION: boolean; MEDIA_STORAGE_PATH: string }
|
||||
let prisma: typeof import('../src/lib/prisma.js')['prisma']
|
||||
let ip = 0
|
||||
const nextIp = () => `10.2.${Math.floor(++ip / 250)}.${ip % 250 + 1}`
|
||||
const run = Date.now().toString(36)
|
||||
const mail = (name: string) => `${name}-${run}@exemple.fr`
|
||||
// PNG d'un pixel
|
||||
const PIXEL = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='
|
||||
const storage = mkdtempSync(path.join(tmpdir(), 'pth-151-'))
|
||||
|
||||
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 account(name: string) {
|
||||
const res = await call('POST', '/auth/register', undefined, { email: mail(name), password: 'mot-de-passe-solide', firstName: name })
|
||||
expect(res.status).toBe(201)
|
||||
return { token: res.body.token as string, id: res.body.user.id as string }
|
||||
}
|
||||
|
||||
describe.skipIf(!TEST_DB)('propositions de la famille sur l\'arbre, vraie base', () => {
|
||||
let owner: { token: string; id: string }
|
||||
let treeId: string
|
||||
let family: 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'))
|
||||
;({ prisma } = await import('../src/lib/prisma.js'))
|
||||
const { createApp } = await import('../src/app.js')
|
||||
app = createApp()
|
||||
env.ALLOW_REGISTRATION = true
|
||||
env.MEDIA_STORAGE_PATH = storage
|
||||
owner = await account('proprio')
|
||||
const tree = await call('POST', '/trees', owner.token, { name: 'Arbre de démo', slug: `fantomes-${run}`, visitorPassword: 'partage-demo-1', contributorPassword: 'partage-demo-1' })
|
||||
expect(tree.status).toBe(201)
|
||||
treeId = tree.body.tree?.id ?? tree.body.id
|
||||
const unlocked = await call('POST', `/trees/${treeId}/access/unlock`, undefined, { password: 'partage-demo-1' })
|
||||
expect(unlocked.status).toBe(200)
|
||||
family = unlocked.body.token
|
||||
})
|
||||
|
||||
afterAll(async () => {
|
||||
await app?.close()
|
||||
})
|
||||
|
||||
const upload = (token?: string) => call('POST', `/trees/${treeId}/annotation-photos`, token, {
|
||||
fileName: 'photo.png', mimeType: 'image/png', sizeBytes: Buffer.from(PIXEL, 'base64').length, dataBase64: PIXEL,
|
||||
})
|
||||
const photoAnnotation = (photoPath: string) => ({ type: 'photo', x: 10, y: 20, content: JSON.stringify({ photoPath, width: 1, height: 1 }), style: {}, zIndex: 1 })
|
||||
const propose = (token: string, changes: unknown[]) => call('POST', `/trees/${treeId}/contributions/sessions`, token, { title: 'Proposition de la famille', submittedByLabel: 'Cousine', changes })
|
||||
const review = (sessionId: string, decision: 'approved' | 'rejected') => call('POST', `/trees/${treeId}/contributions/sessions/${sessionId}/review`, owner.token, { decision })
|
||||
const annotations = async () => (await call('GET', `/trees/${treeId}/annotations`, owner.token)).body.annotations as Array<{ id: string; type: string; content: string }>
|
||||
const fileOf = async (photoId: string) => (await prisma.annotationPhotoUpload.findUnique({ where: { id: photoId } }))?.filePath
|
||||
|
||||
it("personne d'extérieur ne pose une photo : sans jeton 401, un compte sans lien avec l'arbre 403", async () => {
|
||||
expect((await upload()).status).toBe(401)
|
||||
const stranger = await account('inconnu')
|
||||
expect((await upload(stranger.token)).status).toBe(403)
|
||||
})
|
||||
|
||||
it('la photo de la famille attend la relecture, puis devient une annotation au moment où elle est acceptée', async () => {
|
||||
const sent = await upload(family)
|
||||
expect(sent.status).toBe(201)
|
||||
const filePath = await fileOf(sent.body.photoId)
|
||||
expect(filePath).toBeTruthy()
|
||||
|
||||
const proposed = await propose(family, [{ entityType: 'annotation', action: 'create', after: photoAnnotation(sent.body.photoPath) }])
|
||||
expect(proposed.status).toBe(201)
|
||||
expect((await annotations()).some((a) => a.content.includes(sent.body.photoId))).toBe(false)
|
||||
|
||||
expect((await review(proposed.body.session.id, 'approved')).status).toBe(200)
|
||||
expect((await annotations()).some((a) => a.type === 'photo' && a.content.includes(sent.body.photoId))).toBe(true)
|
||||
expect(await fileOf(sent.body.photoId)).toBeUndefined()
|
||||
expect(existsSync(path.join(storage, filePath as string))).toBe(true)
|
||||
})
|
||||
|
||||
it('refusée, la photo de la famille est effacée du disque', async () => {
|
||||
const sent = await upload(family)
|
||||
const filePath = await fileOf(sent.body.photoId) as string
|
||||
const proposed = await propose(family, [{ entityType: 'annotation', action: 'create', after: photoAnnotation(sent.body.photoPath) }])
|
||||
expect((await review(proposed.body.session.id, 'rejected')).status).toBe(200)
|
||||
expect(await fileOf(sent.body.photoId)).toBeUndefined()
|
||||
expect(existsSync(path.join(storage, filePath))).toBe(false)
|
||||
expect((await annotations()).some((a) => a.content.includes(sent.body.photoId))).toBe(false)
|
||||
})
|
||||
|
||||
it('un dessin accepté est posé par le serveur, sans geste du navigateur', async () => {
|
||||
const before = (await annotations()).length
|
||||
const proposed = await propose(family, [{ entityType: 'annotation', action: 'create', after: { type: 'drawing', x: 1, y: 2, content: 'M0 0 L10 10', style: { color: '#b4532a' } } }])
|
||||
expect((await review(proposed.body.session.id, 'approved')).status).toBe(200)
|
||||
expect((await annotations()).length).toBe(before + 1)
|
||||
})
|
||||
|
||||
it("une ancienne proposition d'annotation incomplète est écartée sans bloquer le reste de la relecture", async () => {
|
||||
const before = (await annotations()).length
|
||||
const session = await prisma.contributionSession.create({
|
||||
data: {
|
||||
treeId, submittedByLabel: 'Cousine', mode: 'tree_access', status: 'pending', title: 'Avant la 1.5.1',
|
||||
changes: { create: [
|
||||
{ entityType: 'annotation', action: 'create', afterJson: { type: 'drawing', x: 0, y: 0 } },
|
||||
{ entityType: 'annotation', action: 'create', afterJson: { type: 'text', x: 5, y: 5, content: 'Mamie' } },
|
||||
] },
|
||||
},
|
||||
})
|
||||
const reviewed = await review(session.id, 'approved')
|
||||
expect(reviewed.status).toBe(200)
|
||||
expect(reviewed.body.approvedCount).toBe(1)
|
||||
expect(reviewed.body.rejectedCount).toBe(1)
|
||||
expect((await annotations()).length).toBe(before + 1)
|
||||
})
|
||||
|
||||
it("une photo qui n'est pas de cet arbre est refusée dès l'envoi", async () => {
|
||||
const res = await propose(family, [{ entityType: 'annotation', action: 'create', after: photoAnnotation('/trees/un-autre-arbre/annotation-photos/abc') }])
|
||||
expect(res.status).toBe(400)
|
||||
expect(res.body.error).toBe('invalid_annotation_photo_path')
|
||||
})
|
||||
|
||||
it("l'état d'une proposition : lisible par qui lit l'arbre, pas par un compte sans lien", async () => {
|
||||
const proposed = await propose(family, [{ entityType: 'annotation', action: 'create', after: { type: 'sticker', x: 0, y: 0, content: '🌳' } }])
|
||||
const url = `/trees/${treeId}/contributions/sessions/${proposed.body.session.id}/status`
|
||||
expect((await call('GET', url, family)).body.status).toBe('pending')
|
||||
const stranger = await account('curieux')
|
||||
expect((await call('GET', url, stranger.token)).status).toBe(403)
|
||||
await review(proposed.body.session.id, 'approved')
|
||||
expect((await call('GET', url, family)).body.status).toBe('approved')
|
||||
})
|
||||
|
||||
it("un envoi jamais proposé depuis 7 jours est effacé au suivant ; celui d'une proposition en attente reste", async () => {
|
||||
const orphan = await upload(family)
|
||||
const kept = await upload(family)
|
||||
await propose(family, [{ entityType: 'annotation', action: 'create', after: photoAnnotation(kept.body.photoPath) }])
|
||||
const old = new Date(Date.now() - 8 * 24 * 60 * 60 * 1000)
|
||||
await prisma.annotationPhotoUpload.updateMany({ where: { id: { in: [orphan.body.photoId, kept.body.photoId] } }, data: { createdAt: old } })
|
||||
const orphanPath = await fileOf(orphan.body.photoId) as string
|
||||
|
||||
expect((await upload(family)).status).toBe(201)
|
||||
expect(await fileOf(orphan.body.photoId)).toBeUndefined()
|
||||
expect(existsSync(path.join(storage, orphanPath))).toBe(false)
|
||||
expect(await fileOf(kept.body.photoId)).toBeTruthy()
|
||||
})
|
||||
|
||||
it('revue : refusée puis acceptée dans la même relecture, la photo reste sur le disque', async () => {
|
||||
const sent = await upload(family)
|
||||
const filePath = await fileOf(sent.body.photoId) as string
|
||||
const proposed = await propose(family, [
|
||||
{ entityType: 'annotation', action: 'create', after: photoAnnotation(sent.body.photoPath) },
|
||||
{ entityType: 'annotation', action: 'create', after: { ...photoAnnotation(sent.body.photoPath), x: 99 } },
|
||||
])
|
||||
const session = await prisma.contributionSession.findUnique({ where: { id: proposed.body.session.id }, include: { changes: { orderBy: { createdAt: 'asc' } } } })
|
||||
const [first, second] = session!.changes
|
||||
const res = await call('POST', `/trees/${treeId}/contributions/sessions/${session!.id}/review`, owner.token, {
|
||||
decision: 'approved',
|
||||
changeDecisions: [{ changeId: first.id, decision: 'rejected' }, { changeId: second.id, decision: 'approved' }],
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(existsSync(path.join(storage, filePath))).toBe(true)
|
||||
})
|
||||
|
||||
it("revue : un chemin de photo échappé dans le JSON compte quand même comme cité par une proposition en attente", async () => {
|
||||
const sent = await upload(family)
|
||||
const filePath = await fileOf(sent.body.photoId) as string
|
||||
const plain = await propose(family, [{ entityType: 'annotation', action: 'create', after: photoAnnotation(sent.body.photoPath) }])
|
||||
const escaped = `{"photoPath":"${sent.body.photoPath.replaceAll('/', '\/')}","width":1,"height":1}`
|
||||
const other = await propose(family, [{ entityType: 'annotation', action: 'create', after: { type: 'photo', x: 1, y: 1, content: escaped } }])
|
||||
expect(other.status).toBe(201)
|
||||
await review(plain.body.session.id, 'rejected')
|
||||
expect(existsSync(path.join(storage, filePath))).toBe(true)
|
||||
await review(other.body.session.id, 'approved')
|
||||
expect((await annotations()).some((a) => a.content.includes(sent.body.photoId))).toBe(true)
|
||||
expect(existsSync(path.join(storage, filePath))).toBe(true)
|
||||
})
|
||||
|
||||
it('revue : 70 envois simultanés sur un arbre neuf ne dépassent pas le plafond de 50', async () => {
|
||||
const fresh = await call('POST', '/trees', owner.token, { name: 'Arbre neuf', slug: `neuf-${run}`, visitorPassword: 'partage-neuf-1', contributorPassword: 'partage-neuf-1' })
|
||||
const freshId = fresh.body.tree?.id ?? fresh.body.id
|
||||
const access = (await call('POST', `/trees/${freshId}/access/unlock`, undefined, { password: 'partage-neuf-1' })).body.token
|
||||
const results = await Promise.all(Array.from({ length: 70 }, () => call('POST', `/trees/${freshId}/annotation-photos`, access, {
|
||||
fileName: 'photo.png', mimeType: 'image/png', sizeBytes: Buffer.from(PIXEL, 'base64').length, dataBase64: PIXEL,
|
||||
})))
|
||||
expect(results.filter((r) => r.status === 201).length).toBe(50)
|
||||
expect(await prisma.annotationPhotoUpload.count({ where: { treeId: freshId } })).toBe(50)
|
||||
})
|
||||
|
||||
it('au-delà de 50 photos en attente sur un arbre, la famille est arrêtée ; un gestionnaire non', async () => {
|
||||
const existing = await prisma.annotationPhotoUpload.count({ where: { treeId } })
|
||||
await prisma.annotationPhotoUpload.createMany({
|
||||
data: Array.from({ length: 50 - existing }, (_, index) => ({ id: `rempli-${run}-${index}`, treeId, filePath: `${treeId}/annotation-photos/rempli-${index}.png` })),
|
||||
})
|
||||
expect((await upload(family)).status).toBe(429)
|
||||
expect((await upload(owner.token)).status).toBe(201)
|
||||
})
|
||||
})
|
||||
@@ -5,6 +5,12 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vites
|
||||
// se connectent, et une instance neuve accepte quand même son premier compte.
|
||||
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(),
|
||||
@@ -21,7 +27,7 @@ vi.mock('../src/lib/prisma.js', () => ({
|
||||
}))
|
||||
|
||||
let app: FastifyInstance
|
||||
let env: { ALLOW_REGISTRATION: boolean }
|
||||
let env: { ALLOW_REGISTRATION: boolean, SIGNUP_PROMPTS: boolean }
|
||||
|
||||
const newAccount = { firstName: 'Camille', email: 'camille@example.com', password: 'securepass123' }
|
||||
|
||||
@@ -44,6 +50,7 @@ afterAll(async () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
env.ALLOW_REGISTRATION = false
|
||||
env.SIGNUP_PROMPTS = false
|
||||
prismaMock.user.findUnique.mockResolvedValue(null)
|
||||
prismaMock.user.count.mockResolvedValue(3)
|
||||
prismaMock.user.create.mockResolvedValue({ id: 'user-1', email: newAccount.email, firstName: 'Camille' })
|
||||
@@ -96,7 +103,7 @@ describe('inscription fermée', () => {
|
||||
const res = await app.inject({ method: 'GET', url: '/auth/options' })
|
||||
|
||||
expect(res.statusCode).toBe(200)
|
||||
expect(res.json()).toEqual({ registration: false, passwordLogin: true, oidc: null })
|
||||
expect(res.json()).toEqual({ registration: false, passwordLogin: true, oidc: null, signupPrompts: false })
|
||||
})
|
||||
|
||||
it('instance neuve : le premier compte se crée, sous verrou', async () => {
|
||||
@@ -139,3 +146,22 @@ describe('inscription ouverte (par défaut)', () => {
|
||||
expect(prismaMock.user.count).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
// Invitations à créer son arbre (SIGNUP_PROMPTS) : éteintes par défaut, jamais annoncées quand l'instance ne crée plus de compte
|
||||
describe('invitations à créer son arbre', () => {
|
||||
it('éteintes par défaut', async () => {
|
||||
env.ALLOW_REGISTRATION = true
|
||||
expect((await app.inject({ method: 'GET', url: '/auth/options' })).json().signupPrompts).toBe(false)
|
||||
})
|
||||
|
||||
it('allumées avec SIGNUP_PROMPTS et une inscription ouverte', async () => {
|
||||
env.ALLOW_REGISTRATION = true
|
||||
env.SIGNUP_PROMPTS = true
|
||||
expect((await app.inject({ method: 'GET', url: '/auth/options' })).json().signupPrompts).toBe(true)
|
||||
})
|
||||
|
||||
it("coupées quand l'inscription est fermée, même allumées", async () => {
|
||||
env.SIGNUP_PROMPTS = true
|
||||
expect((await app.inject({ method: 'GET', url: '/auth/options' })).json().signupPrompts).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,50 @@
|
||||
import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
// Les sessions fermées se rechargent avant la première requête : sans elles, l'API refuse de démarrer plutôt que
|
||||
// de rouvrir chaque session fermée sans que personne le voie.
|
||||
const { prismaMock } = vi.hoisted(() => ({
|
||||
prismaMock: {
|
||||
revokedSession: {
|
||||
upsert: vi.fn(),
|
||||
findMany: vi.fn(),
|
||||
deleteMany: vi.fn().mockResolvedValue({ count: 0 }),
|
||||
},
|
||||
$disconnect: vi.fn(),
|
||||
},
|
||||
}))
|
||||
|
||||
vi.mock('../src/lib/prisma.js', () => ({
|
||||
prisma: prismaMock,
|
||||
}))
|
||||
|
||||
describe('sessions fermées au démarrage', () => {
|
||||
let createApp: typeof import('../src/app.js')['createApp']
|
||||
|
||||
beforeAll(async () => {
|
||||
process.env.NODE_ENV = 'test'
|
||||
process.env.DATABASE_URL = 'postgresql://postgres:postgres@localhost:5432/genealogy'
|
||||
process.env.JWT_SECRET = 'test-secret-with-sufficient-length'
|
||||
process.env.CORS_ORIGIN = 'http://localhost:5173'
|
||||
;({ createApp } = await import('../src/app.js'))
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('recharge les sessions fermées, et un jeton fermé est refusé dès la première requête', async () => {
|
||||
prismaMock.revokedSession.findMany.mockResolvedValue([{ jti: 'ferme-1', expiresAt: new Date(Date.now() + 3600_000) }])
|
||||
const app = createApp()
|
||||
await app.ready()
|
||||
const { isUserTokenRevoked } = await import('../src/lib/token-revocation.js')
|
||||
expect(isUserTokenRevoked('ferme-1')).toBe(true)
|
||||
expect(prismaMock.revokedSession.deleteMany).toHaveBeenCalled()
|
||||
await app.close()
|
||||
})
|
||||
|
||||
it('ne démarre pas si la base ne répond pas', async () => {
|
||||
prismaMock.revokedSession.findMany.mockRejectedValue(new Error('base injoignable'))
|
||||
const app = createApp()
|
||||
await expect(app.ready()).rejects.toThrow('base injoignable')
|
||||
})
|
||||
})
|
||||
@@ -7,6 +7,12 @@ import { afterEach, beforeAll, 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().mockResolvedValue(1) },
|
||||
treeMembership: { findUnique: vi.fn() },
|
||||
userTreeAccess: { findUnique: vi.fn().mockResolvedValue(null) },
|
||||
|
||||
@@ -20,6 +20,7 @@ Chaque push sur `main` lance d'abord la CI (`.github/workflows/ci.yml`). Si elle
|
||||
- `/etc/parenthese/build.env` : variables de build du front et de la landing (`VITE_POSTHOG_KEY`, `VITE_POSTHOG_HOST`)
|
||||
- `/etc/cron.d/parenthese-backup` : sauvegarde nocturne par `deploy/backup.sh`
|
||||
- `/etc/genealogy/backup.env` (facultatif) : rétention et envoi S3 des sauvegardes
|
||||
- `/usr/local/sbin/parenthese-ssh-deploy` : copie de `deploy/ssh-deploy.sh`, commande forcée de la clé de déploiement (voir plus bas)
|
||||
|
||||
## Prérequis du serveur
|
||||
|
||||
@@ -28,3 +29,19 @@ Node 20, `pm2` en global, PostgreSQL joignable par `DATABASE_URL`, nginx configu
|
||||
## Déployer à la main
|
||||
|
||||
`bash deploy/deploy.sh --sync` depuis le dépôt sur le serveur. `FORCE_FULL=1` pour tout reconstruire. Ne pas le lancer pendant un déploiement GitHub : le verrou le fera attendre.
|
||||
|
||||
## Clé de déploiement restreinte
|
||||
|
||||
La clé de GitHub ne doit pouvoir que déployer un commit de `main`, jamais lancer une autre commande sur le serveur. On la lie à `deploy/ssh-deploy.sh`, copié hors du dépôt parce que le déploiement réécrit le dépôt :
|
||||
|
||||
```
|
||||
install -m 755 -o root -g root /var/www/parenthese/deploy/ssh-deploy.sh /usr/local/sbin/parenthese-ssh-deploy
|
||||
```
|
||||
|
||||
Puis, dans `authorized_keys`, devant la ligne de la clé `github-actions-parenthese-public` :
|
||||
|
||||
```
|
||||
command="/usr/local/sbin/parenthese-ssh-deploy",no-port-forwarding,no-agent-forwarding,no-X11-forwarding,no-pty ssh-ed25519 AAAA… github-actions-parenthese-public
|
||||
```
|
||||
|
||||
Le workflow n'a pas à changer. Après une mise à jour de `deploy/ssh-deploy.sh`, refaire l'`install`.
|
||||
+5
-1
@@ -133,8 +133,12 @@ predeploy_dump() {
|
||||
BACKEND_CHANGED=0
|
||||
if changed backend ecosystem.config.cjs; then
|
||||
BACKEND_CHANGED=1
|
||||
# Prisma 7 demande Node ^20.19, ^22.12 ou 24+ : avec un Node plus vieux, on s'arrête avant toute installation
|
||||
node -e "const [a, b] = process.versions.node.split('.').map(Number); process.exit((a === 20 && b >= 19) || (a === 22 && b >= 12) || a >= 24 ? 0 : 1)" \
|
||||
|| { echo "ERROR: Node $(node -v) trop ancien pour Prisma 7 (^20.19, ^22.12 ou 24+)"; exit 1; }
|
||||
install_deps backend
|
||||
(cd "$REPO_DIR/backend" && node -e "require('fastify'); require('zod'); require('@prisma/client')") \
|
||||
# Le client Prisma n'existe qu'après prisma:generate (src/generated) : on vérifie ses dépendances, pas le client
|
||||
(cd "$REPO_DIR/backend" && node -e "require('fastify'); require('zod'); require('@prisma/adapter-pg'); require.resolve('@prisma/client/runtime/client')") \
|
||||
|| { echo "ERROR: dépendances backend manquantes après installation"; exit 1; }
|
||||
log "Build backend"
|
||||
(cd "$REPO_DIR/backend" && NODE_ENV='' npm run prisma:generate && NODE_ENV='' npm run build)
|
||||
|
||||
+5
-1
@@ -33,12 +33,16 @@ map $host $parenthese_app_csp {
|
||||
# script-src 'sha256-...' script en ligne du <head> (animation du logo, dans index.html et en/index.html).
|
||||
# S'il change, recalculer l'empreinte : base64(sha256(contenu exact entre
|
||||
# <script> et </script>)), sinon l'animation ne se joue plus (sans autre effet).
|
||||
# 2e 'sha256-...' règles de préchargement des pages (<script type="speculationrules">, le même
|
||||
# texte dans index.html et chaque guide). Même calcul s'il change, sinon les pages
|
||||
# ne sont plus préchargées (sans autre effet). Le mot-clé 'inline-speculation-rules'
|
||||
# ne suffisait pas à Chrome (essayé le 27/10).
|
||||
# posthog comme pour l'app
|
||||
# style-src 'unsafe-inline' attributs style du rendu serveur React
|
||||
# frame-src démonstration de l'app en iframe
|
||||
# frame-ancestors 'none' équivalent de X-Frame-Options DENY
|
||||
map $host $parenthese_landing_csp {
|
||||
default "default-src 'self'; script-src 'self' 'sha256-Av5a1/yoW/tQ2ZQWqH5FnaL896Bubcs9ivdFvsKZBrU='; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self' https://us.i.posthog.com https://us-assets.i.posthog.com; worker-src 'self' blob:; frame-src https://app.parenthese.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'";
|
||||
default "default-src 'self'; script-src 'self' 'sha256-v68KpM0KHUkaezvOmKtoCY2RsfbwoEC9EZYD682DCiU=' 'sha256-eflWcNn8MfPvX2YD4hXJnR3x9nRGu0f7tIEq2j/yfPo='; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self' data:; connect-src 'self' https://us.i.posthog.com https://us-assets.i.posthog.com; worker-src 'self' blob:; frame-src https://app.parenthese.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'";
|
||||
}
|
||||
|
||||
# Réponses de l'API relayées (JSON, médias des familles) : intégrables seulement par l'app (PDF en iframe).
|
||||
|
||||
Executable
+38
@@ -0,0 +1,38 @@
|
||||
#!/usr/bin/env bash
|
||||
# Commande forcée de la clé de déploiement GitHub, posée devant elle dans /root/.ssh/authorized_keys :
|
||||
# command="/usr/local/sbin/parenthese-ssh-deploy",no-port-forwarding,no-agent-forwarding,no-X11-forwarding,no-pty ssh-ed25519 AAAA… github-actions-parenthese-public
|
||||
# Avec elle, la clé ne peut plus que déployer un commit qui appartient déjà à main : une clé volée ne lance aucune
|
||||
# autre commande. Le workflow « Deploy Hostinger » n'a pas à changer : il envoie
|
||||
# FORCE_FULL=<0|1> DEPLOY_SHA=<sha> bash -s
|
||||
# suivi d'un script sur l'entrée standard. Seuls FORCE_FULL et DEPLOY_SHA sont lus, le script envoyé est ignoré,
|
||||
# et la suite reprend la même logique (verrou, commit de main, pas de retour en arrière, deploy.sh).
|
||||
# Installé hors du dépôt, parce que le déploiement réécrit le dépôt pendant qu'il tourne :
|
||||
# install -m 755 -o root -g root /var/www/parenthese/deploy/ssh-deploy.sh /usr/local/sbin/parenthese-ssh-deploy
|
||||
set -euo pipefail
|
||||
|
||||
if ! [[ "${SSH_ORIGINAL_COMMAND:-}" =~ ^FORCE_FULL=([01])\ DEPLOY_SHA=([0-9a-f]{40})\ bash\ -s$ ]]; then
|
||||
echo "Commande refusée : cette clé ne sert qu'à déployer" >&2
|
||||
exit 1
|
||||
fi
|
||||
FORCE_FULL="${BASH_REMATCH[1]}"
|
||||
DEPLOY_SHA="${BASH_REMATCH[2]}"
|
||||
# Le script envoyé par le workflow n'est pas exécuté
|
||||
cat > /dev/null
|
||||
|
||||
cd /var/www/parenthese
|
||||
exec flock -w 900 /tmp/parenthese-deploy.lock env PARENTHESE_DEPLOY_LOCKED=1 FORCE_FULL="$FORCE_FULL" DEPLOY_SHA="$DEPLOY_SHA" bash -c '
|
||||
set -euo pipefail
|
||||
git fetch -q origin main
|
||||
# Le commit validé doit appartenir à main
|
||||
if ! git merge-base --is-ancestor "$DEPLOY_SHA" origin/main; then
|
||||
echo "Commit $DEPLOY_SHA absent de main : rien n est déployé" >&2
|
||||
exit 1
|
||||
fi
|
||||
# Un déploiement plus récent est déjà en ligne : pas de retour en arrière
|
||||
if [ "$(git rev-parse HEAD)" != "$DEPLOY_SHA" ] && git merge-base --is-ancestor "$DEPLOY_SHA" HEAD; then
|
||||
echo "Version plus récente déjà déployée, $DEPLOY_SHA ignoré"
|
||||
exit 0
|
||||
fi
|
||||
git reset -q --hard "$DEPLOY_SHA"
|
||||
bash deploy/deploy.sh
|
||||
'
|
||||
@@ -12,6 +12,9 @@ module.exports = {
|
||||
PORT: 4000,
|
||||
// nginx relaie vers 127.0.0.1:4000 (deploy/nginx.conf) : l'API n'écoute pas sur les interfaces publiques
|
||||
HOST: '127.0.0.1',
|
||||
// Instance hébergée app.parenthese.io : invite la famille et la démo à créer leur arbre (SIGNUP_PROMPTS,
|
||||
// éteint par défaut en auto-hébergement)
|
||||
SIGNUP_PROMPTS: 'true',
|
||||
},
|
||||
max_memory_restart: '512M',
|
||||
log_date_format: 'YYYY-MM-DD HH:mm:ss Z',
|
||||
|
||||
@@ -8,6 +8,18 @@
|
||||
<meta name="description" content="Parenthèse, l'application. Les arbres partagés sont privés : la vitrine publique est sur parenthese.io." />
|
||||
<!-- Arbres familiaux privés (noms, dates) : l'app ne doit pas être indexée, la vitrine est parenthese.io -->
|
||||
<meta name="robots" content="noindex, nofollow" />
|
||||
<!-- Aperçu d'un lien collé dans WhatsApp, Messenger, iMessage… : le même pour toutes les adresses de l'app.
|
||||
Rien ne vient de l'arbre partagé (ni nom de famille, ni photo) : les robots d'aperçu ne reçoivent que ce texte et l'image de la démo. -->
|
||||
<meta property="og:type" content="website" />
|
||||
<meta property="og:site_name" content="Parenthèse" />
|
||||
<meta property="og:locale" content="fr_FR" />
|
||||
<meta property="og:title" content="Un arbre de famille à parcourir" />
|
||||
<meta property="og:description" content="Photos, voix et souvenirs de la famille, réunis sur un arbre. S'ouvre depuis ce lien, sans compte." />
|
||||
<meta property="og:image" content="https://app.parenthese.io/og-image.png" />
|
||||
<meta property="og:image:width" content="1200" />
|
||||
<meta property="og:image:height" content="630" />
|
||||
<meta property="og:image:alt" content="Un arbre de famille avec des portraits et des souvenirs autour de chaque personne" />
|
||||
<meta name="twitter:card" content="summary_large_image" />
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
Generated
+785
-927
File diff suppressed because it is too large.
Load diff
+10
-10
@@ -12,28 +12,28 @@
|
||||
"test:watch": "vitest"
|
||||
},
|
||||
"dependencies": {
|
||||
"@lucide/icons": "^1.59.0",
|
||||
"lucide-react": "^1.59.0",
|
||||
"posthog-js": "^1.438.12",
|
||||
"@lucide/icons": "^1.66.0",
|
||||
"blurhash": "^2.0.5",
|
||||
"lucide-react": "^1.66.0",
|
||||
"posthog-js": "^1.444.0",
|
||||
"react": "^19.3.1",
|
||||
"react-dom": "^19.3.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^10.0.1",
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"@types/react": "^19.3.0",
|
||||
"@types/react-dom": "^19.3.0",
|
||||
"@vitejs/plugin-react": "^6.1.2",
|
||||
"autoprefixer": "^10.6.1",
|
||||
"eslint": "^10.13.0",
|
||||
"eslint": "^10.14.0",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.7",
|
||||
"globals": "^17.13.0",
|
||||
"postcss": "^8.5.31",
|
||||
"tailwindcss": "^3.4.19",
|
||||
"vite": "^8.3.4",
|
||||
"globals": "^17.14.0",
|
||||
"tailwindcss": "^4.3.3",
|
||||
"vite": "^8.3.5",
|
||||
"vitest": "^5.0.5"
|
||||
},
|
||||
"overrides": {
|
||||
"postcss-selector-parser": "^7.1.6"
|
||||
"minimatch": "^11.0.4"
|
||||
}
|
||||
}
|
||||
@@ -1,6 +0,0 @@
|
||||
export default {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 219 KiB |
@@ -513,13 +513,6 @@
|
||||
|
||||
/* Confirmation "Tout approuver" inline */
|
||||
|
||||
/* Toast succès contribution envoyée */
|
||||
|
||||
@keyframes toastIn {
|
||||
from { opacity: 0; transform: translateX(-50%) translateY(12px); }
|
||||
to { opacity: 1; transform: translateX(-50%) translateY(0); }
|
||||
}
|
||||
|
||||
@media (max-width: 700px) {
|
||||
|
||||
.media-manager-item {
|
||||
|
||||
+584
-234
File diff suppressed because it is too large.
Load diff
@@ -88,6 +88,22 @@ export function oidcStartUrl(returnTo = '/') {
|
||||
return `${API_BASE_URL}/auth/oidc/start?returnTo=${encodeURIComponent(returnTo)}`
|
||||
}
|
||||
|
||||
// Relier le fournisseur au compte connecté : un ticket de deux minutes, à usage unique, puis le départ OIDC qui le porte
|
||||
export async function requestOidcLinkTicket(token) {
|
||||
const data = await apiRequest('/auth/oidc/link', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
})
|
||||
|
||||
return data?.ticket
|
||||
}
|
||||
|
||||
export function oidcLinkUrl(ticket) {
|
||||
return `${API_BASE_URL}/auth/oidc/start?link=${encodeURIComponent(ticket)}`
|
||||
}
|
||||
|
||||
// Jeton de passage reçu au retour du fournisseur, échangé une seule fois contre une session
|
||||
export async function exchangeOidcCode(code) {
|
||||
return apiRequest('/auth/oidc/exchange', {
|
||||
|
||||
@@ -38,13 +38,44 @@ function timeoutSignal(options) {
|
||||
return AbortSignal.timeout(options.timeoutMs ?? (isLargeBody ? UPLOAD_TIMEOUT_MS : DEFAULT_TIMEOUT_MS))
|
||||
}
|
||||
|
||||
// Envois sans doublon (backend/src/lib/idempotency.ts). Un envoi qui n'a pas abouti (délai dépassé, réseau coupé,
|
||||
// erreur) garde sa clé, et le même envoi refait (même adresse, même contenu) la réutilise : si le premier avait en
|
||||
// fait abouti, le serveur renvoie sa réponse au lieu de tout recréer. Une réussite libère la clé, et renvoyer le même
|
||||
// contenu plus tard (un souvenir supprimé puis remis) est un nouvel envoi.
|
||||
const unsettledKeys = new Map()
|
||||
|
||||
// Empreinte rapide du contenu (cyrb53) : crypto.subtle n'existe pas hors HTTPS (auto-hébergement en réseau local)
|
||||
function fingerprint(text) {
|
||||
let h1 = 0xdeadbeef
|
||||
let h2 = 0x41c6ce57
|
||||
for (let i = 0; i < text.length; i += 1) {
|
||||
const ch = text.charCodeAt(i)
|
||||
h1 = Math.imul(h1 ^ ch, 2654435761)
|
||||
h2 = Math.imul(h2 ^ ch, 1597334677)
|
||||
}
|
||||
h1 = Math.imul(h1 ^ (h1 >>> 16), 2246822507) ^ Math.imul(h2 ^ (h2 >>> 13), 3266489909)
|
||||
h2 = Math.imul(h2 ^ (h2 >>> 16), 2246822507) ^ Math.imul(h1 ^ (h1 >>> 13), 3266489909)
|
||||
return `${text.length}:${(h2 >>> 0).toString(36)}${(h1 >>> 0).toString(36)}`
|
||||
}
|
||||
|
||||
// getRandomValues existe aussi hors HTTPS, contrairement à crypto.randomUUID
|
||||
function newIdempotencyKey() {
|
||||
const bytes = new Uint8Array(16)
|
||||
crypto.getRandomValues(bytes)
|
||||
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')
|
||||
}
|
||||
|
||||
async function apiRequest(path, options = {}) {
|
||||
const { timeoutMs: _timeoutMs, ...fetchOptions } = options
|
||||
const { timeoutMs: _timeoutMs, idempotent = false, ...fetchOptions } = options
|
||||
const providedHeaders = options.headers || {}
|
||||
const hasExplicitContentType = Object.keys(providedHeaders).some((key) => key.toLowerCase() === 'content-type')
|
||||
|
||||
const print = idempotent ? `${path}|${fingerprint(typeof options.body === 'string' ? options.body : '')}` : null
|
||||
if (print && !unsettledKeys.has(print)) unsettledKeys.set(print, newIdempotencyKey())
|
||||
|
||||
const headers = {
|
||||
...(options.body !== undefined && !hasExplicitContentType ? { 'Content-Type': 'application/json' } : {}),
|
||||
...(print ? { 'Idempotency-Key': unsettledKeys.get(print) } : {}),
|
||||
...providedHeaders,
|
||||
}
|
||||
|
||||
@@ -68,6 +99,7 @@ async function apiRequest(path, options = {}) {
|
||||
if (!response.ok) {
|
||||
throw new ApiError(payload?.error || `request_failed_${response.status}`, response.status, payload)
|
||||
}
|
||||
if (print) unsettledKeys.delete(print)
|
||||
|
||||
return payload
|
||||
}
|
||||
|
||||
@@ -34,3 +34,52 @@ describe('apiRequest', () => {
|
||||
expect(error).not.toBeInstanceOf(ApiError)
|
||||
})
|
||||
})
|
||||
|
||||
// Clé d'idempotence : gardée tant que l'envoi n'a pas abouti, libérée par une réussite
|
||||
describe('apiRequest, envois idempotents', () => {
|
||||
const keysSent = []
|
||||
const respond = (ok) => vi.fn(async (_url, init) => {
|
||||
keysSent.push(init.headers['Idempotency-Key'])
|
||||
if (ok === 'network') throw new TypeError('Failed to fetch')
|
||||
return new Response('{}', { status: ok ? 201 : 503 })
|
||||
})
|
||||
const send = (body = '{"a":1}') => apiRequest('/trees/t/annotation-photos', { method: 'POST', idempotent: true, body })
|
||||
|
||||
afterEach(() => {
|
||||
keysSent.length = 0
|
||||
})
|
||||
|
||||
it('un envoi refait après une coupure ou une erreur garde la même clé', async () => {
|
||||
vi.stubGlobal('fetch', respond('network'))
|
||||
await expect(send()).rejects.toThrow()
|
||||
vi.stubGlobal('fetch', respond(false))
|
||||
await expect(send()).rejects.toThrow()
|
||||
vi.stubGlobal('fetch', respond(true))
|
||||
await send()
|
||||
expect(keysSent).toHaveLength(3)
|
||||
expect(new Set(keysSent).size).toBe(1)
|
||||
expect(keysSent[0]).toMatch(/^[0-9a-f]{32}$/)
|
||||
})
|
||||
|
||||
it('après une réussite, le même contenu repart avec une clé neuve', async () => {
|
||||
vi.stubGlobal('fetch', respond(true))
|
||||
await send('{"b":2}')
|
||||
await send('{"b":2}')
|
||||
expect(keysSent[0]).not.toBe(keysSent[1])
|
||||
})
|
||||
|
||||
it('un autre contenu a sa propre clé, et un appel ordinaire n’en envoie pas', async () => {
|
||||
vi.stubGlobal('fetch', respond('network'))
|
||||
await expect(send('{"c":3}')).rejects.toThrow()
|
||||
await expect(send('{"c":4}')).rejects.toThrow()
|
||||
await expect(apiRequest('/trees/t', { method: 'POST', body: '{}' })).rejects.toThrow()
|
||||
expect(keysSent[0]).not.toBe(keysSent[1])
|
||||
expect(keysSent[2]).toBeUndefined()
|
||||
})
|
||||
|
||||
it('l’option idempotent ne part pas dans fetch', async () => {
|
||||
vi.stubGlobal('fetch', respond(true))
|
||||
await send('{"d":5}')
|
||||
expect(fetch.mock.calls[0][1]).not.toHaveProperty('idempotent')
|
||||
})
|
||||
})
|
||||
@@ -71,6 +71,7 @@ export async function fetchPersonLife(treeId, personId, token) {
|
||||
export async function createLifeEvent(treeId, personId, payload, token) {
|
||||
return apiRequest(`/trees/${encodeURIComponent(treeId)}/persons/${encodeURIComponent(personId)}/life/events`, {
|
||||
method: 'POST',
|
||||
idempotent: true,
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
@@ -84,9 +85,10 @@ export async function updateLifeEvent(treeId, eventId, payload, token) {
|
||||
})
|
||||
}
|
||||
|
||||
export async function deleteLifeEvent(treeId, eventId, token) {
|
||||
export async function deleteLifeEvent(treeId, eventId, token, { keepalive = false } = {}) {
|
||||
return apiRequest(`/trees/${encodeURIComponent(treeId)}/life/events/${encodeURIComponent(eventId)}`, {
|
||||
method: 'DELETE',
|
||||
keepalive,
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
})
|
||||
}
|
||||
@@ -178,9 +180,10 @@ export async function updatePerson(treeId, personId, payload, token) {
|
||||
return data.person
|
||||
}
|
||||
|
||||
export async function deletePerson(treeId, personId, token) {
|
||||
export async function deletePerson(treeId, personId, token, { keepalive = false } = {}) {
|
||||
const data = await apiRequest(`/trees/${encodeURIComponent(treeId)}/persons/${encodeURIComponent(personId)}`, {
|
||||
method: 'DELETE',
|
||||
keepalive,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
@@ -213,6 +216,19 @@ export async function createParentChildLink(treeId, payload, token) {
|
||||
return data.link
|
||||
}
|
||||
|
||||
// Type, date et lieu d'un couple, depuis l'onglet Vie
|
||||
export async function updateUnion(treeId, unionId, payload, token) {
|
||||
const data = await apiRequest(`/trees/${encodeURIComponent(treeId)}/unions/${encodeURIComponent(unionId)}`, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
|
||||
return data.union
|
||||
}
|
||||
|
||||
export async function deleteUnion(treeId, unionId, token) {
|
||||
const data = await apiRequest(`/trees/${encodeURIComponent(treeId)}/unions/${encodeURIComponent(unionId)}`, {
|
||||
method: 'DELETE',
|
||||
@@ -371,6 +387,7 @@ export async function listTreeVisits(treeId, token) {
|
||||
export async function submitContributionSession(treeId, payload, token) {
|
||||
const data = await apiRequest(`/trees/${encodeURIComponent(treeId)}/contributions/sessions`, {
|
||||
method: 'POST',
|
||||
idempotent: true,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
@@ -404,9 +421,22 @@ export async function reviewContributionSession(treeId, sessionId, payload, toke
|
||||
return data
|
||||
}
|
||||
|
||||
// État d'une proposition envoyée (en attente, acceptée, refusée) : la famille retire ses fantômes une fois relue
|
||||
export async function fetchContributionStatus(treeId, sessionId, token) {
|
||||
const data = await apiRequest(`/trees/${encodeURIComponent(treeId)}/contributions/sessions/${encodeURIComponent(sessionId)}/status`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
})
|
||||
|
||||
return data?.status || null
|
||||
}
|
||||
|
||||
export async function uploadAnnotationPhoto(treeId, payload, token) {
|
||||
const data = await apiRequest(`/trees/${encodeURIComponent(treeId)}/annotation-photos`, {
|
||||
method: 'POST',
|
||||
idempotent: true,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
@@ -419,6 +449,7 @@ export async function uploadAnnotationPhoto(treeId, payload, token) {
|
||||
export async function uploadPersonMedia(treeId, personId, payload, token) {
|
||||
const data = await apiRequest(`/trees/${encodeURIComponent(treeId)}/persons/${encodeURIComponent(personId)}/media`, {
|
||||
method: 'POST',
|
||||
idempotent: true,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
@@ -440,11 +471,12 @@ export async function reorderPersonMedia(treeId, personId, orderedMediaIds, toke
|
||||
return data
|
||||
}
|
||||
|
||||
export async function deletePersonMedia(treeId, personId, mediaId, token) {
|
||||
export async function deletePersonMedia(treeId, personId, mediaId, token, { keepalive = false } = {}) {
|
||||
const data = await apiRequest(
|
||||
`/trees/${encodeURIComponent(treeId)}/persons/${encodeURIComponent(personId)}/media/${encodeURIComponent(mediaId)}`,
|
||||
{
|
||||
method: 'DELETE',
|
||||
keepalive,
|
||||
headers: {
|
||||
Authorization: `Bearer ${token}`,
|
||||
},
|
||||
|
||||
@@ -29,6 +29,10 @@ const AccountDashboard = ({
|
||||
oidcName = '',
|
||||
onOidcLogin,
|
||||
hasPassword = true,
|
||||
// Compte à mot de passe sur une instance OIDC : « Se connecter aussi avec … » relie le fournisseur, pour que le compte
|
||||
// reste accessible quand l'instance passe en connexion par le fournisseur seule. oidcLinked : déjà fait
|
||||
onLinkOidc,
|
||||
oidcLinked = false,
|
||||
pendingTreeName = '',
|
||||
onLogin,
|
||||
onRegister,
|
||||
@@ -305,7 +309,14 @@ const AccountDashboard = ({
|
||||
{t('Essayer la démo')}
|
||||
</button>
|
||||
)}
|
||||
{onLinkOidc && !oidcLinked && (
|
||||
<button type="button" className="pz-btn pz-btn--ghost pz-btn--sm account-oidc-link" onClick={onLinkOidc} disabled={loading}>
|
||||
<LogIn size={15} aria-hidden="true" />
|
||||
{t('Se connecter aussi avec {name}', { name: oidcName })}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{oidcLinked && oidcName && <p className="account-oidc-linked">{t('Connexion avec {name} reliée à ce compte.', { name: oidcName })}</p>}
|
||||
</div>
|
||||
|
||||
<div className="pz-account-foot">
|
||||
|
||||
@@ -3,6 +3,7 @@ import { X } from 'lucide-react'
|
||||
import './AccountScreens.css'
|
||||
import { t } from '../i18n/index.js'
|
||||
import { initialOf } from '../utils/initial.js'
|
||||
import PortraitThumb from './PortraitThumb.jsx'
|
||||
|
||||
const AccountPanel = ({
|
||||
visible,
|
||||
@@ -51,7 +52,7 @@ const AccountPanel = ({
|
||||
|
||||
<div className="ap-linked">
|
||||
<span className="ap-avatar" aria-hidden="true">
|
||||
{linkedPerson?.photo ? <img src={linkedPerson.photo} alt="" /> : initialOf(linkedPerson?.firstName || userDisplayName, 'C')}
|
||||
{linkedPerson?.photo ? <PortraitThumb src={linkedPerson.photo} crop={linkedPerson.avatarCrop} /> : initialOf(linkedPerson?.firstName || userDisplayName, 'C')}
|
||||
</span>
|
||||
<p className="pz-small">
|
||||
{linkedPerson
|
||||
@@ -87,7 +88,7 @@ const AccountPanel = ({
|
||||
onClick={() => onSelectPerson?.(person.id)}
|
||||
>
|
||||
<span className="ap-item-avatar" aria-hidden="true">
|
||||
{person.photo ? <img src={person.photo} alt="" /> : initialOf(person.firstName)}
|
||||
{person.photo ? <PortraitThumb src={person.photo} crop={person.avatarCrop} /> : initialOf(person.firstName)}
|
||||
</span>
|
||||
<span className="ap-item-name">{person.firstName} <em>{person.lastName || ''}</em></span>
|
||||
{isSelected && <span className="pz-tag pz-tag--accent">{t("C'est moi")}</span>}
|
||||
|
||||
@@ -70,3 +70,6 @@
|
||||
/* Arbre avec une icône choisie : l'emoji seul, sans la pastille de couleur de la lettre */
|
||||
.pz-tree-mono--emoji { background: transparent; font-size: 22px; line-height: 1; }
|
||||
.invite-tree-icon { font-size: 30px; line-height: 1; }
|
||||
|
||||
/* Connexion par le fournisseur reliée au compte (OIDC) */
|
||||
.account-oidc-linked { margin: 8px 0 0; font: 400 13px var(--pz-sans); color: var(--pz-muted); }
|
||||
@@ -120,3 +120,8 @@
|
||||
|
||||
/* Titre de section en casse normale (pas de sur-titre en capitales dans le panneau d'ajout) */
|
||||
.apn-section-title { font: 500 14px/1.3 var(--pz-sans); color: var(--pz-ink); margin: 0 0 10px; }
|
||||
|
||||
/* Doublon probable (1.5.1) : une personne du même nom est déjà dans l'arbre */
|
||||
.apn-duplicate { display: grid; gap: 6px; padding: 10px 12px; border: 1px solid var(--pz-a200); border-radius: 10px; background: var(--pz-a50); }
|
||||
.apn-duplicate-line { display: flex; align-items: center; justify-content: space-between; gap: 8px; margin: 0; font: 500 13.5px var(--pz-sans); color: var(--pz-ink); }
|
||||
.apn-duplicate-hint { margin: 0; font: 400 12.5px var(--pz-sans); color: var(--pz-muted); }
|
||||
@@ -7,6 +7,8 @@ import { t } from '../i18n/index.js'
|
||||
import { firstNameLabel } from '../utils/personName.js'
|
||||
import { SEX_CHOICES } from '../utils/personSex.js'
|
||||
import { initialOf } from '../utils/initial.js'
|
||||
import { findLikelyDuplicates } from '../utils/duplicates.js'
|
||||
import PortraitThumb from './PortraitThumb.jsx'
|
||||
|
||||
// Titre traduit d'un bloc : le passage entre <em> et </em> garde son italique
|
||||
function withEmphasis(text) {
|
||||
@@ -33,7 +35,11 @@ function withEmphasis(text) {
|
||||
* @param {Function} props.onSubmit - Handler soumission (formData)
|
||||
* @param {Function} props.onClose - Handler fermeture
|
||||
*/
|
||||
function AddPersonPanel({ visible, persons = [], loading = false, error = '', onSubmit, onClose }) {
|
||||
/**
|
||||
* @param {Object} props.prefill - ouverture depuis une fiche (1.5.1) : { nonce, firstName, lastName, relation: { type, personId, personName } }
|
||||
* @param {Function} props.onOpenPerson - « Ouvrir sa fiche » sous l'alerte de doublon
|
||||
*/
|
||||
function AddPersonPanel({ visible, persons = [], loading = false, error = '', onSubmit, onClose, prefill = null, onOpenPerson = null }) {
|
||||
const [firstName, setFirstName] = useState('')
|
||||
// Prénom inconnu : enregistré vide, affiché « Prénom inconnu » dans l'arbre et la fiche
|
||||
const [unknownFirstName, setUnknownFirstName] = useState(false)
|
||||
@@ -61,6 +67,23 @@ function AddPersonPanel({ visible, persons = [], loading = false, error = '', on
|
||||
const firstNameRef = useRef(null)
|
||||
const panelRef = useRef(null)
|
||||
|
||||
// Ouvert depuis une fiche : le lien avec la personne est déjà là, et le nom de famille proposé pour un enfant
|
||||
// ou un frère ou une sœur (modifiable). Avant, il fallait rechercher à nouveau la personne qu'on venait de quitter.
|
||||
useEffect(() => {
|
||||
if (!prefill?.nonce) return
|
||||
setFirstName(prefill.firstName || '')
|
||||
setUnknownFirstName(false)
|
||||
setLastName(prefill.lastName || '')
|
||||
setTouched({})
|
||||
if (prefill.relation?.personId != null) {
|
||||
setSelectedRelationType(prefill.relation.type)
|
||||
setRelations([{ personId: prefill.relation.personId, personName: prefill.relation.personName || '', type: prefill.relation.type }])
|
||||
}
|
||||
}, [prefill?.nonce]) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
// Doublon probable : même prénom et même nom qu'une personne de l'arbre
|
||||
const duplicates = unknownFirstName ? [] : findLikelyDuplicates(persons, firstName, lastName)
|
||||
|
||||
// Focus sur Prénom à l'ouverture
|
||||
useEffect(() => {
|
||||
if (visible) {
|
||||
@@ -251,6 +274,21 @@ function AddPersonPanel({ visible, persons = [], loading = false, error = '', on
|
||||
<p className="apn-error-text">{t('Il faut au moins un prénom.')}</p>
|
||||
)}
|
||||
{lastNameMissing && <p className="apn-error-text">{t('Il faut au moins un nom si le prénom est inconnu.')}</p>}
|
||||
{duplicates.length > 0 && (
|
||||
<div className="apn-duplicate" role="status">
|
||||
{duplicates.map((p) => (
|
||||
<p key={p.id} className="apn-duplicate-line">
|
||||
<span>{p.birthYear
|
||||
? t('{name} ({year}) est déjà dans l’arbre.', { name: `${firstNameLabel(p)} ${p.lastName || ''}`.trim(), year: p.birthYear })
|
||||
: t('{name} est déjà dans l’arbre.', { name: `${firstNameLabel(p)} ${p.lastName || ''}`.trim() })}</span>
|
||||
{onOpenPerson && (
|
||||
<button type="button" className="pz-btn pz-btn--ghost pz-btn--sm" onClick={() => onOpenPerson(p)}>{t('Ouvrir sa fiche')}</button>
|
||||
)}
|
||||
</p>
|
||||
))}
|
||||
<p className="apn-duplicate-hint">{t('Si c’est une autre personne, ajoutez-la quand même.')}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="pz-field">
|
||||
<label htmlFor="ap-birthName">{t('Nom de naissance')} <span className="apn-optional">{t('si différent')}</span></label>
|
||||
@@ -355,7 +393,7 @@ function AddPersonPanel({ visible, persons = [], loading = false, error = '', on
|
||||
<li key={p.id}>
|
||||
<button type="button" className="apn-dropdown-item" onClick={() => handleAddRelation(p)}>
|
||||
<span className="apn-avatar" aria-hidden="true">
|
||||
{p.photo ? <img src={p.photo} alt="" /> : initialOf(p.firstName)}
|
||||
{p.photo ? <PortraitThumb src={p.photo} crop={p.avatarCrop} /> : initialOf(p.firstName)}
|
||||
</span>
|
||||
<span className="apn-dropdown-name">{firstNameLabel(p)} <em>{p.lastName || ''}</em></span>
|
||||
{(p.birthYear || p.birthDate) && (
|
||||
|
||||
@@ -24,6 +24,7 @@ import { removeManager } from '../api/managersApi.js'
|
||||
import { t } from '../i18n/index.js'
|
||||
import { readGedcomFile } from '../utils/gedcomText.js'
|
||||
import { readGedcomBundle, zipErrorMessage } from '../utils/gedcomBundle.js'
|
||||
import Skeleton from './Skeleton.jsx'
|
||||
|
||||
function normalizeSlug(value) {
|
||||
return String(value || '')
|
||||
@@ -40,6 +41,10 @@ const TREE_ICONS = ['🌳', '🌿', '🌻', '🏡', '❤️', '🧡', '⭐', '
|
||||
const AdminPanel = ({
|
||||
familyTabs = true,
|
||||
onFamilyTabsChange = null,
|
||||
tabKinDepth = 1,
|
||||
onTabKinDepthChange = null,
|
||||
fullNames = false,
|
||||
onFullNamesChange = null,
|
||||
visible,
|
||||
treeId,
|
||||
authToken,
|
||||
@@ -442,7 +447,7 @@ const AdminPanel = ({
|
||||
|
||||
<div className="ts-content">
|
||||
{loading ? (
|
||||
<p className="pz-small ts-loading">{t('Chargement…')}</p>
|
||||
<Skeleton variant="lines" count={4} />
|
||||
) : (
|
||||
<>
|
||||
{errorMessage && <div className="pz-error" role="alert">{errorMessage}</div>}
|
||||
@@ -532,6 +537,7 @@ const AdminPanel = ({
|
||||
|
||||
<fieldset className="ts-policy">
|
||||
<legend className="pz-eyebrow">{t('Affichage')}</legend>
|
||||
<p className="pz-small">{t('Réglages de ce navigateur.')}</p>
|
||||
<label className={`ts-choice ${familyTabs ? 'is-active' : ''}`}>
|
||||
<input
|
||||
type="checkbox"
|
||||
@@ -540,8 +546,31 @@ const AdminPanel = ({
|
||||
onChange={(event) => onFamilyTabsChange?.(event.target.checked)}
|
||||
/>
|
||||
<span className="ts-choice-text">
|
||||
<strong>{t('Les grandes familles par alliance dans des onglets')}</strong>
|
||||
<small>{t("Une belle-famille plus large qu'un écran s'ouvre dans son propre onglet au lieu d'être dessinée dans l'arbre. Réglage de ce navigateur.")}</small>
|
||||
<strong>{t('Séparer les belles-familles en onglets')}</strong>
|
||||
<small>{t("Quand la famille d'un conjoint est trop large pour l'écran, elle s'ouvre dans un onglet en haut de l'arbre.")}</small>
|
||||
</span>
|
||||
</label>
|
||||
<div className="pz-field">
|
||||
<span className="pz-label" id="settingsTabKinLabel">{t("Dans un onglet, montrer aussi les proches de l'autre côté")}</span>
|
||||
<div className="ts-icons" role="radiogroup" aria-labelledby="settingsTabKinLabel">
|
||||
{[[0, t('Ma ligne seulement')], [1, t('1 lien')], [2, t('2 liens')], [3, t('3 liens')]].map(([d, text]) => (
|
||||
<button key={d} type="button" role="radio" aria-checked={tabKinDepth === d} disabled={!familyTabs} className="ts-icon ts-icon--letter" onClick={() => onTabKinDepthChange?.(d)}>
|
||||
{text}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
<p className="pz-hint">{t('Un lien : un parent, un enfant ou un conjoint. Ils apparaissent en plus clair ; votre propre ligne reste toujours visible.')}</p>
|
||||
</div>
|
||||
<label className={`ts-choice ${fullNames ? 'is-active' : ''}`}>
|
||||
<input
|
||||
type="checkbox"
|
||||
name="fullNames"
|
||||
checked={fullNames}
|
||||
onChange={(event) => onFullNamesChange?.(event.target.checked)}
|
||||
/>
|
||||
<span className="ts-choice-text">
|
||||
<strong>{t('Afficher le nom de famille')}</strong>
|
||||
<small>{t("Sous chaque prénom. Le nom de naissance s'il est connu.")}</small>
|
||||
</span>
|
||||
</label>
|
||||
</fieldset>
|
||||
|
||||
@@ -7,7 +7,10 @@ import './SettingsPanels.css'
|
||||
import PzBusy from './PzBusy.jsx'
|
||||
import { HELP_URL } from '../utils/siteLinks.js'
|
||||
import { t, dateLocale } from '../i18n/index.js'
|
||||
import { buildInviteText, isChristmasSeason } from '../utils/inviteText.js'
|
||||
import { toOpaqueTreeId, trackAppEvent } from '../utils/analytics.js'
|
||||
import { sexLabel } from '../utils/personSex.js'
|
||||
import Skeleton from './Skeleton.jsx'
|
||||
|
||||
// ─── helpers ────────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -216,21 +219,6 @@ function formatSessionDate(value) {
|
||||
})
|
||||
}
|
||||
|
||||
// Message d'invitation prêt à envoyer par mail, SMS ou WhatsApp
|
||||
function buildInviteText(url, password) {
|
||||
return [
|
||||
t('Bonjour à tous,'),
|
||||
'',
|
||||
t("Je rassemble l'histoire de notre famille dans un arbre en ligne, et j'aimerais que vous m'aidiez à le compléter."),
|
||||
'',
|
||||
t("L'arbre est ici {url}", { url }),
|
||||
t("Le mot de passe pour l'ouvrir est {password}", { password }),
|
||||
'',
|
||||
t("En bas de l'écran, vous pouvez ajouter une photo, un souvenir ou une personne qui manque."),
|
||||
t("Le mode d'emploi, si besoin {url}", { url: HELP_URL }),
|
||||
].join('\n')
|
||||
}
|
||||
|
||||
// ─── component ──────────────────────────────────────────────────────────────
|
||||
|
||||
const ContributionPanel = ({
|
||||
@@ -240,6 +228,8 @@ const ContributionPanel = ({
|
||||
loading,
|
||||
errorMessage,
|
||||
inviteShareUrl,
|
||||
// Onglet de famille ouvert : le lien ouvre l'arbre sur cette famille
|
||||
inviteFamilyName = '',
|
||||
inviteKnownPasswords,
|
||||
inviteSaving,
|
||||
inviteError,
|
||||
@@ -251,6 +241,7 @@ const ContributionPanel = ({
|
||||
onRotatePasswords,
|
||||
onRememberPassword,
|
||||
onReviewSession,
|
||||
seasonalInvite = false,
|
||||
}) => {
|
||||
const [decisionMap, setDecisionMap] = useState({})
|
||||
const [collapsedSessions, setCollapsedSessions] = useState(new Set())
|
||||
@@ -352,14 +343,23 @@ const ContributionPanel = ({
|
||||
}, [inviteKnownPasswords?.share, visible])
|
||||
|
||||
const knownShare = inviteKnownPasswords?.share || ''
|
||||
const defaultInviteText = knownShare && inviteShareUrl ? buildInviteText(inviteShareUrl, knownShare) : ''
|
||||
const defaultInviteText = knownShare && inviteShareUrl ? buildInviteText(inviteShareUrl, knownShare, { seasonal: seasonalInvite }) : ''
|
||||
const [inviteText, setInviteText] = useState('')
|
||||
useEffect(() => { setInviteText(defaultInviteText) }, [defaultInviteText])
|
||||
|
||||
const handleCopy = async (value, label) => {
|
||||
// what : link, password ou message. Ce qui a été copié, jamais le texte lui-même
|
||||
const handleCopy = async (value, label, what) => {
|
||||
const text = String(value || '').trim()
|
||||
if (!text) return
|
||||
try { await navigator.clipboard.writeText(text); setCopyFeedback(label) }
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
setCopyFeedback(label)
|
||||
trackAppEvent('share_copied', {
|
||||
what,
|
||||
...(what === 'message' ? { seasonal: Boolean(seasonalInvite && isChristmasSeason()) } : {}),
|
||||
tree_id: toOpaqueTreeId(treeId),
|
||||
})
|
||||
}
|
||||
catch { setCopyFeedback(t('Copie indisponible')) }
|
||||
}
|
||||
|
||||
@@ -403,12 +403,12 @@ const ContributionPanel = ({
|
||||
{/* ── Section invitation ── */}
|
||||
<div className="contrib-invite">
|
||||
<div className="contrib-invite-top">
|
||||
<strong className="contrib-invite-title">{t('Le lien à envoyer à la famille')}</strong>
|
||||
<strong className="contrib-invite-title">{inviteFamilyName ? t('Le lien à envoyer à la famille {name}', { name: inviteFamilyName }) : t('Le lien à envoyer à la famille')}</strong>
|
||||
{copyFeedback && <span className="contrib-copy-feedback">{copyFeedback}</span>}
|
||||
</div>
|
||||
<div className="contrib-invite-link">
|
||||
<code className="contrib-link-url">{inviteShareUrl || t('Lien indisponible')}</code>
|
||||
<button type="button" className="pz-btn pz-btn--primary pz-btn--sm" disabled={!inviteShareUrl} onClick={() => handleCopy(inviteShareUrl, t('Lien copié'))}><Copy size={14} strokeWidth={2} />{t('Copier')}</button>
|
||||
<button type="button" className="pz-btn pz-btn--primary pz-btn--sm" disabled={!inviteShareUrl} onClick={() => handleCopy(inviteShareUrl, t('Lien copié'), 'link')}><Copy size={14} strokeWidth={2} />{t('Copier')}</button>
|
||||
</div>
|
||||
<div className="contrib-invite-passwords">
|
||||
<div className="contrib-role-row">
|
||||
@@ -422,7 +422,7 @@ const ContributionPanel = ({
|
||||
) : (
|
||||
<>
|
||||
<button type="button" className={`contrib-pass-reveal${knownShare && !showPassword ? ' contrib-pass-reveal--blurred' : ''}`} onClick={() => setShowPassword((v) => !v)} disabled={!knownShare} title={showPassword ? t('Cliquer pour masquer') : t('Cliquer pour révéler')}>{knownShare || t('Pas encore enregistré')}</button>
|
||||
{knownShare && <button type="button" className="contrib-pill-btn contrib-pill-btn--edit" onClick={() => handleCopy(knownShare, t('Mot de passe copié'))}>{t('Copier')}</button>}
|
||||
{knownShare && <button type="button" className="contrib-pill-btn contrib-pill-btn--edit" onClick={() => handleCopy(knownShare, t('Mot de passe copié'), 'password')}>{t('Copier')}</button>}
|
||||
{!knownShare && <button type="button" className="contrib-pill-btn contrib-pill-btn--edit" disabled={inviteSaving} onClick={() => setPasswordMode('remember')}>{t("Saisir l'actuel")}</button>}
|
||||
<button type="button" className="contrib-pill-btn contrib-pill-btn--edit" disabled={inviteSaving} onClick={() => setPasswordMode('change')}>{t('Changer')}</button>
|
||||
</>
|
||||
@@ -437,7 +437,7 @@ const ContributionPanel = ({
|
||||
{defaultInviteText && (
|
||||
<div className="contrib-invite-message">
|
||||
<div className="contrib-invite-message-row">
|
||||
<button type="button" className="contrib-pill-btn contrib-pill-btn--edit" onClick={() => handleCopy(inviteText, t('Message copié'))}><Copy size={14} strokeWidth={2} />{t("Copier le message d'invitation")}</button>
|
||||
<button type="button" className="contrib-pill-btn contrib-pill-btn--edit" onClick={() => handleCopy(inviteText, t('Message copié'), 'message')}><Copy size={14} strokeWidth={2} />{t("Copier le message d'invitation")}</button>
|
||||
<button type="button" className="contrib-link-btn" aria-expanded={showInviteMessage} aria-controls="contrib-invite-text" onClick={() => setShowInviteMessage((v) => !v)}>
|
||||
{showInviteMessage ? t('Masquer le message') : t('Voir ou modifier le message')}
|
||||
</button>
|
||||
@@ -469,7 +469,7 @@ const ContributionPanel = ({
|
||||
{errorMessage && <div className="contrib-error">{errorMessage}</div>}
|
||||
|
||||
{loading ? (
|
||||
<div className="contrib-empty">{t('Chargement…')}</div>
|
||||
<Skeleton variant="rows" count={3} />
|
||||
) : sessions.length === 0 ? (
|
||||
<div className="contrib-empty">{t("Rien à relire pour l'instant. Les propositions de la famille apparaîtront ici.")}</div>
|
||||
) : (
|
||||
@@ -558,16 +558,21 @@ const ContributionPanel = ({
|
||||
key={change.id}
|
||||
className={`contrib-change-card${isApproved ? ' contrib-change-card--approved' : ''}${isRejected ? ' contrib-change-card--rejected' : ''}`}
|
||||
>
|
||||
<div className="contrib-change-card-head">
|
||||
{/* Étiquette posée sur le bord haut de la carte. Une fiche changée depuis la proposition dit « À vérifier »
|
||||
à la place de « Modification » ; toute autre action garde son mot (une suppression reste lisible) */}
|
||||
{change.conflictState === 'needs_review' ? (
|
||||
<span className="contrib-action-badge contrib-action-badge--conflict" title={t('La fiche a changé depuis cette proposition')}>
|
||||
{change.action === 'update' ? t('À vérifier') : t('{action}, à vérifier', { action: formatAction(change.action) })}
|
||||
</span>
|
||||
) : (
|
||||
<span className={`contrib-action-badge contrib-action-badge--${change.action}`}>
|
||||
{formatAction(change.action)}
|
||||
</span>
|
||||
)}
|
||||
<div className="contrib-change-card-head">
|
||||
<span className="contrib-change-entity-name">
|
||||
{personName || formatEntityType(change.entityType)}
|
||||
</span>
|
||||
{change.conflictState === 'needs_review' && (
|
||||
<span className="contrib-conflict-badge">{t('À vérifier')}</span>
|
||||
)}
|
||||
<div className="contrib-card-decisions">
|
||||
<button
|
||||
type="button"
|
||||
|
||||
@@ -36,7 +36,7 @@ export default function DateField({ id, value, onChange, placeholder, className
|
||||
else setText(dateToInputText(parsed))
|
||||
}}
|
||||
/>
|
||||
{touched && invalid && <span className="pz-date-hint" role="status">{t('Une année (1950) ou une date (12/03/1950)')}</span>}
|
||||
{touched && invalid && <span className="pz-date-hint" role="status">{t('Une année (1950) ou une date ({exemple})', { exemple: dateToInputText('1950-03-12') })}</span>}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -12,7 +12,8 @@ import { t } from '../i18n/index.js'
|
||||
* - Enregistrer brouillon et quitter
|
||||
* - Abandonner les modifications
|
||||
*/
|
||||
function EditConfirmModal({ visible, onContinue, onSaveAndQuit, onDiscard }) {
|
||||
// demo : la démo ne garde rien sur l'appareil, ses modifications vivent le temps de la page
|
||||
function EditConfirmModal({ visible, onContinue, onSaveAndQuit, onDiscard, demo = false }) {
|
||||
const continueRef = useRef(null)
|
||||
|
||||
// Focus sur "Continuer" à l'ouverture + trap ESC
|
||||
@@ -47,7 +48,9 @@ function EditConfirmModal({ visible, onContinue, onSaveAndQuit, onDiscard }) {
|
||||
<div className="pz-modal-head">
|
||||
<p className="pz-eyebrow">{t('Modifications en cours')}</p>
|
||||
<h2 id="edit-confirm-title" className="pz-title">{titleBefore}<em>{t("l'édition")}</em>{titleAfter}</h2>
|
||||
<p className="pz-sub">{t('Vos dernières modifications ne sont pas encore enregistrées. Elles restent sur cet appareil tant que vous ne les abandonnez pas.')}</p>
|
||||
<p className="pz-sub">{demo
|
||||
? t('Vos dernières modifications restent dans la démo tant que cette page est ouverte, puis elles disparaissent.')
|
||||
: t('Vos dernières modifications ne sont pas encore enregistrées. Elles restent sur cet appareil tant que vous ne les abandonnez pas.')}</p>
|
||||
</div>
|
||||
|
||||
<div className="pz-modal-actions pz-modal-actions--split">
|
||||
|
||||
@@ -58,6 +58,10 @@
|
||||
.edit-mode-toast--contrib .edit-mode-toast-short { display: inline; }
|
||||
}
|
||||
|
||||
/* « Terminé » dans la barre du bas fait déjà sortir de l'édition : pas de seconde croix dans la bulle (Patch, 27/10) */
|
||||
body:has(.nav-annot-exit) .edit-mode-toast-close { display: none; }
|
||||
body:has(.nav-annot-exit) .edit-mode-toast:not(.edit-mode-toast--with-submit) { padding-right: 16px; }
|
||||
|
||||
/* Téléphone : le texte de l'éditeur se coupait en « Vous modifi… » à côté du bouton, qui suffit à lui seul.
|
||||
L'invité garde son texte court, qui tient sur une ligne. */
|
||||
@media (max-width: 480px) {
|
||||
|
||||
Loaded 100 of 228 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user